1 ;;; -*- mode: scheme; coding: utf-8; -*-
3 ;;;; Copyright (C) 1995,1996,1997,1998,1999,2000,2001,2002,2003,2004,2005,2006,2007,2008,2009,2010
4 ;;;; Free Software Foundation, Inc.
6 ;;;; This library is free software; you can redistribute it and/or
7 ;;;; modify it under the terms of the GNU Lesser General Public
8 ;;;; License as published by the Free Software Foundation; either
9 ;;;; version 3 of the License, or (at your option) any later version.
11 ;;;; This library is distributed in the hope that it will be useful,
12 ;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
13 ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 ;;;; Lesser General Public License for more details.
16 ;;;; You should have received a copy of the GNU Lesser General Public
17 ;;;; License along with this library; if not, write to the Free Software
18 ;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
25 ;;; This file is the first thing loaded into Guile. It adds many mundane
26 ;;; definitions and a few that are interesting.
28 ;;; The module system (hence the hierarchical namespace) are defined in this
36 ;; Before compiling, make sure any symbols are resolved in the (guile)
37 ;; module, the primary location of those symbols, rather than in
38 ;; (guile-user), the default module that we compile in.
41 (set-current-module (resolve-module '(guile))))
48 ;; Define delimited continuation operators, and implement catch and throw in
51 (define make-prompt-tag
52 (lambda* (#:optional (stem "prompt"))
55 (define default-prompt-tag
56 ;; not sure if we should expose this to the user as a fluid
57 (let ((%default-prompt-tag (make-prompt-tag)))
59 %default-prompt-tag)))
61 (define (call-with-prompt tag thunk handler)
62 (@prompt tag (thunk) handler))
63 (define (abort-to-prompt tag . args)
67 ;; Define catch and with-throw-handler, using some common helper routines and a
68 ;; shared fluid. Hide the helpers in a lexical contour.
70 (define with-throw-handler #f)
72 ;; Ideally we'd like to be able to give these default values for all threads,
73 ;; even threads not created by Guile; but alack, that does not currently seem
74 ;; possible. So wrap the getters in thunks.
75 (define %running-exception-handlers (make-fluid))
76 (define %exception-handler (make-fluid))
78 (define (running-exception-handlers)
79 (or (fluid-ref %running-exception-handlers)
81 (fluid-set! %running-exception-handlers '())
83 (define (exception-handler)
84 (or (fluid-ref %exception-handler)
86 (fluid-set! %exception-handler default-exception-handler)
87 default-exception-handler)))
89 (define (default-exception-handler k . args)
93 ((not (pair? args)) 0)
94 ((integer? (car args)) (car args))
98 (format (current-error-port) "guile: uncaught throw to ~a: ~a\n" k args)
101 (define (default-throw-handler prompt-tag catch-k)
102 (let ((prev (exception-handler)))
103 (lambda (thrown-k . args)
104 (if (or (eq? thrown-k catch-k) (eqv? catch-k #t))
105 (apply abort-to-prompt prompt-tag thrown-k args)
106 (apply prev thrown-k args)))))
108 (define (custom-throw-handler prompt-tag catch-k pre)
109 (let ((prev (exception-handler)))
110 (lambda (thrown-k . args)
111 (if (or (eq? thrown-k catch-k) (eqv? catch-k #t))
112 (let ((running (running-exception-handlers)))
113 (with-fluids ((%running-exception-handlers (cons pre running)))
114 (if (not (memq pre running))
115 (apply pre thrown-k args))
118 (apply abort-to-prompt prompt-tag thrown-k args)
119 (apply prev thrown-k args))))
120 (apply prev thrown-k args)))))
123 (lambda* (k thunk handler #:optional pre-unwind-handler)
124 "Invoke @var{thunk} in the dynamic context of @var{handler} for
125 exceptions matching @var{key}. If thunk throws to the symbol
126 @var{key}, then @var{handler} is invoked this way:
128 (handler key args ...)
131 @var{key} is a symbol or @code{#t}.
133 @var{thunk} takes no arguments. If @var{thunk} returns
134 normally, that is the return value of @code{catch}.
136 Handler is invoked outside the scope of its own @code{catch}.
137 If @var{handler} again throws to the same key, a new handler
138 from further up the call chain is invoked.
140 If the key is @code{#t}, then a throw to @emph{any} symbol will
141 match this call to @code{catch}.
143 If a @var{pre-unwind-handler} is given and @var{thunk} throws
144 an exception that matches @var{key}, Guile calls the
145 @var{pre-unwind-handler} before unwinding the dynamic state and
146 invoking the main @var{handler}. @var{pre-unwind-handler} should
147 be a procedure with the same signature as @var{handler}, that
148 is @code{(lambda (key . args))}. It is typically used to save
149 the stack at the point where the exception occurred, but can also
150 query other parts of the dynamic state at that point, such as
153 A @var{pre-unwind-handler} can exit either normally or non-locally.
154 If it exits normally, Guile unwinds the stack and dynamic context
155 and then calls the normal (third argument) handler. If it exits
156 non-locally, that exit determines the continuation."
157 (if (not (or (symbol? k) (eqv? k #t)))
158 (scm-error "catch" 'wrong-type-arg
159 "Wrong type argument in position ~a: ~a"
160 (list 1 k) (list k)))
161 (let ((tag (make-prompt-tag "catch")))
167 (if pre-unwind-handler
168 (custom-throw-handler tag k pre-unwind-handler)
169 (default-throw-handler tag k))))
171 (lambda (cont k . args)
172 (apply handler k args))))))
174 (set! with-throw-handler
175 (lambda (k thunk pre-unwind-handler)
176 "Add @var{handler} to the dynamic context as a throw handler
177 for key @var{key}, then invoke @var{thunk}."
178 (if (not (or (symbol? k) (eqv? k #t)))
179 (scm-error "with-throw-handler" 'wrong-type-arg
180 "Wrong type argument in position ~a: ~a"
181 (list 1 k) (list k)))
182 (with-fluids ((%exception-handler
183 (custom-throw-handler #f k pre-unwind-handler)))
188 "Invoke the catch form matching @var{key}, passing @var{args} to the
191 @var{key} is a symbol. It will match catches of the same symbol or of @code{#t}.
193 If there is no handler at all, Guile prints an error and then exits."
194 (if (not (symbol? key))
195 ((exception-handler) 'wrong-type-arg "throw"
196 "Wrong type argument in position ~a: ~a" (list 1 key) (list key))
197 (apply (exception-handler) key args)))))
202 ;;; {R4RS compliance}
205 (primitive-load-path "ice-9/r4rs")
209 ;;; {Simple Debugging Tools}
212 ;; peek takes any number of arguments, writes them to the
213 ;; current ouput port, and returns the last argument.
214 ;; It is handy to wrap around an expression to look at
215 ;; a value each time is evaluated, e.g.:
217 ;; (+ 10 (troublesome-fn))
218 ;; => (+ 10 (pk 'troublesome-fn-returned (troublesome-fn)))
221 (define (peek . stuff)
226 (car (last-pair stuff)))
231 (define (warn . stuff)
232 (with-output-to-port (current-error-port)
235 (display ";;; WARNING ")
238 (car (last-pair stuff)))))
245 (define (provide sym)
246 (if (not (memq sym *features*))
247 (set! *features* (cons sym *features*))))
249 ;; Return #t iff FEATURE is available to this Guile interpreter. In SLIB,
250 ;; provided? also checks to see if the module is available. We should do that
253 (define (provided? feature)
254 (and (memq feature *features*) #t))
261 (define (make-struct/no-tail vtable . args)
262 (apply make-struct vtable 0 args))
266 ;;; {and-map and or-map}
268 ;;; (and-map fn lst) is like (and (fn (car lst)) (fn (cadr lst)) (fn...) ...)
269 ;;; (or-map fn lst) is like (or (fn (car lst)) (fn (cadr lst)) (fn...) ...)
274 ;; Apply f to successive elements of l until exhaustion or f returns #f.
275 ;; If returning early, return #f. Otherwise, return the last value returned
276 ;; by f. If f has never been called because l is empty, return #t.
278 (define (and-map f lst)
279 (let loop ((result #t)
284 (loop (f (car l)) (cdr l))))))
288 ;; Apply f to successive elements of l until exhaustion or while f returns #f.
289 ;; If returning early, return the return value of f.
291 (define (or-map f lst)
292 (let loop ((result #f)
296 (loop (f (car l)) (cdr l))))))
300 ;; let format alias simple-format until the more complete version is loaded
302 (define format simple-format)
304 ;; this is scheme wrapping the C code so the final pred call is a tail call,
307 (lambda* (char_pred s #:optional (start 0) (end (string-length s)))
308 (if (and (procedure? char_pred)
310 (<= end (string-length s))) ;; let c-code handle range error
311 (or (string-any-c-code char_pred s start (1- end))
312 (char_pred (string-ref s (1- end))))
313 (string-any-c-code char_pred s start end))))
315 ;; this is scheme wrapping the C code so the final pred call is a tail call,
318 (lambda* (char_pred s #:optional (start 0) (end (string-length s)))
319 (if (and (procedure? char_pred)
321 (<= end (string-length s))) ;; let c-code handle range error
322 (and (string-every-c-code char_pred s start (1- end))
323 (char_pred (string-ref s (1- end))))
324 (string-every-c-code char_pred s start end))))
326 ;; A variant of string-fill! that we keep for compatability
328 (define (substring-fill! str start end fill)
329 (string-fill! str fill start end))
333 ;; Define a minimal stub of the module API for psyntax, before modules
335 (define (module-name x)
337 (define (module-define! module sym val)
338 (let ((v (hashq-ref (%get-pre-modules-obarray) sym)))
340 (variable-set! v val)
341 (hashq-set! (%get-pre-modules-obarray) sym
342 (make-variable val)))))
343 (define (module-ref module sym)
344 (let ((v (module-variable module sym)))
345 (if v (variable-ref v) (error "badness!" (pk module) (pk sym)))))
346 (define (resolve-module . args)
349 ;; API provided by psyntax
350 (define syntax-violation #f)
351 (define datum->syntax #f)
352 (define syntax->datum #f)
353 (define syntax-source #f)
354 (define identifier? #f)
355 (define generate-temporaries #f)
356 (define bound-identifier=? #f)
357 (define free-identifier=? #f)
359 ;; $sc-dispatch is an implementation detail of psyntax. It is used by
360 ;; expanded macros, to dispatch an input against a set of patterns.
361 (define $sc-dispatch #f)
364 (primitive-load-path "ice-9/psyntax-pp")
365 ;; The binding for `macroexpand' has now been overridden, making psyntax the
372 ((_ x y ...) (if x (and y ...) #f))))
378 ((_ x y ...) (let ((t x)) (if t t (or y ...))))))
380 ;; The "maybe-more" bits are something of a hack, so that we can support
381 ;; SRFI-61. Rewrites into a standalone syntax-case macro would be
384 (syntax-rules (=> else)
385 ((_ "maybe-more" test consequent)
386 (if test consequent))
388 ((_ "maybe-more" test consequent clause ...)
389 (if test consequent (cond clause ...)))
391 ((_ (else else1 else2 ...))
392 (begin else1 else2 ...))
394 ((_ (test => receiver) more-clause ...)
396 (cond "maybe-more" t (receiver t) more-clause ...)))
398 ((_ (generator guard => receiver) more-clause ...)
399 (call-with-values (lambda () generator)
402 (apply guard t) (apply receiver t) more-clause ...))))
404 ((_ (test => receiver ...) more-clause ...)
405 (syntax-violation 'cond "wrong number of receiver expressions"
406 '(test => receiver ...)))
407 ((_ (generator guard => receiver ...) more-clause ...)
408 (syntax-violation 'cond "wrong number of receiver expressions"
409 '(generator guard => receiver ...)))
411 ((_ (test) more-clause ...)
413 (cond "maybe-more" t t more-clause ...)))
415 ((_ (test body1 body2 ...) more-clause ...)
417 test (begin body1 body2 ...) more-clause ...))))
423 (let ((atom-key (key ...)))
424 (case atom-key clauses ...)))
426 (else result1 result2 ...))
427 (begin result1 result2 ...))
429 ((atoms ...) result1 result2 ...))
430 (if (memv key '(atoms ...))
431 (begin result1 result2 ...)))
433 ((atoms ...) result1 result2 ...)
435 (if (memv key '(atoms ...))
436 (begin result1 result2 ...)
437 (case key clause clauses ...)))))
441 ((do ((var init step ...) ...)
454 (loop (do "step" var step ...)
464 ((_ exp) (make-promise (lambda () exp)))))
466 (include-from-path "ice-9/quasisyntax")
468 (define-syntax current-source-location
472 (with-syntax ((s (datum->syntax x (syntax-source x))))
481 (define-syntax define-macro
485 ((_ (macro . args) doc body1 body ...)
486 (string? (syntax->datum #'doc))
487 #'(define-macro macro doc (lambda args body1 body ...)))
488 ((_ (macro . args) body ...)
489 #'(define-macro macro #f (lambda args body ...)))
490 ((_ macro doc transformer)
491 (or (string? (syntax->datum #'doc))
492 (not (syntax->datum #'doc)))
493 #'(define-syntax macro
496 #((macro-type . defmacro)
497 (defmacro-args args))
500 (let ((v (syntax->datum #'args)))
501 (datum->syntax y (apply transformer v)))))))))))
503 (define-syntax defmacro
505 "Define a defmacro, with the old lispy defun syntax."
507 ((_ macro args doc body1 body ...)
508 (string? (syntax->datum #'doc))
509 #'(define-macro macro doc (lambda args body1 body ...)))
510 ((_ macro args body ...)
511 #'(define-macro macro #f (lambda args body ...))))))
520 (define-syntax begin-deprecated
524 (if (include-deprecated-features)
525 #'(begin form form* ...)
530 ;;; {Trivial Functions}
533 (define (identity x) x)
534 (define (and=> value procedure) (and value (procedure value)))
535 (define call/cc call-with-current-continuation)
537 (define-syntax false-if-exception
542 (lambda (k . args) #f)))))
546 ;;; {General Properties}
549 ;; Properties are a lispy way to associate random info with random objects.
550 ;; Traditionally properties are implemented as an alist or a plist actually
551 ;; pertaining to the object in question.
553 ;; These "object properties" have the advantage that they can be associated with
554 ;; any object, even if the object has no plist. Object properties are good when
555 ;; you are extending pre-existing objects in unexpected ways. They also present
556 ;; a pleasing, uniform procedure-with-setter interface. But if you have a data
557 ;; type that always has properties, it's often still best to store those
558 ;; properties within the object itself.
560 (define (make-object-property)
561 (let ((prop (primitive-make-property #f)))
562 (make-procedure-with-setter
563 (lambda (obj) (primitive-property-ref prop obj))
564 (lambda (obj val) (primitive-property-set! prop obj val)))))
568 ;;; {Symbol Properties}
571 ;;; Symbol properties are something you see in old Lisp code. In most current
572 ;;; Guile code, symbols are not used as a data structure -- they are used as
573 ;;; keys into other data structures.
575 (define (symbol-property sym prop)
576 (let ((pair (assoc prop (symbol-pref sym))))
577 (and pair (cdr pair))))
579 (define (set-symbol-property! sym prop val)
580 (let ((pair (assoc prop (symbol-pref sym))))
583 (symbol-pset! sym (acons prop val (symbol-pref sym))))))
585 (define (symbol-property-remove! sym prop)
586 (let ((pair (assoc prop (symbol-pref sym))))
588 (symbol-pset! sym (delq! pair (symbol-pref sym))))))
595 (define (array-shape a)
596 (map (lambda (ind) (if (number? ind) (list 0 (+ -1 ind)) ind))
597 (array-dimensions a)))
604 ;;; It's much better if you can use lambda* / define*, of course.
606 (define (kw-arg-ref args kw)
607 (let ((rem (member kw args)))
608 (and rem (pair? (cdr rem)) (cadr rem))))
615 (define (struct-layout s)
616 (struct-ref (struct-vtable s) vtable-index-layout))
623 ;; Printing records: by default, records are printed as
625 ;; #<type-name field1: val1 field2: val2 ...>
627 ;; You can change that by giving a custom printing function to
628 ;; MAKE-RECORD-TYPE (after the list of field symbols). This function
629 ;; will be called like
631 ;; (<printer> object port)
633 ;; It should print OBJECT to PORT.
635 (define (inherit-print-state old-port new-port)
636 (if (get-print-state old-port)
637 (port-with-print-state new-port (get-print-state old-port))
640 ;; 0: type-name, 1: fields, 2: constructor
641 (define record-type-vtable
642 ;; FIXME: This should just call make-vtable, not make-vtable-vtable; but for
643 ;; that we need to expose the bare vtable-vtable to Scheme.
644 (make-vtable-vtable "prprpw" 0
646 (cond ((eq? s record-type-vtable)
647 (display "#<record-type-vtable>" p))
649 (display "#<record-type " p)
650 (display (record-type-name s) p)
653 (define (record-type? obj)
654 (and (struct? obj) (eq? record-type-vtable (struct-vtable obj))))
656 (define* (make-record-type type-name fields #:optional printer)
657 ;; Pre-generate constructors for nfields < 20.
658 (define-syntax make-constructor
660 (define *max-static-argument-count* 20)
661 (define (make-formals n)
667 (string (integer->char (+ (char->integer #\a) i)))))
671 ((_ rtd exp) (not (identifier? #'exp))
673 (make-constructor rtd n)))
677 (if (< n *max-static-argument-count*)
678 (cons (with-syntax (((formal ...) (make-formals n))
682 (make-struct rtd 0 formal ...))))
687 (if (= (length args) nfields)
688 (apply make-struct rtd 0 args)
689 (scm-error 'wrong-number-of-args
690 (format #f "make-~a" type-name)
691 "Wrong number of arguments" '() #f)))))))))
693 (define (default-record-printer s p)
695 (display (record-type-name (record-type-descriptor s)) p)
696 (let loop ((fields (record-type-fields (record-type-descriptor s)))
699 ((not (null? fields))
701 (display (car fields) p)
703 (display (struct-ref s off) p)
704 (loop (cdr fields) (+ 1 off)))))
707 (let ((rtd (make-struct record-type-vtable 0
710 (map (lambda (f) "pw") fields)))
711 (or printer default-record-printer)
713 (copy-tree fields))))
714 (struct-set! rtd (+ vtable-offset-user 2)
715 (make-constructor rtd (length fields)))
716 ;; Temporary solution: Associate a name to the record type descriptor
717 ;; so that the object system can create a wrapper class for it.
718 (set-struct-vtable-name! rtd (if (symbol? type-name)
720 (string->symbol type-name)))
723 (define (record-type-name obj)
724 (if (record-type? obj)
725 (struct-ref obj vtable-offset-user)
726 (error 'not-a-record-type obj)))
728 (define (record-type-fields obj)
729 (if (record-type? obj)
730 (struct-ref obj (+ 1 vtable-offset-user))
731 (error 'not-a-record-type obj)))
733 (define* (record-constructor rtd #:optional field-names)
734 (if (not field-names)
735 (struct-ref rtd (+ 2 vtable-offset-user))
737 `(lambda ,field-names
738 (make-struct ',rtd 0 ,@(map (lambda (f)
739 (if (memq f field-names)
742 (record-type-fields rtd)))))))
744 (define (record-predicate rtd)
745 (lambda (obj) (and (struct? obj) (eq? rtd (struct-vtable obj)))))
747 (define (%record-type-error rtd obj) ;; private helper
748 (or (eq? rtd (record-type-descriptor obj))
749 (scm-error 'wrong-type-arg "%record-type-check"
750 "Wrong type record (want `~S'): ~S"
751 (list (record-type-name rtd) obj)
754 (define (record-accessor rtd field-name)
755 (let ((pos (list-index (record-type-fields rtd) field-name)))
757 (error 'no-such-field field-name))
759 (if (eq? (struct-vtable obj) rtd)
761 (%record-type-error rtd obj)))))
763 (define (record-modifier rtd field-name)
764 (let ((pos (list-index (record-type-fields rtd) field-name)))
766 (error 'no-such-field field-name))
768 (if (eq? (struct-vtable obj) rtd)
769 (struct-set! obj pos val)
770 (%record-type-error rtd obj)))))
772 (define (record? obj)
773 (and (struct? obj) (record-type? (struct-vtable obj))))
775 (define (record-type-descriptor obj)
778 (error 'not-a-record obj)))
787 (define (->bool x) (not (not x)))
794 (define (symbol-append . args)
795 (string->symbol (apply string-append (map symbol->string args))))
797 (define (list->symbol . args)
798 (string->symbol (apply list->string args)))
800 (define (symbol . args)
801 (string->symbol (apply string args)))
808 (define (list-index l k)
814 (loop (+ n 1) (cdr l))))))
818 (if (provided? 'posix)
819 (primitive-load-path "ice-9/posix"))
821 (if (provided? 'socket)
822 (primitive-load-path "ice-9/networking"))
824 ;; For reference, Emacs file-exists-p uses stat in this same way.
826 (if (provided? 'posix)
828 (->bool (stat str #f)))
830 (let ((port (catch 'system-error (lambda () (open-file str OPEN_READ))
832 (if port (begin (close-port port) #t)
835 (define file-is-directory?
836 (if (provided? 'posix)
838 (eq? (stat:type (stat str)) 'directory))
840 (let ((port (catch 'system-error
841 (lambda () (open-file (string-append str "/.")
844 (if port (begin (close-port port) #t)
847 (define (system-error-errno args)
848 (if (eq? (car args) 'system-error)
849 (car (list-ref args 4))
860 (scm-error 'misc-error #f "?" #f #f))
862 (let ((msg (string-join (cons "~A" (make-list (length args) "~S")))))
863 (scm-error 'misc-error #f msg (cons message args) #f)))))
867 ;;; {Time Structures}
870 (define (tm:sec obj) (vector-ref obj 0))
871 (define (tm:min obj) (vector-ref obj 1))
872 (define (tm:hour obj) (vector-ref obj 2))
873 (define (tm:mday obj) (vector-ref obj 3))
874 (define (tm:mon obj) (vector-ref obj 4))
875 (define (tm:year obj) (vector-ref obj 5))
876 (define (tm:wday obj) (vector-ref obj 6))
877 (define (tm:yday obj) (vector-ref obj 7))
878 (define (tm:isdst obj) (vector-ref obj 8))
879 (define (tm:gmtoff obj) (vector-ref obj 9))
880 (define (tm:zone obj) (vector-ref obj 10))
882 (define (set-tm:sec obj val) (vector-set! obj 0 val))
883 (define (set-tm:min obj val) (vector-set! obj 1 val))
884 (define (set-tm:hour obj val) (vector-set! obj 2 val))
885 (define (set-tm:mday obj val) (vector-set! obj 3 val))
886 (define (set-tm:mon obj val) (vector-set! obj 4 val))
887 (define (set-tm:year obj val) (vector-set! obj 5 val))
888 (define (set-tm:wday obj val) (vector-set! obj 6 val))
889 (define (set-tm:yday obj val) (vector-set! obj 7 val))
890 (define (set-tm:isdst obj val) (vector-set! obj 8 val))
891 (define (set-tm:gmtoff obj val) (vector-set! obj 9 val))
892 (define (set-tm:zone obj val) (vector-set! obj 10 val))
894 (define (tms:clock obj) (vector-ref obj 0))
895 (define (tms:utime obj) (vector-ref obj 1))
896 (define (tms:stime obj) (vector-ref obj 2))
897 (define (tms:cutime obj) (vector-ref obj 3))
898 (define (tms:cstime obj) (vector-ref obj 4))
902 ;;; {File Descriptors and Ports}
905 (define file-position ftell)
906 (define* (file-set-position port offset #:optional (whence SEEK_SET))
907 (seek port offset whence))
909 (define (move->fdes fd/port fd)
910 (cond ((integer? fd/port)
911 (dup->fdes fd/port fd)
915 (primitive-move->fdes fd/port fd)
916 (set-port-revealed! fd/port 1)
919 (define (release-port-handle port)
920 (let ((revealed (port-revealed port)))
922 (set-port-revealed! port (- revealed 1)))))
927 (fdopen (dup->fdes port/fd) mode))
928 ((port/fd mode new-fd)
929 (let ((port (fdopen (dup->fdes port/fd new-fd) mode)))
930 (set-port-revealed! port 1)
936 (dup->port port/fd "r"))
938 (dup->port port/fd "r" new-fd))))
943 (dup->port port/fd "w"))
945 (dup->port port/fd "w" new-fd))))
950 (if (integer? port/fd)
952 (dup->port port/fd (port-mode port/fd))))
954 (if (integer? port/fd)
955 (dup->fdes port/fd new-fd)
956 (dup->port port/fd (port-mode port/fd) new-fd)))))
958 (define (duplicate-port port modes)
959 (dup->port port modes))
961 (define (fdes->inport fdes)
962 (let loop ((rest-ports (fdes->ports fdes)))
963 (cond ((null? rest-ports)
964 (let ((result (fdopen fdes "r")))
965 (set-port-revealed! result 1)
967 ((input-port? (car rest-ports))
968 (set-port-revealed! (car rest-ports)
969 (+ (port-revealed (car rest-ports)) 1))
972 (loop (cdr rest-ports))))))
974 (define (fdes->outport fdes)
975 (let loop ((rest-ports (fdes->ports fdes)))
976 (cond ((null? rest-ports)
977 (let ((result (fdopen fdes "w")))
978 (set-port-revealed! result 1)
980 ((output-port? (car rest-ports))
981 (set-port-revealed! (car rest-ports)
982 (+ (port-revealed (car rest-ports)) 1))
985 (loop (cdr rest-ports))))))
987 (define (port->fdes port)
988 (set-port-revealed! port (+ (port-revealed port) 1))
991 (define (setenv name value)
993 (putenv (string-append name "=" value))
996 (define (unsetenv name)
997 "Remove the entry for NAME from the environment."
1005 (define (in-vicinity vicinity file)
1006 (let ((tail (let ((len (string-length vicinity)))
1009 (string-ref vicinity (- len 1))))))
1010 (string-append vicinity
1019 ;;; {Help for scm_shell}
1021 ;;; The argument-processing code used by Guile-based shells generates
1022 ;;; Scheme code based on the argument list. This page contains help
1023 ;;; functions for the code it generates.
1026 (define (command-line) (program-arguments))
1028 ;; This is mostly for the internal use of the code generated by
1029 ;; scm_compile_shell_switches.
1031 (define (turn-on-debugging)
1032 (debug-enable 'debug)
1033 (debug-enable 'backtrace)
1034 (read-enable 'positions))
1036 (define (load-user-init)
1037 (let* ((home (or (getenv "HOME")
1038 (false-if-exception (passwd:dir (getpwuid (getuid))))
1039 "/")) ;; fallback for cygwin etc.
1040 (init-file (in-vicinity home ".guile")))
1041 (if (file-exists? init-file)
1042 (primitive-load init-file))))
1046 ;;; {The interpreter stack}
1049 ;; %stacks defined in stacks.c
1050 (define (%start-stack tag thunk)
1051 (let ((prompt-tag (make-prompt-tag "start-stack")))
1055 (with-fluids ((%stacks (acons tag prompt-tag
1056 (or (fluid-ref %stacks) '()))))
1059 (%start-stack tag (lambda () (apply k args)))))))
1060 (define-syntax start-stack
1063 (%start-stack tag (lambda () exp)))))
1067 ;;; {Loading by paths}
1070 ;;; Load a Scheme source file named NAME, searching for it in the
1071 ;;; directories listed in %load-path, and applying each of the file
1072 ;;; name extensions listed in %load-extensions.
1073 (define (load-from-path name)
1074 (start-stack 'load-stack
1075 (primitive-load-path name)))
1077 (define %load-verbosely #f)
1078 (define (assert-load-verbosity v) (set! %load-verbosely v))
1080 (define (%load-announce file)
1082 (with-output-to-port (current-error-port)
1085 (display "loading ")
1090 (set! %load-hook %load-announce)
1092 (define* (load name #:optional reader)
1093 ;; Returns the .go file corresponding to `name'. Does not search load
1094 ;; paths, only the fallback path. If the .go file is missing or out of
1095 ;; date, and autocompilation is enabled, will try autocompilation, just
1096 ;; as primitive-load-path does internally. primitive-load is
1097 ;; unaffected. Returns #f if autocompilation failed or was disabled.
1099 ;; NB: Unless we need to compile the file, this function should not cause
1100 ;; (system base compile) to be loaded up. For that reason compiled-file-name
1101 ;; partially duplicates functionality from (system base compile).
1102 (define (compiled-file-name canon-path)
1103 (and %compile-fallback-path
1105 %compile-fallback-path
1106 ;; no need for '/' separator here, canon-path is absolute
1108 (cond ((or (null? %load-compiled-extensions)
1109 (string-null? (car %load-compiled-extensions)))
1110 (warn "invalid %load-compiled-extensions"
1111 %load-compiled-extensions)
1113 (else (car %load-compiled-extensions))))))
1114 (define (fresh-compiled-file-name go-path)
1117 (let* ((scmstat (stat name))
1118 (gostat (stat go-path #f)))
1119 (if (and gostat (= (stat:mtime gostat) (stat:mtime scmstat)))
1123 (format (current-error-port)
1124 ";;; note: source file ~a\n;;; newer than compiled ~a\n"
1127 (%load-should-autocompile
1128 (%warn-autocompilation-enabled)
1129 (format (current-error-port) ";;; compiling ~a\n" name)
1130 ;; This use of @ is (ironically?) boot-safe, as modules have
1131 ;; not been booted yet, so the resolve-module call in psyntax
1132 ;; doesn't try to load a module, and compile-file will be
1133 ;; treated as a function, not a macro.
1134 (let ((cfn ((@ (system base compile) compile-file) name
1135 #:env (current-module))))
1136 (format (current-error-port) ";;; compiled ~a\n" cfn)
1140 (format (current-error-port)
1141 ";;; WARNING: compilation of ~a failed:\n;;; key ~a, throw_args ~s\n"
1144 (with-fluids ((current-reader reader))
1145 (let ((cfn (and=> (and=> (false-if-exception (canonicalize-path name))
1147 fresh-compiled-file-name)))
1150 (start-stack 'load-stack
1151 (primitive-load name))))))
1155 ;;; {Reader Extensions}
1157 ;;; Reader code for various "#c" forms.
1160 (define read-eval? (make-fluid))
1161 (fluid-set! read-eval? #f)
1162 (read-hash-extend #\.
1164 (if (fluid-ref read-eval?)
1165 (eval (read port) (interaction-environment))
1167 "#. read expansion found and read-eval? is #f."))))
1171 ;;; {Low Level Modules}
1173 ;;; These are the low level data structures for modules.
1175 ;;; Every module object is of the type 'module-type', which is a record
1176 ;;; consisting of the following members:
1178 ;;; - eval-closure: the function that defines for its module the strategy that
1179 ;;; shall be followed when looking up symbols in the module.
1181 ;;; An eval-closure is a function taking two arguments: the symbol to be
1182 ;;; looked up and a boolean value telling whether a binding for the symbol
1183 ;;; should be created if it does not exist yet. If the symbol lookup
1184 ;;; succeeded (either because an existing binding was found or because a new
1185 ;;; binding was created), a variable object representing the binding is
1186 ;;; returned. Otherwise, the value #f is returned. Note that the eval
1187 ;;; closure does not take the module to be searched as an argument: During
1188 ;;; construction of the eval-closure, the eval-closure has to store the
1189 ;;; module it belongs to in its environment. This means, that any
1190 ;;; eval-closure can belong to only one module.
1192 ;;; The eval-closure of a module can be defined arbitrarily. However, three
1193 ;;; special cases of eval-closures are to be distinguished: During startup
1194 ;;; the module system is not yet activated. In this phase, no modules are
1195 ;;; defined and all bindings are automatically stored by the system in the
1196 ;;; pre-modules-obarray. Since no eval-closures exist at this time, the
1197 ;;; functions which require an eval-closure as their argument need to be
1198 ;;; passed the value #f.
1200 ;;; The other two special cases of eval-closures are the
1201 ;;; standard-eval-closure and the standard-interface-eval-closure. Both
1202 ;;; behave equally for the case that no new binding is to be created. The
1203 ;;; difference between the two comes in, when the boolean argument to the
1204 ;;; eval-closure indicates that a new binding shall be created if it is not
1207 ;;; Given that no new binding shall be created, both standard eval-closures
1208 ;;; define the following standard strategy of searching bindings in the
1209 ;;; module: First, the module's obarray is searched for the symbol. Second,
1210 ;;; if no binding for the symbol was found in the module's obarray, the
1211 ;;; module's binder procedure is exececuted. If this procedure did not
1212 ;;; return a binding for the symbol, the modules referenced in the module's
1213 ;;; uses list are recursively searched for a binding of the symbol. If the
1214 ;;; binding can not be found in these modules also, the symbol lookup has
1217 ;;; If a new binding shall be created, the standard-interface-eval-closure
1218 ;;; immediately returns indicating failure. That is, it does not even try
1219 ;;; to look up the symbol. In contrast, the standard-eval-closure would
1220 ;;; first search the obarray, and if no binding was found there, would
1221 ;;; create a new binding in the obarray, therefore not calling the binder
1222 ;;; procedure or searching the modules in the uses list.
1224 ;;; The explanation of the following members obarray, binder and uses
1225 ;;; assumes that the symbol lookup follows the strategy that is defined in
1226 ;;; the standard-eval-closure and the standard-interface-eval-closure.
1228 ;;; - obarray: a hash table that maps symbols to variable objects. In this
1229 ;;; hash table, the definitions are found that are local to the module (that
1230 ;;; is, not imported from other modules). When looking up bindings in the
1231 ;;; module, this hash table is searched first.
1233 ;;; - binder: either #f or a function taking a module and a symbol argument.
1234 ;;; If it is a function it is called after the obarray has been
1235 ;;; unsuccessfully searched for a binding. It then can provide bindings
1236 ;;; that would otherwise not be found locally in the module.
1238 ;;; - uses: a list of modules from which non-local bindings can be inherited.
1239 ;;; These modules are the third place queried for bindings after the obarray
1240 ;;; has been unsuccessfully searched and the binder function did not deliver
1241 ;;; a result either.
1243 ;;; - transformer: either #f or a function taking a scheme expression as
1244 ;;; delivered by read. If it is a function, it will be called to perform
1245 ;;; syntax transformations (e. g. makro expansion) on the given scheme
1246 ;;; expression. The output of the transformer function will then be passed
1247 ;;; to Guile's internal memoizer. This means that the output must be valid
1248 ;;; scheme code. The only exception is, that the output may make use of the
1249 ;;; syntax extensions provided to identify the modules that a binding
1252 ;;; - name: the name of the module. This is used for all kinds of printing
1253 ;;; outputs. In certain places the module name also serves as a way of
1254 ;;; identification. When adding a module to the uses list of another
1255 ;;; module, it is made sure that the new uses list will not contain two
1256 ;;; modules of the same name.
1258 ;;; - kind: classification of the kind of module. The value is (currently?)
1259 ;;; only used for printing. It has no influence on how a module is treated.
1260 ;;; Currently the following values are used when setting the module kind:
1261 ;;; 'module, 'directory, 'interface, 'custom-interface. If no explicit kind
1262 ;;; is set, it defaults to 'module.
1264 ;;; - duplicates-handlers: a list of procedures that get called to make a
1265 ;;; choice between two duplicate bindings when name clashes occur. See the
1266 ;;; `duplicate-handlers' global variable below.
1268 ;;; - observers: a list of procedures that get called when the module is
1271 ;;; - weak-observers: a weak-key hash table of procedures that get called
1272 ;;; when the module is modified. See `module-observe-weak' for details.
1274 ;;; In addition, the module may (must?) contain a binding for
1275 ;;; `%module-public-interface'. This variable should be bound to a module
1276 ;;; representing the exported interface of a module. See the
1277 ;;; `module-public-interface' and `module-export!' procedures.
1279 ;;; !!! warning: The interface to lazy binder procedures is going
1280 ;;; to be changed in an incompatible way to permit all the basic
1281 ;;; module ops to be virtualized.
1283 ;;; (make-module size use-list lazy-binding-proc) => module
1284 ;;; module-{obarray,uses,binder}[|-set!]
1285 ;;; (module? obj) => [#t|#f]
1286 ;;; (module-locally-bound? module symbol) => [#t|#f]
1287 ;;; (module-bound? module symbol) => [#t|#f]
1288 ;;; (module-symbol-locally-interned? module symbol) => [#t|#f]
1289 ;;; (module-symbol-interned? module symbol) => [#t|#f]
1290 ;;; (module-local-variable module symbol) => [#<variable ...> | #f]
1291 ;;; (module-variable module symbol) => [#<variable ...> | #f]
1292 ;;; (module-symbol-binding module symbol opt-value)
1293 ;;; => [ <obj> | opt-value | an error occurs ]
1294 ;;; (module-make-local-var! module symbol) => #<variable...>
1295 ;;; (module-add! module symbol var) => unspecified
1296 ;;; (module-remove! module symbol) => unspecified
1297 ;;; (module-for-each proc module) => unspecified
1298 ;;; (make-scm-module) => module ; a lazy copy of the symhash module
1299 ;;; (set-current-module module) => unspecified
1300 ;;; (current-module) => #<module...>
1306 ;;; {Printing Modules}
1309 ;; This is how modules are printed. You can re-define it.
1310 (define (%print-module mod port)
1312 (display (or (module-kind mod) "module") port)
1314 (display (module-name mod) port)
1316 (display (number->string (object-address mod) 16) port)
1320 ;; Locally extend the syntax to allow record accessors to be defined at
1321 ;; compile-time. Cache the rtd locally to the constructor, the getters and
1322 ;; the setters, in order to allow for redefinition of the record type; not
1323 ;; relevant in the case of modules, but perhaps if we make this public, it
1326 ((define-record-type
1328 (define (make-id scope . fragments)
1329 (datum->syntax #'scope
1330 (apply symbol-append
1332 (if (symbol? x) x (syntax->datum x)))
1335 (define (getter rtd type-name field slot)
1336 #`(define #,(make-id rtd type-name '- field)
1338 (lambda (#,type-name)
1339 (if (eq? (struct-vtable #,type-name) rtd)
1340 (struct-ref #,type-name #,slot)
1341 (%record-type-error rtd #,type-name))))))
1343 (define (setter rtd type-name field slot)
1344 #`(define #,(make-id rtd 'set- type-name '- field '!)
1346 (lambda (#,type-name val)
1347 (if (eq? (struct-vtable #,type-name) rtd)
1348 (struct-set! #,type-name #,slot val)
1349 (%record-type-error rtd #,type-name))))))
1351 (define (accessors rtd type-name fields n exp)
1352 (syntax-case fields ()
1354 (((field #:no-accessors) field* ...) (identifier? #'field)
1355 (accessors rtd type-name #'(field* ...) (1+ n)
1357 (((field #:no-setter) field* ...) (identifier? #'field)
1358 (accessors rtd type-name #'(field* ...) (1+ n)
1360 #,(getter rtd type-name #'field n))))
1361 (((field #:no-getter) field* ...) (identifier? #'field)
1362 (accessors rtd type-name #'(field* ...) (1+ n)
1364 #,(setter rtd type-name #'field n))))
1365 ((field field* ...) (identifier? #'field)
1366 (accessors rtd type-name #'(field* ...) (1+ n)
1368 #,(getter rtd type-name #'field n)
1369 #,(setter rtd type-name #'field n))))))
1371 (define (predicate rtd type-name fields exp)
1373 rtd type-name fields 0
1376 (define (#,(make-id rtd type-name '?) obj)
1377 (and (struct? obj) (eq? (struct-vtable obj) #,rtd))))))
1379 (define (field-list fields)
1380 (syntax-case fields ()
1382 (((f . opts) . rest) (identifier? #'f)
1383 (cons #'f (field-list #'rest)))
1384 ((f . rest) (identifier? #'f)
1385 (cons #'f (field-list #'rest)))))
1387 (define (constructor rtd type-name fields exp)
1388 (let ((ctor (make-id rtd type-name '-constructor))
1389 (args (field-list fields)))
1390 (predicate rtd type-name fields
1395 (make-struct rtd 0 #,@args))))
1396 (struct-set! #,rtd (+ vtable-offset-user 2)
1399 (define (type type-name printer fields)
1400 (define (make-layout)
1401 (let lp ((fields fields) (slots '()))
1402 (syntax-case fields ()
1403 (() (datum->syntax #'here
1405 (apply string-append slots))))
1406 ((_ . rest) (lp #'rest (cons "pw" slots))))))
1408 (let ((rtd (make-id type-name type-name '-type)))
1409 (constructor rtd type-name fields
1412 (make-struct record-type-vtable 0
1416 '#,(field-list fields)))
1417 (set-struct-vtable-name! #,rtd '#,type-name)))))
1420 ((_ type-name printer (field ...))
1421 (type #'type-name #'printer #'(field ...)))))))
1425 ;; A module is characterized by an obarray in which local symbols
1426 ;; are interned, a list of modules, "uses", from which non-local
1427 ;; bindings can be inherited, and an optional lazy-binder which
1428 ;; is a (CLOSURE module symbol) which, as a last resort, can provide
1429 ;; bindings that would otherwise not be found locally in the module.
1431 ;; NOTE: If you change the set of fields or their order, you also need to
1432 ;; change the constants in libguile/modules.h.
1434 ;; NOTE: The getter `module-eval-closure' is used in libguile/modules.c.
1435 ;; NOTE: The getter `module-transfomer' is defined libguile/modules.c.
1436 ;; NOTE: The getter `module-name' is defined later, due to boot reasons.
1437 ;; NOTE: The getter `module-public-interface' is used in libguile/modules.c.
1439 (define-record-type module
1440 (lambda (obj port) (%print-module obj port))
1445 (transformer #:no-getter)
1449 (import-obarray #:no-setter)
1451 (weak-observers #:no-setter)
1459 ;; make-module &opt size uses binder
1461 ;; Create a new module, perhaps with a particular size of obarray,
1462 ;; initial uses list, or binding procedure.
1467 (define (parse-arg index default)
1468 (if (> (length args) index)
1469 (list-ref args index)
1472 (define %default-import-size
1473 ;; Typical number of imported bindings actually used by a module.
1476 (if (> (length args) 3)
1477 (error "Too many args to make-module." args))
1479 (let ((size (parse-arg 0 31))
1480 (uses (parse-arg 1 '()))
1481 (binder (parse-arg 2 #f)))
1483 (if (not (integer? size))
1484 (error "Illegal size to make-module." size))
1485 (if (not (and (list? uses)
1486 (and-map module? uses)))
1487 (error "Incorrect use list." uses))
1488 (if (and binder (not (procedure? binder)))
1490 "Lazy-binder expected to be a procedure or #f." binder))
1492 (let ((module (module-constructor (make-hash-table size)
1493 uses binder #f macroexpand
1495 (make-hash-table %default-import-size)
1497 (make-weak-key-hash-table 31) #f
1498 (make-hash-table 7) #f #f #f)))
1500 ;; We can't pass this as an argument to module-constructor,
1501 ;; because we need it to close over a pointer to the module
1503 (set-module-eval-closure! module (standard-eval-closure module))
1510 ;;; {Observer protocol}
1513 (define (module-observe module proc)
1514 (set-module-observers! module (cons proc (module-observers module)))
1517 (define* (module-observe-weak module observer-id #:optional (proc observer-id))
1518 ;; Register PROC as an observer of MODULE under name OBSERVER-ID (which can
1519 ;; be any Scheme object). PROC is invoked and passed MODULE any time
1520 ;; MODULE is modified. PROC gets unregistered when OBSERVER-ID gets GC'd
1521 ;; (thus, it is never unregistered if OBSERVER-ID is an immediate value,
1524 ;; The two-argument version is kept for backward compatibility: when called
1525 ;; with two arguments, the observer gets unregistered when closure PROC
1526 ;; gets GC'd (making it impossible to use an anonymous lambda for PROC).
1527 (hashq-set! (module-weak-observers module) observer-id proc))
1529 (define (module-unobserve token)
1530 (let ((module (car token))
1533 (hash-remove! (module-weak-observers module) id)
1534 (set-module-observers! module (delq1! id (module-observers module)))))
1537 (define module-defer-observers #f)
1538 (define module-defer-observers-mutex (make-mutex 'recursive))
1539 (define module-defer-observers-table (make-hash-table))
1541 (define (module-modified m)
1542 (if module-defer-observers
1543 (hash-set! module-defer-observers-table m #t)
1544 (module-call-observers m)))
1546 ;;; This function can be used to delay calls to observers so that they
1547 ;;; can be called once only in the face of massive updating of modules.
1549 (define (call-with-deferred-observers thunk)
1552 (lock-mutex module-defer-observers-mutex)
1553 (set! module-defer-observers #t))
1556 (set! module-defer-observers #f)
1557 (hash-for-each (lambda (m dummy)
1558 (module-call-observers m))
1559 module-defer-observers-table)
1560 (hash-clear! module-defer-observers-table)
1561 (unlock-mutex module-defer-observers-mutex))))
1563 (define (module-call-observers m)
1564 (for-each (lambda (proc) (proc m)) (module-observers m))
1566 ;; We assume that weak observers don't (un)register themselves as they are
1567 ;; called since this would preclude proper iteration over the hash table
1569 (hash-for-each (lambda (id proc) (proc m)) (module-weak-observers m)))
1573 ;;; {Module Searching in General}
1575 ;;; We sometimes want to look for properties of a symbol
1576 ;;; just within the obarray of one module. If the property
1577 ;;; holds, then it is said to hold ``locally'' as in, ``The symbol
1578 ;;; DISPLAY is locally rebound in the module `safe-guile'.''
1581 ;;; Other times, we want to test for a symbol property in the obarray
1582 ;;; of M and, if it is not found there, try each of the modules in the
1583 ;;; uses list of M. This is the normal way of testing for some
1584 ;;; property, so we state these properties without qualification as
1585 ;;; in: ``The symbol 'fnord is interned in module M because it is
1586 ;;; interned locally in module M2 which is a member of the uses list
1590 ;; module-search fn m
1592 ;; return the first non-#f result of FN applied to M and then to
1593 ;; the modules in the uses of m, and so on recursively. If all applications
1594 ;; return #f, then so does this function.
1596 (define (module-search fn m v)
1599 (or (module-search fn (car pos) v)
1602 (loop (module-uses m))))
1605 ;;; {Is a symbol bound in a module?}
1607 ;;; Symbol S in Module M is bound if S is interned in M and if the binding
1608 ;;; of S in M has been set to some well-defined value.
1611 ;; module-locally-bound? module symbol
1613 ;; Is a symbol bound (interned and defined) locally in a given module?
1615 (define (module-locally-bound? m v)
1616 (let ((var (module-local-variable m v)))
1618 (variable-bound? var))))
1620 ;; module-bound? module symbol
1622 ;; Is a symbol bound (interned and defined) anywhere in a given module
1625 (define (module-bound? m v)
1626 (let ((var (module-variable m v)))
1628 (variable-bound? var))))
1630 ;;; {Is a symbol interned in a module?}
1632 ;;; Symbol S in Module M is interned if S occurs in
1633 ;;; of S in M has been set to some well-defined value.
1635 ;;; It is possible to intern a symbol in a module without providing
1636 ;;; an initial binding for the corresponding variable. This is done
1638 ;;; (module-add! module symbol (make-undefined-variable))
1640 ;;; In that case, the symbol is interned in the module, but not
1641 ;;; bound there. The unbound symbol shadows any binding for that
1642 ;;; symbol that might otherwise be inherited from a member of the uses list.
1645 (define (module-obarray-get-handle ob key)
1646 ((if (symbol? key) hashq-get-handle hash-get-handle) ob key))
1648 (define (module-obarray-ref ob key)
1649 ((if (symbol? key) hashq-ref hash-ref) ob key))
1651 (define (module-obarray-set! ob key val)
1652 ((if (symbol? key) hashq-set! hash-set!) ob key val))
1654 (define (module-obarray-remove! ob key)
1655 ((if (symbol? key) hashq-remove! hash-remove!) ob key))
1657 ;; module-symbol-locally-interned? module symbol
1659 ;; is a symbol interned (not neccessarily defined) locally in a given module
1660 ;; or its uses? Interned symbols shadow inherited bindings even if
1661 ;; they are not themselves bound to a defined value.
1663 (define (module-symbol-locally-interned? m v)
1664 (not (not (module-obarray-get-handle (module-obarray m) v))))
1666 ;; module-symbol-interned? module symbol
1668 ;; is a symbol interned (not neccessarily defined) anywhere in a given module
1669 ;; or its uses? Interned symbols shadow inherited bindings even if
1670 ;; they are not themselves bound to a defined value.
1672 (define (module-symbol-interned? m v)
1673 (module-search module-symbol-locally-interned? m v))
1676 ;;; {Mapping modules x symbols --> variables}
1679 ;; module-local-variable module symbol
1680 ;; return the local variable associated with a MODULE and SYMBOL.
1682 ;;; This function is very important. It is the only function that can
1683 ;;; return a variable from a module other than the mutators that store
1684 ;;; new variables in modules. Therefore, this function is the location
1685 ;;; of the "lazy binder" hack.
1687 ;;; If symbol is defined in MODULE, and if the definition binds symbol
1688 ;;; to a variable, return that variable object.
1690 ;;; If the symbols is not found at first, but the module has a lazy binder,
1691 ;;; then try the binder.
1693 ;;; If the symbol is not found at all, return #f.
1695 ;;; (This is now written in C, see `modules.c'.)
1698 ;;; {Mapping modules x symbols --> bindings}
1700 ;;; These are similar to the mapping to variables, except that the
1701 ;;; variable is dereferenced.
1704 ;; module-symbol-binding module symbol opt-value
1706 ;; return the binding of a variable specified by name within
1707 ;; a given module, signalling an error if the variable is unbound.
1708 ;; If the OPT-VALUE is passed, then instead of signalling an error,
1709 ;; return OPT-VALUE.
1711 (define (module-symbol-local-binding m v . opt-val)
1712 (let ((var (module-local-variable m v)))
1713 (if (and var (variable-bound? var))
1715 (if (not (null? opt-val))
1717 (error "Locally unbound variable." v)))))
1719 ;; module-symbol-binding module symbol opt-value
1721 ;; return the binding of a variable specified by name within
1722 ;; a given module, signalling an error if the variable is unbound.
1723 ;; If the OPT-VALUE is passed, then instead of signalling an error,
1724 ;; return OPT-VALUE.
1726 (define (module-symbol-binding m v . opt-val)
1727 (let ((var (module-variable m v)))
1728 (if (and var (variable-bound? var))
1730 (if (not (null? opt-val))
1732 (error "Unbound variable." v)))))
1737 ;;; {Adding Variables to Modules}
1740 ;; module-make-local-var! module symbol
1742 ;; ensure a variable for V in the local namespace of M.
1743 ;; If no variable was already there, then create a new and uninitialzied
1746 ;; This function is used in modules.c.
1748 (define (module-make-local-var! m v)
1749 (or (let ((b (module-obarray-ref (module-obarray m) v)))
1752 ;; Mark as modified since this function is called when
1753 ;; the standard eval closure defines a binding
1757 ;; Create a new local variable.
1758 (let ((local-var (make-undefined-variable)))
1759 (module-add! m v local-var)
1762 ;; module-ensure-local-variable! module symbol
1764 ;; Ensure that there is a local variable in MODULE for SYMBOL. If
1765 ;; there is no binding for SYMBOL, create a new uninitialized
1766 ;; variable. Return the local variable.
1768 (define (module-ensure-local-variable! module symbol)
1769 (or (module-local-variable module symbol)
1770 (let ((var (make-undefined-variable)))
1771 (module-add! module symbol var)
1774 ;; module-add! module symbol var
1776 ;; ensure a particular variable for V in the local namespace of M.
1778 (define (module-add! m v var)
1779 (if (not (variable? var))
1780 (error "Bad variable to module-add!" var))
1781 (module-obarray-set! (module-obarray m) v var)
1782 (module-modified m))
1786 ;; make sure that a symbol is undefined in the local namespace of M.
1788 (define (module-remove! m v)
1789 (module-obarray-remove! (module-obarray m) v)
1790 (module-modified m))
1792 (define (module-clear! m)
1793 (hash-clear! (module-obarray m))
1794 (module-modified m))
1796 ;; MODULE-FOR-EACH -- exported
1798 ;; Call PROC on each symbol in MODULE, with arguments of (SYMBOL VARIABLE).
1800 (define (module-for-each proc module)
1801 (hash-for-each proc (module-obarray module)))
1803 (define (module-map proc module)
1804 (hash-map->list proc (module-obarray module)))
1808 ;; Modules exist in a separate namespace from values, because you generally do
1809 ;; not want the name of a submodule, which you might not even use, to collide
1810 ;; with local variables that happen to be named the same as the submodule.
1812 (define (module-ref-submodule module name)
1813 (or (hashq-ref (module-submodules module) name)
1814 (and (module-submodule-binder module)
1815 ((module-submodule-binder module) module name))))
1817 (define (module-define-submodule! module name submodule)
1818 (hashq-set! (module-submodules module) name submodule))
1822 ;;; {Low Level Bootstrapping}
1827 ;; A root module uses the pre-modules-obarray as its obarray. This
1828 ;; special obarray accumulates all bindings that have been established
1829 ;; before the module system is fully booted.
1831 ;; (The obarray continues to be used by code that has been closed over
1832 ;; before the module system has been booted.)
1834 (define (make-root-module)
1835 (let ((m (make-module 0)))
1836 (set-module-obarray! m (%get-pre-modules-obarray))
1841 ;; The root interface is a module that uses the same obarray as the
1842 ;; root module. It does not allow new definitions, tho.
1844 (define (make-scm-module)
1845 (let ((m (make-module 0)))
1846 (set-module-obarray! m (%get-pre-modules-obarray))
1847 (set-module-eval-closure! m (standard-interface-eval-closure m))
1853 ;;; {Module-based Loading}
1856 (define (save-module-excursion thunk)
1857 (let ((inner-module (current-module))
1859 (dynamic-wind (lambda ()
1860 (set! outer-module (current-module))
1861 (set-current-module inner-module)
1862 (set! inner-module #f))
1865 (set! inner-module (current-module))
1866 (set-current-module outer-module)
1867 (set! outer-module #f)))))
1869 (define basic-load load)
1871 (define* (load-module filename #:optional reader)
1872 (save-module-excursion
1874 (let ((oldname (and (current-load-port)
1875 (port-filename (current-load-port)))))
1876 (basic-load (if (and oldname
1877 (> (string-length filename) 0)
1878 (not (char=? (string-ref filename 0) #\/))
1879 (not (string=? (dirname oldname) ".")))
1880 (string-append (dirname oldname) "/" filename)
1887 ;;; {MODULE-REF -- exported}
1890 ;; Returns the value of a variable called NAME in MODULE or any of its
1891 ;; used modules. If there is no such variable, then if the optional third
1892 ;; argument DEFAULT is present, it is returned; otherwise an error is signaled.
1894 (define (module-ref module name . rest)
1895 (let ((variable (module-variable module name)))
1896 (if (and variable (variable-bound? variable))
1897 (variable-ref variable)
1899 (error "No variable named" name 'in module)
1900 (car rest) ; default value
1903 ;; MODULE-SET! -- exported
1905 ;; Sets the variable called NAME in MODULE (or in a module that MODULE uses)
1906 ;; to VALUE; if there is no such variable, an error is signaled.
1908 (define (module-set! module name value)
1909 (let ((variable (module-variable module name)))
1911 (variable-set! variable value)
1912 (error "No variable named" name 'in module))))
1914 ;; MODULE-DEFINE! -- exported
1916 ;; Sets the variable called NAME in MODULE to VALUE; if there is no such
1917 ;; variable, it is added first.
1919 (define (module-define! module name value)
1920 (let ((variable (module-local-variable module name)))
1923 (variable-set! variable value)
1924 (module-modified module))
1925 (let ((variable (make-variable value)))
1926 (module-add! module name variable)))))
1928 ;; MODULE-DEFINED? -- exported
1930 ;; Return #t iff NAME is defined in MODULE (or in a module that MODULE
1933 (define (module-defined? module name)
1934 (let ((variable (module-variable module name)))
1935 (and variable (variable-bound? variable))))
1937 ;; MODULE-USE! module interface
1939 ;; Add INTERFACE to the list of interfaces used by MODULE.
1941 (define (module-use! module interface)
1942 (if (not (or (eq? module interface)
1943 (memq interface (module-uses module))))
1945 ;; Newly used modules must be appended rather than consed, so that
1946 ;; `module-variable' traverses the use list starting from the first
1948 (set-module-uses! module
1949 (append (filter (lambda (m)
1951 (equal? (module-name m)
1952 (module-name interface))))
1953 (module-uses module))
1955 (hash-clear! (module-import-obarray module))
1956 (module-modified module))))
1958 ;; MODULE-USE-INTERFACES! module interfaces
1960 ;; Same as MODULE-USE! but add multiple interfaces and check for duplicates
1962 (define (module-use-interfaces! module interfaces)
1963 (set-module-uses! module
1964 (append (module-uses module) interfaces))
1965 (hash-clear! (module-import-obarray module))
1966 (module-modified module))
1970 ;;; {Recursive Namespaces}
1972 ;;; A hierarchical namespace emerges if we consider some module to be
1973 ;;; root, and submodules of that module to be nested namespaces.
1975 ;;; The routines here manage variable names in hierarchical namespace.
1976 ;;; Each variable name is a list of elements, looked up in successively nested
1979 ;;; (nested-ref some-root-module '(foo bar baz))
1980 ;;; => <value of a variable named baz in the submodule bar of
1981 ;;; the submodule foo of some-root-module>
1986 ;;; ;; a-root is a module
1987 ;;; ;; name is a list of symbols
1989 ;;; nested-ref a-root name
1990 ;;; nested-set! a-root name val
1991 ;;; nested-define! a-root name val
1992 ;;; nested-remove! a-root name
1994 ;;; These functions manipulate values in namespaces. For referencing the
1995 ;;; namespaces themselves, use the following:
1997 ;;; nested-ref-module a-root name
1998 ;;; nested-define-module! a-root name mod
2000 ;;; (current-module) is a natural choice for a root so for convenience there are
2003 ;;; local-ref name == nested-ref (current-module) name
2004 ;;; local-set! name val == nested-set! (current-module) name val
2005 ;;; local-define name val == nested-define! (current-module) name val
2006 ;;; local-remove name == nested-remove! (current-module) name
2007 ;;; local-ref-module name == nested-ref-module (current-module) name
2008 ;;; local-define-module! name m == nested-define-module! (current-module) name m
2012 (define (nested-ref root names)
2015 (let loop ((cur root)
2019 (module-ref cur head #f)
2020 (let ((cur (module-ref-submodule cur head)))
2022 (loop cur (car tail) (cdr tail))))))))
2024 (define (nested-set! root names val)
2025 (let loop ((cur root)
2029 (module-set! cur head val)
2030 (let ((cur (module-ref-submodule cur head)))
2032 (error "failed to resolve module" names)
2033 (loop cur (car tail) (cdr tail)))))))
2035 (define (nested-define! root names val)
2036 (let loop ((cur root)
2040 (module-define! cur head val)
2041 (let ((cur (module-ref-submodule cur head)))
2043 (error "failed to resolve module" names)
2044 (loop cur (car tail) (cdr tail)))))))
2046 (define (nested-remove! root names)
2047 (let loop ((cur root)
2051 (module-remove! cur head)
2052 (let ((cur (module-ref-submodule cur head)))
2054 (error "failed to resolve module" names)
2055 (loop cur (car tail) (cdr tail)))))))
2058 (define (nested-ref-module root names)
2059 (let loop ((cur root)
2063 (let ((cur (module-ref-submodule cur (car names))))
2065 (loop cur (cdr names)))))))
2067 (define (nested-define-module! root names module)
2069 (error "can't redefine root module" root module)
2070 (let loop ((cur root)
2074 (module-define-submodule! cur head module)
2075 (let ((cur (or (module-ref-submodule cur head)
2076 (let ((m (make-module 31)))
2077 (set-module-kind! m 'directory)
2078 (set-module-name! m (append (module-name cur)
2080 (module-define-submodule! cur head m)
2082 (loop cur (car tail) (cdr tail)))))))
2085 (define (local-ref names)
2086 (nested-ref (current-module) names))
2088 (define (local-set! names val)
2089 (nested-set! (current-module) names val))
2091 (define (local-define names val)
2092 (nested-define! (current-module) names val))
2094 (define (local-remove names)
2095 (nested-remove! (current-module) names))
2097 (define (local-ref-module names)
2098 (nested-ref-module (current-module) names))
2100 (define (local-define-module names mod)
2101 (nested-define-module! (current-module) names mod))
2107 ;;; {The (guile) module}
2109 ;;; The standard module, which has the core Guile bindings. Also called the
2110 ;;; "root module", as it is imported by many other modules, but it is not
2111 ;;; necessarily the root of anything; and indeed, the module named '() might be
2112 ;;; better thought of as a root.
2115 (define (set-system-module! m s)
2116 (set-procedure-property! (module-eval-closure m) 'system-module s))
2117 (define the-root-module (make-root-module))
2118 (define the-scm-module (make-scm-module))
2119 (set-module-public-interface! the-root-module the-scm-module)
2120 (set-module-name! the-root-module '(guile))
2121 (set-module-name! the-scm-module '(guile))
2122 (set-module-kind! the-scm-module 'interface)
2123 (set-system-module! the-root-module #t)
2124 (set-system-module! the-scm-module #t)
2129 ;; Now that we have a root module, even though modules aren't fully booted,
2130 ;; expand the definition of resolve-module.
2132 (define (resolve-module name . args)
2133 (if (equal? name '(guile))
2135 (error "unexpected module to resolve during module boot" name)))
2137 ;; Cheat. These bindings are needed by modules.c, but we don't want
2138 ;; to move their real definition here because that would be unnatural.
2140 (define process-define-module #f)
2141 (define process-use-modules #f)
2142 (define module-export! #f)
2143 (define default-duplicate-binding-procedures #f)
2145 ;; This boots the module system. All bindings needed by modules.c
2146 ;; must have been defined by now.
2148 (set-current-module the-root-module)
2153 ;; Now that modules are booted, give module-name its final definition.
2156 (let ((accessor (record-accessor module-type 'name)))
2159 (let ((name (list (gensym))))
2160 ;; Name MOD and bind it in the module root so that it's visible to
2161 ;; `resolve-module'. This is important as `psyntax' stores module
2162 ;; names and relies on being able to `resolve-module' them.
2163 (set-module-name! mod name)
2164 (nested-define-module! (resolve-module '() #f) name mod)
2167 (define (make-modules-in module name)
2168 (or (nested-ref-module module name)
2169 (let ((m (make-module 31)))
2170 (set-module-kind! m 'directory)
2171 (set-module-name! m (append (module-name module) name))
2172 (nested-define-module! module name m)
2175 (define (beautify-user-module! module)
2176 (let ((interface (module-public-interface module)))
2177 (if (or (not interface)
2178 (eq? interface module))
2179 (let ((interface (make-module 31)))
2180 (set-module-name! interface (module-name module))
2181 (set-module-version! interface (module-version module))
2182 (set-module-kind! interface 'interface)
2183 (set-module-public-interface! module interface))))
2184 (if (and (not (memq the-scm-module (module-uses module)))
2185 (not (eq? module the-root-module)))
2186 ;; Import the default set of bindings (from the SCM module) in MODULE.
2187 (module-use! module the-scm-module)))
2189 (define (version-matches? version-ref target)
2190 (define (sub-versions-match? v-refs t)
2191 (define (sub-version-matches? v-ref t)
2192 (let ((matches? (lambda (v) (sub-version-matches? v t))))
2194 ((number? v-ref) (eqv? v-ref t))
2197 ((>=) (>= t (cadr v-ref)))
2198 ((<=) (<= t (cadr v-ref)))
2199 ((and) (and-map matches? (cdr v-ref)))
2200 ((or) (or-map matches? (cdr v-ref)))
2201 ((not) (not (matches? (cadr v-ref))))
2202 (else (error "Invalid sub-version reference" v-ref))))
2203 (else (error "Invalid sub-version reference" v-ref)))))
2205 (and (not (null? t))
2206 (sub-version-matches? (car v-refs) (car t))
2207 (sub-versions-match? (cdr v-refs) (cdr t)))))
2209 (let ((matches? (lambda (v) (version-matches? v target))))
2210 (or (null? version-ref)
2211 (case (car version-ref)
2212 ((and) (and-map matches? (cdr version-ref)))
2213 ((or) (or-map matches? (cdr version-ref)))
2214 ((not) (not (matches? (cadr version-ref))))
2215 (else (sub-versions-match? version-ref target))))))
2217 (define (make-fresh-user-module)
2218 (let ((m (make-module)))
2219 (beautify-user-module! m)
2222 ;; NOTE: This binding is used in libguile/modules.c.
2224 (define resolve-module
2225 (let ((root (make-module)))
2226 (set-module-name! root '())
2227 ;; Define the-root-module as '(guile).
2228 (module-define-submodule! root 'guile the-root-module)
2230 (lambda* (name #:optional (autoload #t) (version #f) #:key (ensure #t))
2231 (let ((already (nested-ref-module root name)))
2234 (or (not autoload) (module-public-interface already)))
2235 ;; A hit, a palpable hit.
2237 (not (version-matches? version (module-version already))))
2238 (error "incompatible module version already loaded" name))
2241 ;; Try to autoload the module, and recurse.
2242 (try-load-module name version)
2243 (resolve-module name #f #:ensure ensure))
2245 ;; No module found (or if one was, it had no public interface), and
2246 ;; we're not autoloading. Make an empty module if #:ensure is true.
2249 (make-modules-in root name)))))))))
2252 (define (try-load-module name version)
2253 (try-module-autoload name version))
2255 (define (purify-module! module)
2256 "Removes bindings in MODULE which are inherited from the (guile) module."
2257 (let ((use-list (module-uses module)))
2258 (if (and (pair? use-list)
2259 (eq? (car (last-pair use-list)) the-scm-module))
2260 (set-module-uses! module (reverse (cdr (reverse use-list)))))))
2262 ;; Return a module that is an interface to the module designated by
2265 ;; `resolve-interface' takes four keyword arguments:
2267 ;; #:select SELECTION
2269 ;; SELECTION is a list of binding-specs to be imported; A binding-spec
2270 ;; is either a symbol or a pair of symbols (ORIG . SEEN), where ORIG
2271 ;; is the name in the used module and SEEN is the name in the using
2272 ;; module. Note that SEEN is also passed through RENAMER, below. The
2273 ;; default is to select all bindings. If you specify no selection but
2274 ;; a renamer, only the bindings that already exist in the used module
2275 ;; are made available in the interface. Bindings that are added later
2276 ;; are not picked up.
2280 ;; BINDINGS is a list of bindings which should not be imported.
2284 ;; PREFIX is a symbol that will be appended to each exported name.
2285 ;; The default is to not perform any renaming.
2287 ;; #:renamer RENAMER
2289 ;; RENAMER is a procedure that takes a symbol and returns its new
2290 ;; name. The default is not perform any renaming.
2292 ;; Signal "no code for module" error if module name is not resolvable
2293 ;; or its public interface is not available. Signal "no binding"
2294 ;; error if selected binding does not exist in the used module.
2296 (define* (resolve-interface name #:key
2301 (symbol-prefix-proc prefix)
2304 (let* ((module (resolve-module name #t version #:ensure #f))
2305 (public-i (and module (module-public-interface module))))
2306 (and (or (not module) (not public-i))
2307 (error "no code for module" name))
2308 (if (and (not select) (null? hide) (eq? renamer identity))
2310 (let ((selection (or select (module-map (lambda (sym var) sym)
2312 (custom-i (make-module 31)))
2313 (set-module-kind! custom-i 'custom-interface)
2314 (set-module-name! custom-i name)
2315 ;; XXX - should use a lazy binder so that changes to the
2316 ;; used module are picked up automatically.
2317 (for-each (lambda (bspec)
2318 (let* ((direct? (symbol? bspec))
2319 (orig (if direct? bspec (car bspec)))
2320 (seen (if direct? bspec (cdr bspec)))
2321 (var (or (module-local-variable public-i orig)
2322 (module-local-variable module orig)
2324 ;; fixme: format manually for now
2326 #f "no binding `~A' in module ~A"
2328 (if (memq orig hide)
2329 (set! hide (delq! orig hide))
2330 (module-add! custom-i
2334 ;; Check that we are not hiding bindings which don't exist
2335 (for-each (lambda (binding)
2336 (if (not (module-local-variable public-i binding))
2339 #f "no binding `~A' to hide in module ~A"
2344 (define (symbol-prefix-proc prefix)
2346 (symbol-append prefix symbol)))
2348 ;; This function is called from "modules.c". If you change it, be
2349 ;; sure to update "modules.c" as well.
2351 (define (process-define-module args)
2352 (let* ((module-id (car args))
2353 (module (resolve-module module-id #f))
2355 (unrecognized (lambda (arg)
2356 (error "unrecognized define-module argument" arg))))
2357 (beautify-user-module! module)
2358 (let loop ((kws kws)
2359 (reversed-interfaces '())
2366 (call-with-deferred-observers
2368 (module-use-interfaces! module (reverse reversed-interfaces))
2369 (module-export! module exports)
2370 (module-replace! module replacements)
2371 (module-re-export! module re-exports)
2372 (if (not (null? autoloads))
2373 (apply module-autoload! module autoloads))))
2375 ((#:use-module #:use-syntax)
2376 (or (pair? (cdr kws))
2379 ((equal? (caadr kws) '(ice-9 syncase))
2380 (issue-deprecation-warning
2381 "(ice-9 syncase) is deprecated. Support for syntax-case is now in Guile core.")
2389 (let* ((interface-args (cadr kws))
2390 (interface (apply resolve-interface interface-args)))
2391 (and (eq? (car kws) #:use-syntax)
2392 (or (symbol? (caar interface-args))
2393 (error "invalid module name for use-syntax"
2394 (car interface-args)))
2395 (set-module-transformer!
2397 (module-ref interface
2398 (car (last-pair (car interface-args)))
2401 (cons interface reversed-interfaces)
2407 (or (and (pair? (cdr kws)) (pair? (cddr kws)))
2414 (let ((name (cadr kws))
2415 (bindings (caddr kws)))
2416 (cons* name bindings autoloads))))
2418 (set-system-module! module #t)
2419 (loop (cdr kws) reversed-interfaces exports re-exports
2420 replacements autoloads))
2422 (purify-module! module)
2423 (loop (cdr kws) reversed-interfaces exports re-exports
2424 replacements autoloads))
2426 (or (pair? (cdr kws))
2428 (let ((version (cadr kws)))
2429 (set-module-version! module version)
2430 (set-module-version! (module-public-interface module) version))
2431 (loop (cddr kws) reversed-interfaces exports re-exports
2432 replacements autoloads))
2434 (if (not (pair? (cdr kws)))
2436 (set-module-duplicates-handlers!
2438 (lookup-duplicates-handlers (cadr kws)))
2439 (loop (cddr kws) reversed-interfaces exports re-exports
2440 replacements autoloads))
2441 ((#:export #:export-syntax)
2442 (or (pair? (cdr kws))
2446 (append (cadr kws) exports)
2450 ((#:re-export #:re-export-syntax)
2451 (or (pair? (cdr kws))
2456 (append (cadr kws) re-exports)
2459 ((#:replace #:replace-syntax)
2460 (or (pair? (cdr kws))
2466 (append (cadr kws) replacements)
2469 (or (pair? (cdr kws))
2471 (set-module-filename! module (cadr kws))
2479 (unrecognized kws)))))
2480 (run-hook module-defined-hook module)
2483 ;; `module-defined-hook' is a hook that is run whenever a new module
2484 ;; is defined. Its members are called with one argument, the new
2486 (define module-defined-hook (make-hook 1))
2493 (define (make-autoload-interface module name bindings)
2494 (let ((b (lambda (a sym definep)
2495 (and (memq sym bindings)
2496 (let ((i (module-public-interface (resolve-module name))))
2498 (error "missing interface for module" name))
2499 (let ((autoload (memq a (module-uses module))))
2500 ;; Replace autoload-interface with actual interface if
2501 ;; that has not happened yet.
2502 (if (pair? autoload)
2503 (set-car! autoload i)))
2504 (module-local-variable i sym))))))
2505 (module-constructor (make-hash-table 0) '() b #f #f name 'autoload #f
2506 (make-hash-table 0) '() (make-weak-value-hash-table 31) #f
2507 (make-hash-table 0) #f #f #f)))
2509 (define (module-autoload! module . args)
2510 "Have @var{module} automatically load the module named @var{name} when one
2511 of the symbols listed in @var{bindings} is looked up. @var{args} should be a
2512 list of module-name/binding-list pairs, e.g., as in @code{(module-autoload!
2513 module '(ice-9 q) '(make-q q-length))}."
2514 (let loop ((args args))
2518 (error "invalid name+binding autoload list" args))
2520 (let ((name (car args))
2521 (bindings (cadr args)))
2522 (module-use! module (make-autoload-interface module
2524 (loop (cddr args)))))))
2529 ;;; {Autoloading modules}
2532 (define autoloads-in-progress '())
2534 ;; This function is called from "modules.c". If you change it, be
2535 ;; sure to update "modules.c" as well.
2537 (define* (try-module-autoload module-name #:optional version)
2538 (let* ((reverse-name (reverse module-name))
2539 (name (symbol->string (car reverse-name)))
2540 (dir-hint-module-name (reverse (cdr reverse-name)))
2541 (dir-hint (apply string-append
2543 (string-append (symbol->string elt) "/"))
2544 dir-hint-module-name))))
2545 (resolve-module dir-hint-module-name #f)
2546 (and (not (autoload-done-or-in-progress? dir-hint name))
2549 (lambda () (autoload-in-progress! dir-hint name))
2551 (with-fluids ((current-reader #f))
2552 (save-module-excursion
2554 ;; The initial environment when loading a module is a fresh
2556 (set-current-module (make-fresh-user-module))
2557 ;; Here we could allow some other search strategy (other than
2558 ;; primitive-load-path), for example using versions encoded
2559 ;; into the file system -- but then we would have to figure
2560 ;; out how to locate the compiled file, do autocompilation,
2561 ;; etc. Punt for now, and don't use versions when locating
2563 (primitive-load-path (in-vicinity dir-hint name) #f)
2565 (lambda () (set-autoloaded! dir-hint name didit)))
2570 ;;; {Dynamic linking of modules}
2573 (define autoloads-done '((guile . guile)))
2575 (define (autoload-done-or-in-progress? p m)
2576 (let ((n (cons p m)))
2577 (->bool (or (member n autoloads-done)
2578 (member n autoloads-in-progress)))))
2580 (define (autoload-done! p m)
2581 (let ((n (cons p m)))
2582 (set! autoloads-in-progress
2583 (delete! n autoloads-in-progress))
2584 (or (member n autoloads-done)
2585 (set! autoloads-done (cons n autoloads-done)))))
2587 (define (autoload-in-progress! p m)
2588 (let ((n (cons p m)))
2589 (set! autoloads-done
2590 (delete! n autoloads-done))
2591 (set! autoloads-in-progress (cons n autoloads-in-progress))))
2593 (define (set-autoloaded! p m done?)
2595 (autoload-done! p m)
2596 (let ((n (cons p m)))
2597 (set! autoloads-done (delete! n autoloads-done))
2598 (set! autoloads-in-progress (delete! n autoloads-in-progress)))))
2602 ;;; {Run-time options}
2605 (define-syntax define-option-interface
2607 ((_ (interface (options enable disable) (option-set!)))
2614 (begin (interface arg) (interface))
2617 (apply (lambda (name value documentation)
2619 (if (< (string-length (symbol->string name)) 8)
2624 (display documentation)
2628 (define (enable . flags)
2629 (interface (append flags (interface)))
2631 (define (disable . flags)
2632 (let ((options (interface)))
2633 (for-each (lambda (flag) (set! options (delq! flag options)))
2637 (define-syntax option-set!
2640 (options (append (options) (list 'opt val))))))))))
2642 (define-option-interface
2643 (eval-options-interface
2644 (eval-options eval-enable eval-disable)
2647 (define-option-interface
2648 (debug-options-interface
2649 (debug-options debug-enable debug-disable)
2652 (define-option-interface
2653 (evaluator-traps-interface
2654 (traps trap-enable trap-disable)
2657 (define-option-interface
2658 (read-options-interface
2659 (read-options read-enable read-disable)
2662 (define-option-interface
2663 (print-options-interface
2664 (print-options print-enable print-disable)
2669 ;;; {The Unspecified Value}
2671 ;;; Currently Guile represents unspecified values via one particular value,
2672 ;;; which may be obtained by evaluating (if #f #f). It would be nice in the
2673 ;;; future if we could replace this with a return of 0 values, though.
2676 (define-syntax *unspecified*
2677 (identifier-syntax (if #f #f)))
2679 (define (unspecified? v) (eq? v *unspecified*))
2687 (define *repl-level* (make-fluid))
2689 ;; Programs can call `batch-mode?' to see if they are running as part of a
2690 ;; script or if they are running interactively. REPL implementations ensure that
2691 ;; `batch-mode?' returns #f during their extent.
2693 (define (batch-mode?)
2694 (negative? (or (fluid-ref *repl-level*) -1)))
2696 ;; Programs can re-enter batch mode, for example after a fork, by calling
2697 ;; `ensure-batch-mode!'. It's not a great interface, though; it would be better
2698 ;; to abort to the outermost prompt, and call a thunk there.
2700 (define (ensure-batch-mode!)
2701 (fluid-set! *repl-level* #f))
2703 (define (quit . args)
2704 (apply throw 'quit args))
2708 (define (gc-run-time)
2709 (cdr (assq 'gc-time-taken (gc-stats))))
2711 (define abort-hook (make-hook))
2712 (define before-error-hook (make-hook))
2713 (define after-error-hook (make-hook))
2714 (define before-backtrace-hook (make-hook))
2715 (define after-backtrace-hook (make-hook))
2717 (define before-read-hook (make-hook))
2718 (define after-read-hook (make-hook))
2719 (define before-eval-hook (make-hook 1))
2720 (define after-eval-hook (make-hook 1))
2721 (define before-print-hook (make-hook 1))
2722 (define after-print-hook (make-hook 1))
2724 ;;; This hook is run at the very end of an interactive session.
2726 (define exit-hook (make-hook))
2728 ;;; The default repl-reader function. We may override this if we've
2729 ;;; the readline library.
2731 (lambda* (prompt #:optional (reader (fluid-ref current-reader)))
2732 (if (not (char-ready?))
2733 (display (if (string? prompt) prompt (prompt))))
2735 (run-hook before-read-hook)
2736 ((or reader read) (current-input-port))))
2741 ;;; {IOTA functions: generating lists of numbers}
2745 (let loop ((count (1- n)) (result '()))
2746 (if (< count 0) result
2747 (loop (1- count) (cons count result)))))
2753 ;;; with `continue' and `break'.
2756 ;; The inliner will remove the prompts at compile-time if it finds that
2757 ;; `continue' or `break' are not used.
2759 (define-syntax while
2762 ((while cond body ...)
2763 #`(let ((break-tag (make-prompt-tag "break"))
2764 (continue-tag (make-prompt-tag "continue")))
2768 (define-syntax #,(datum->syntax #'while 'break)
2772 #'(abort-to-prompt break-tag))
2774 (syntax-violation 'break "too many arguments" x))
2777 (abort-to-prompt break-tag))))))
2782 (define-syntax #,(datum->syntax #'while 'continue)
2786 #'(abort-to-prompt continue-tag))
2788 (syntax-violation 'continue "too many arguments" x))
2791 (apply abort-to-prompt continue-tag args))))))
2792 (do () ((not cond)) body ...))
2793 (lambda (k) (lp)))))
2800 ;;; {Module System Macros}
2803 ;; Return a list of expressions that evaluate to the appropriate
2804 ;; arguments for resolve-interface according to SPEC.
2806 (eval-when (compile)
2807 (if (memq 'prefix (read-options))
2808 (error "boot-9 must be compiled with #:kw, not :kw")))
2810 (define (keyword-like-symbol->keyword sym)
2811 (symbol->keyword (string->symbol (substring (symbol->string sym) 1))))
2813 ;; FIXME: we really need to clean up the guts of the module system.
2814 ;; We can compile to something better than process-define-module.
2816 (define-syntax define-module
2818 (define (keyword-like? stx)
2819 (let ((dat (syntax->datum stx)))
2821 (eqv? (string-ref (symbol->string dat) 0) #\:))))
2822 (define (->keyword sym)
2823 (symbol->keyword (string->symbol (substring (symbol->string sym) 1))))
2825 (define (quotify-iface args)
2826 (let loop ((in args) (out '()))
2829 ;; The user wanted #:foo, but wrote :foo. Fix it.
2830 ((sym . in) (keyword-like? #'sym)
2831 (loop #`(#,(->keyword (syntax->datum #'sym)) . in) out))
2832 ((kw . in) (not (keyword? (syntax->datum #'kw)))
2833 (syntax-violation 'define-module "expected keyword arg" x #'kw))
2834 ((#:renamer renamer . in)
2835 (loop #'in (cons* #'renamer #:renamer out)))
2837 (loop #'in (cons* #''val #'kw out))))))
2839 (define (quotify args)
2840 ;; Just quote everything except #:use-module and #:use-syntax. We
2841 ;; need to know about all arguments regardless since we want to turn
2842 ;; symbols that look like keywords into real keywords, and the
2843 ;; keyword args in a define-module form are not regular
2844 ;; (i.e. no-backtrace doesn't take a value).
2845 (let loop ((in args) (out '()))
2848 ;; The user wanted #:foo, but wrote :foo. Fix it.
2849 ((sym . in) (keyword-like? #'sym)
2850 (loop #`(#,(->keyword (syntax->datum #'sym)) . in) out))
2851 ((kw . in) (not (keyword? (syntax->datum #'kw)))
2852 (syntax-violation 'define-module "expected keyword arg" x #'kw))
2853 ((#:no-backtrace . in)
2854 (loop #'in (cons #:no-backtrace out)))
2856 (loop #'in (cons #:pure out)))
2858 (syntax-violation 'define-module "keyword arg without value" x #'kw))
2859 ((use-module (name name* ...) . in)
2860 (and (memq (syntax->datum #'use-module) '(#:use-module #:use-syntax))
2861 (and-map symbol? (syntax->datum #'(name name* ...))))
2863 (cons* #''((name name* ...))
2866 ((use-module ((name name* ...) arg ...) . in)
2867 (and (memq (syntax->datum #'use-module) '(#:use-module #:use-syntax))
2868 (and-map symbol? (syntax->datum #'(name name* ...))))
2870 (cons* #`(list '(name name* ...) #,@(quotify-iface #'(arg ...)))
2873 ((#:autoload name bindings . in)
2874 (loop #'in (cons* #''bindings #''name #:autoload out)))
2876 (loop #'in (cons* #''val #'kw out))))))
2879 ((_ (name name* ...) arg ...)
2880 (with-syntax (((quoted-arg ...) (quotify #'(arg ...))))
2881 #'(eval-when (eval load compile expand)
2882 (let ((m (process-define-module
2883 (list '(name name* ...)
2884 #:filename (assq-ref
2885 (or (current-source-location) '())
2888 (set-current-module m)
2891 ;; The guts of the use-modules macro. Add the interfaces of the named
2892 ;; modules to the use-list of the current module, in order.
2894 ;; This function is called by "modules.c". If you change it, be sure
2895 ;; to change scm_c_use_module as well.
2897 (define (process-use-modules module-interface-args)
2898 (let ((interfaces (map (lambda (mif-args)
2899 (or (apply resolve-interface mif-args)
2900 (error "no such module" mif-args)))
2901 module-interface-args)))
2902 (call-with-deferred-observers
2904 (module-use-interfaces! (current-module) interfaces)))))
2906 (define-syntax use-modules
2908 (define (keyword-like? stx)
2909 (let ((dat (syntax->datum stx)))
2911 (eqv? (string-ref (symbol->string dat) 0) #\:))))
2912 (define (->keyword sym)
2913 (symbol->keyword (string->symbol (substring (symbol->string sym) 1))))
2915 (define (quotify-iface args)
2916 (let loop ((in args) (out '()))
2919 ;; The user wanted #:foo, but wrote :foo. Fix it.
2920 ((sym . in) (keyword-like? #'sym)
2921 (loop #`(#,(->keyword (syntax->datum #'sym)) . in) out))
2922 ((kw . in) (not (keyword? (syntax->datum #'kw)))
2923 (syntax-violation 'define-module "expected keyword arg" x #'kw))
2924 ((#:renamer renamer . in)
2925 (loop #'in (cons* #'renamer #:renamer out)))
2927 (loop #'in (cons* #''val #'kw out))))))
2929 (define (quotify specs)
2930 (let lp ((in specs) (out '()))
2933 (((name name* ...) . in)
2934 (and-map symbol? (syntax->datum #'(name name* ...)))
2935 (lp #'in (cons #''((name name* ...)) out)))
2936 ((((name name* ...) arg ...) . in)
2937 (and-map symbol? (syntax->datum #'(name name* ...)))
2938 (with-syntax (((quoted-arg ...) (quotify-iface #'(arg ...))))
2939 (lp #'in (cons #`(list '(name name* ...) quoted-arg ...)
2944 (with-syntax (((quoted-args ...) (quotify #'(spec ...))))
2945 #'(eval-when (eval load compile expand)
2946 (process-use-modules (list quoted-args ...))
2949 (define-syntax use-syntax
2953 (eval-when (eval load compile expand)
2954 (issue-deprecation-warning
2955 "`use-syntax' is deprecated. Please contact guile-devel for more info."))
2956 (use-modules spec ...)))))
2958 (include-from-path "ice-9/r6rs-libraries")
2960 (define-syntax define-private
2965 (define-syntax define-public
2967 ((_ (name . args) . body)
2968 (define-public name (lambda args . body)))
2974 (define-syntax defmacro-public
2976 ((_ name args . body)
2978 (defmacro name args . body)
2979 (export-syntax name)))))
2981 ;; And now for the most important macro.
2984 ((_ formals body ...)
2985 (lambda formals body ...))))
2988 ;; Export a local variable
2990 ;; This function is called from "modules.c". If you change it, be
2991 ;; sure to update "modules.c" as well.
2993 (define (module-export! m names)
2994 (let ((public-i (module-public-interface m)))
2995 (for-each (lambda (name)
2996 (let* ((internal-name (if (pair? name) (car name) name))
2997 (external-name (if (pair? name) (cdr name) name))
2998 (var (module-ensure-local-variable! m internal-name)))
2999 (module-add! public-i external-name var)))
3002 (define (module-replace! m names)
3003 (let ((public-i (module-public-interface m)))
3004 (for-each (lambda (name)
3005 (let* ((internal-name (if (pair? name) (car name) name))
3006 (external-name (if (pair? name) (cdr name) name))
3007 (var (module-ensure-local-variable! m internal-name)))
3008 (set-object-property! var 'replace #t)
3009 (module-add! public-i external-name var)))
3012 ;; Export all local variables from a module
3014 (define (module-export-all! mod)
3015 (define (fresh-interface!)
3016 (let ((iface (make-module)))
3017 (set-module-name! iface (module-name mod))
3018 (set-module-version! iface (module-version mod))
3019 (set-module-kind! iface 'interface)
3020 (set-module-public-interface! mod iface)
3022 (let ((iface (or (module-public-interface mod)
3023 (fresh-interface!))))
3024 (set-module-obarray! iface (module-obarray mod))))
3026 ;; Re-export a imported variable
3028 (define (module-re-export! m names)
3029 (let ((public-i (module-public-interface m)))
3030 (for-each (lambda (name)
3031 (let* ((internal-name (if (pair? name) (car name) name))
3032 (external-name (if (pair? name) (cdr name) name))
3033 (var (module-variable m internal-name)))
3035 (error "Undefined variable:" internal-name))
3036 ((eq? var (module-local-variable m internal-name))
3037 (error "re-exporting local variable:" internal-name))
3039 (module-add! public-i external-name var)))))
3042 (define-syntax export
3045 (eval-when (eval load compile expand)
3046 (call-with-deferred-observers
3048 (module-export! (current-module) '(name ...))))))))
3050 (define-syntax re-export
3053 (eval-when (eval load compile expand)
3054 (call-with-deferred-observers
3056 (module-re-export! (current-module) '(name ...))))))))
3058 (define-syntax export!
3061 (eval-when (eval load compile expand)
3062 (call-with-deferred-observers
3064 (module-replace! (current-module) '(name ...))))))))
3066 (define-syntax export-syntax
3069 (export name ...))))
3071 (define-syntax re-export-syntax
3074 (re-export name ...))))
3076 (define load load-module)
3083 (define make-mutable-parameter
3084 (let ((make (lambda (fluid converter)
3088 (fluid-set! fluid (converter (car args))))))))
3089 (lambda* (init #:optional (converter identity))
3090 (let ((fluid (make-fluid)))
3091 (fluid-set! fluid (converter init))
3092 (make fluid converter)))))
3096 ;;; {Handling of duplicate imported bindings}
3099 ;; Duplicate handlers take the following arguments:
3101 ;; module importing module
3102 ;; name conflicting name
3103 ;; int1 old interface where name occurs
3104 ;; val1 value of binding in old interface
3105 ;; int2 new interface where name occurs
3106 ;; val2 value of binding in new interface
3107 ;; var previous resolution or #f
3108 ;; val value of previous resolution
3110 ;; A duplicate handler can take three alternative actions:
3112 ;; 1. return #f => leave responsibility to next handler
3113 ;; 2. exit with an error
3114 ;; 3. return a variable resolving the conflict
3117 (define duplicate-handlers
3118 (let ((m (make-module 7)))
3120 (define (check module name int1 val1 int2 val2 var val)
3121 (scm-error 'misc-error
3123 "~A: `~A' imported from both ~A and ~A"
3124 (list (module-name module)
3130 (define (warn module name int1 val1 int2 val2 var val)
3131 (format (current-error-port)
3132 "WARNING: ~A: `~A' imported from both ~A and ~A\n"
3133 (module-name module)
3139 (define (replace module name int1 val1 int2 val2 var val)
3140 (let ((old (or (and var (object-property var 'replace) var)
3141 (module-variable int1 name)))
3142 (new (module-variable int2 name)))
3143 (if (object-property old 'replace)
3144 (and (or (eq? old new)
3145 (not (object-property new 'replace)))
3147 (and (object-property new 'replace)
3150 (define (warn-override-core module name int1 val1 int2 val2 var val)
3151 (and (eq? int1 the-scm-module)
3153 (format (current-error-port)
3154 "WARNING: ~A: imported module ~A overrides core binding `~A'\n"
3155 (module-name module)
3158 (module-local-variable int2 name))))
3160 (define (first module name int1 val1 int2 val2 var val)
3161 (or var (module-local-variable int1 name)))
3163 (define (last module name int1 val1 int2 val2 var val)
3164 (module-local-variable int2 name))
3166 (define (noop module name int1 val1 int2 val2 var val)
3169 (set-module-name! m 'duplicate-handlers)
3170 (set-module-kind! m 'interface)
3171 (module-define! m 'check check)
3172 (module-define! m 'warn warn)
3173 (module-define! m 'replace replace)
3174 (module-define! m 'warn-override-core warn-override-core)
3175 (module-define! m 'first first)
3176 (module-define! m 'last last)
3177 (module-define! m 'merge-generics noop)
3178 (module-define! m 'merge-accessors noop)
3181 (define (lookup-duplicates-handlers handler-names)
3183 (map (lambda (handler-name)
3184 (or (module-symbol-local-binding
3185 duplicate-handlers handler-name #f)
3186 (error "invalid duplicate handler name:"
3188 (if (list? handler-names)
3190 (list handler-names)))))
3192 (define default-duplicate-binding-procedures
3193 (make-mutable-parameter #f))
3195 (define default-duplicate-binding-handler
3196 (make-mutable-parameter '(replace warn-override-core warn last)
3197 (lambda (handler-names)
3198 (default-duplicate-binding-procedures
3199 (lookup-duplicates-handlers handler-names))
3204 ;;; {`cond-expand' for SRFI-0 support.}
3206 ;;; This syntactic form expands into different commands or
3207 ;;; definitions, depending on the features provided by the Scheme
3213 ;;; --> (cond-expand <cond-expand-clause>+)
3214 ;;; | (cond-expand <cond-expand-clause>* (else <command-or-definition>))
3215 ;;; <cond-expand-clause>
3216 ;;; --> (<feature-requirement> <command-or-definition>*)
3217 ;;; <feature-requirement>
3218 ;;; --> <feature-identifier>
3219 ;;; | (and <feature-requirement>*)
3220 ;;; | (or <feature-requirement>*)
3221 ;;; | (not <feature-requirement>)
3222 ;;; <feature-identifier>
3223 ;;; --> <a symbol which is the name or alias of a SRFI>
3225 ;;; Additionally, this implementation provides the
3226 ;;; <feature-identifier>s `guile' and `r5rs', so that programs can
3227 ;;; determine the implementation type and the supported standard.
3229 ;;; Currently, the following feature identifiers are supported:
3231 ;;; guile r5rs srfi-0 srfi-4 srfi-6 srfi-13 srfi-14 srfi-55 srfi-61
3233 ;;; Remember to update the features list when adding more SRFIs.
3236 (define %cond-expand-features
3237 ;; Adjust the above comment when changing this.
3241 srfi-0 ;; cond-expand itself
3242 srfi-4 ;; homogenous numeric vectors
3243 srfi-6 ;; open-input-string etc, in the guile core
3244 srfi-13 ;; string library
3245 srfi-14 ;; character sets
3246 srfi-55 ;; require-extension
3247 srfi-61 ;; general cond clause
3250 ;; This table maps module public interfaces to the list of features.
3252 (define %cond-expand-table (make-hash-table 31))
3254 ;; Add one or more features to the `cond-expand' feature list of the
3257 (define (cond-expand-provide module features)
3258 (let ((mod (module-public-interface module)))
3260 (hashq-set! %cond-expand-table mod
3261 (append (hashq-ref %cond-expand-table mod '())
3264 (define-syntax cond-expand
3266 (define (module-has-feature? mod sym)
3267 (or-map (lambda (mod)
3268 (memq sym (hashq-ref %cond-expand-table mod '())))
3271 (define (condition-matches? condition)
3272 (syntax-case condition (and or not)
3274 (and-map condition-matches? #'(c ...)))
3276 (or-map condition-matches? #'(c ...)))
3278 (if (condition-matches? #'c) #f #t))
3281 (let ((sym (syntax->datum #'c)))
3282 (if (memq sym %cond-expand-features)
3284 (module-has-feature? (current-module) sym))))))
3286 (define (match clauses alternate)
3287 (syntax-case clauses ()
3288 (((condition form ...) . rest)
3289 (if (condition-matches? #'condition)
3291 (match #'rest alternate)))
3294 (syntax-case x (else)
3295 ((_ clause ... (else form ...))
3296 (match #'(clause ...)
3298 #'(begin form ...))))
3300 (match #'(clause ...)
3302 (syntax-violation 'cond-expand "unfulfilled cond-expand" x)))))))
3304 ;; This procedure gets called from the startup code with a list of
3305 ;; numbers, which are the numbers of the SRFIs to be loaded on startup.
3307 (define (use-srfis srfis)
3308 (process-use-modules
3310 (list (list 'srfi (string->symbol
3311 (string-append "srfi-" (number->string num))))))
3316 ;;; srfi-55: require-extension
3319 (define-syntax require-extension
3321 (syntax-case x (srfi)
3323 (and-map integer? (syntax->datum #'(n ...)))
3327 (datum->syntax x (symbol-append 'srfi- n)))
3329 (map number->string (syntax->datum #'(n ...)))))))
3330 #'(use-modules (srfi srfi-n) ...)))
3332 (identifier? #'type)
3333 (syntax-violation 'require-extension "Not a recognized extension type"
3338 (define using-readline?
3339 (let ((using-readline? (make-fluid)))
3340 (make-procedure-with-setter
3341 (lambda () (fluid-ref using-readline?))
3342 (lambda (v) (fluid-set! using-readline? v)))))
3345 (let ((guile-user-module (resolve-module '(guile-user))))
3347 ;; Use some convenient modules (in reverse order)
3349 (set-current-module guile-user-module)
3350 (process-use-modules
3355 (if (provided? 'regex)
3358 (if (provided? 'threads)
3359 '(((ice-9 threads)))
3361 ;; load debugger on demand
3362 (module-autoload! guile-user-module '(system vm debug) '(debug))
3364 (let ((old-handlers #f)
3365 ;; We can't use @ here, as modules have been booted, but in Guile's
3366 ;; build the srfi-1 helper lib hasn't been built yet, which will
3367 ;; result in an error when (system repl repl) is loaded at compile
3368 ;; time (to see if it is a macro or not).
3369 (start-repl (module-ref (resolve-module '(system repl repl))
3371 (signals (if (provided? 'posix)
3372 `((,SIGINT . "User interrupt"))
3379 (let ((make-handler (lambda (msg)
3387 (map (lambda (sig-msg)
3388 (sigaction (car sig-msg)
3389 (make-handler (cdr sig-msg))))
3392 ;; the protected thunk.
3394 (let ((status (start-repl 'scheme)))
3395 (run-hook exit-hook)
3400 (map (lambda (sig-msg old-handler)
3401 (if (not (car old-handler))
3402 ;; restore original C handler.
3403 (sigaction (car sig-msg) #f)
3404 ;; restore Scheme handler, SIG_IGN or SIG_DFL.
3405 (sigaction (car sig-msg)
3407 (cdr old-handler))))
3408 signals old-handlers))))))
3412 ;;; {Deprecated stuff}
3416 (module-use! the-scm-module (resolve-interface '(ice-9 deprecated))))
3420 ;;; Place the user in the guile-user module.
3424 (module-use! the-scm-module (resolve-interface '(srfi srfi-4)))
3426 (define-module (guile-user)
3427 #:autoload (system base compile) (compile))
3429 ;; Remain in the `(guile)' module at compilation-time so that the
3430 ;; `-Wunused-toplevel' warning works as expected.
3431 (eval-when (compile) (set-current-module the-root-module))
3433 ;;; boot-9.scm ends here