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.
71 ;; Ideally we'd like to be able to give these default values for all threads,
72 ;; even threads not created by Guile; but alack, that does not currently seem
73 ;; possible. So wrap the getters in thunks.
74 (define %running-exception-handlers (make-fluid))
75 (define %exception-handler (make-fluid))
77 (define (running-exception-handlers)
78 (or (fluid-ref %running-exception-handlers)
80 (fluid-set! %running-exception-handlers '())
82 (define (exception-handler)
83 (or (fluid-ref %exception-handler)
85 (fluid-set! %exception-handler default-exception-handler)
86 default-exception-handler)))
88 (define (default-exception-handler k . args)
92 ((not (pair? args)) 0)
93 ((integer? (car args)) (car args))
97 (format (current-error-port) "guile: uncaught throw to ~a: ~a\n" k args)
100 (define (default-throw-handler prompt-tag catch-k)
101 (let ((prev (exception-handler)))
102 (lambda (thrown-k . args)
103 (if (or (eq? thrown-k catch-k) (eqv? catch-k #t))
104 (apply abort-to-prompt prompt-tag thrown-k args)
105 (apply prev thrown-k args)))))
107 (define (custom-throw-handler prompt-tag catch-k pre)
108 (let ((prev (exception-handler)))
109 (lambda (thrown-k . args)
110 (if (or (eq? thrown-k catch-k) (eqv? catch-k #t))
111 (let ((running (running-exception-handlers)))
112 (with-fluids ((%running-exception-handlers (cons pre running)))
113 (if (not (memq pre running))
114 (apply pre thrown-k args))
117 (apply abort-to-prompt prompt-tag thrown-k args)
118 (apply prev thrown-k args))))
119 (apply prev thrown-k args)))))
122 (lambda* (k thunk handler #:optional pre-unwind-handler)
123 "Invoke @var{thunk} in the dynamic context of @var{handler} for
124 exceptions matching @var{key}. If thunk throws to the symbol
125 @var{key}, then @var{handler} is invoked this way:
127 (handler key args ...)
130 @var{key} is a symbol or @code{#t}.
132 @var{thunk} takes no arguments. If @var{thunk} returns
133 normally, that is the return value of @code{catch}.
135 Handler is invoked outside the scope of its own @code{catch}.
136 If @var{handler} again throws to the same key, a new handler
137 from further up the call chain is invoked.
139 If the key is @code{#t}, then a throw to @emph{any} symbol will
140 match this call to @code{catch}.
142 If a @var{pre-unwind-handler} is given and @var{thunk} throws
143 an exception that matches @var{key}, Guile calls the
144 @var{pre-unwind-handler} before unwinding the dynamic state and
145 invoking the main @var{handler}. @var{pre-unwind-handler} should
146 be a procedure with the same signature as @var{handler}, that
147 is @code{(lambda (key . args))}. It is typically used to save
148 the stack at the point where the exception occurred, but can also
149 query other parts of the dynamic state at that point, such as
152 A @var{pre-unwind-handler} can exit either normally or non-locally.
153 If it exits normally, Guile unwinds the stack and dynamic context
154 and then calls the normal (third argument) handler. If it exits
155 non-locally, that exit determines the continuation."
156 (if (not (or (symbol? k) (eqv? k #t)))
157 (scm-error "catch" 'wrong-type-arg
158 "Wrong type argument in position ~a: ~a"
159 (list 1 k) (list k)))
160 (let ((tag (make-prompt-tag "catch")))
166 (if pre-unwind-handler
167 (custom-throw-handler tag k pre-unwind-handler)
168 (default-throw-handler tag k))))
170 (lambda (cont k . args)
171 (apply handler k args))))))
173 (define! 'with-throw-handler
174 (lambda (k thunk pre-unwind-handler)
175 "Add @var{handler} to the dynamic context as a throw handler
176 for key @var{key}, then invoke @var{thunk}."
177 (if (not (or (symbol? k) (eqv? k #t)))
178 (scm-error "with-throw-handler" 'wrong-type-arg
179 "Wrong type argument in position ~a: ~a"
180 (list 1 k) (list k)))
181 (with-fluids ((%exception-handler
182 (custom-throw-handler #f k pre-unwind-handler)))
187 "Invoke the catch form matching @var{key}, passing @var{args} to the
190 @var{key} is a symbol. It will match catches of the same symbol or of @code{#t}.
192 If there is no handler at all, Guile prints an error and then exits."
193 (if (not (symbol? key))
194 ((exception-handler) 'wrong-type-arg "throw"
195 "Wrong type argument in position ~a: ~a" (list 1 key) (list key))
196 (apply (exception-handler) key args)))))
201 ;;; {R4RS compliance}
204 (primitive-load-path "ice-9/r4rs")
208 ;;; {Simple Debugging Tools}
211 ;; peek takes any number of arguments, writes them to the
212 ;; current ouput port, and returns the last argument.
213 ;; It is handy to wrap around an expression to look at
214 ;; a value each time is evaluated, e.g.:
216 ;; (+ 10 (troublesome-fn))
217 ;; => (+ 10 (pk 'troublesome-fn-returned (troublesome-fn)))
220 (define (peek . stuff)
225 (car (last-pair stuff)))
230 (define (warn . stuff)
231 (with-output-to-port (current-error-port)
234 (display ";;; WARNING ")
237 (car (last-pair stuff)))))
244 (define (provide sym)
245 (if (not (memq sym *features*))
246 (set! *features* (cons sym *features*))))
248 ;; Return #t iff FEATURE is available to this Guile interpreter. In SLIB,
249 ;; provided? also checks to see if the module is available. We should do that
252 (define (provided? feature)
253 (and (memq feature *features*) #t))
257 ;;; {and-map and or-map}
259 ;;; (and-map fn lst) is like (and (fn (car lst)) (fn (cadr lst)) (fn...) ...)
260 ;;; (or-map fn lst) is like (or (fn (car lst)) (fn (cadr lst)) (fn...) ...)
265 ;; Apply f to successive elements of l until exhaustion or f returns #f.
266 ;; If returning early, return #f. Otherwise, return the last value returned
267 ;; by f. If f has never been called because l is empty, return #t.
269 (define (and-map f lst)
270 (let loop ((result #t)
275 (loop (f (car l)) (cdr l))))))
279 ;; Apply f to successive elements of l until exhaustion or while f returns #f.
280 ;; If returning early, return the return value of f.
282 (define (or-map f lst)
283 (let loop ((result #f)
287 (loop (f (car l)) (cdr l))))))
291 ;; let format alias simple-format until the more complete version is loaded
293 (define format simple-format)
295 ;; this is scheme wrapping the C code so the final pred call is a tail call,
298 (lambda* (char_pred s #:optional (start 0) (end (string-length s)))
299 (if (and (procedure? char_pred)
301 (<= end (string-length s))) ;; let c-code handle range error
302 (or (string-any-c-code char_pred s start (1- end))
303 (char_pred (string-ref s (1- end))))
304 (string-any-c-code char_pred s start end))))
306 ;; this is scheme wrapping the C code so the final pred call is a tail call,
309 (lambda* (char_pred s #:optional (start 0) (end (string-length s)))
310 (if (and (procedure? char_pred)
312 (<= end (string-length s))) ;; let c-code handle range error
313 (and (string-every-c-code char_pred s start (1- end))
314 (char_pred (string-ref s (1- end))))
315 (string-every-c-code char_pred s start end))))
317 ;; A variant of string-fill! that we keep for compatability
319 (define (substring-fill! str start end fill)
320 (string-fill! str fill start end))
324 ;; Define a minimal stub of the module API for psyntax, before modules
326 (define (module-name x)
328 (define (module-define! module sym val)
329 (let ((v (hashq-ref (%get-pre-modules-obarray) sym)))
331 (variable-set! v val)
332 (hashq-set! (%get-pre-modules-obarray) sym
333 (make-variable val)))))
334 (define (module-ref module sym)
335 (let ((v (module-variable module sym)))
336 (if v (variable-ref v) (error "badness!" (pk module) (pk sym)))))
337 (define (resolve-module . args)
340 ;; API provided by psyntax
341 (define syntax-violation #f)
342 (define datum->syntax #f)
343 (define syntax->datum #f)
344 (define syntax-source #f)
345 (define identifier? #f)
346 (define generate-temporaries #f)
347 (define bound-identifier=? #f)
348 (define free-identifier=? #f)
350 ;; $sc-dispatch is an implementation detail of psyntax. It is used by
351 ;; expanded macros, to dispatch an input against a set of patterns.
352 (define $sc-dispatch #f)
355 (primitive-load-path "ice-9/psyntax-pp")
356 ;; The binding for `macroexpand' has now been overridden, making psyntax the
363 ((_ x y ...) (if x (and y ...) #f))))
369 ((_ x y ...) (let ((t x)) (if t t (or y ...))))))
371 ;; The "maybe-more" bits are something of a hack, so that we can support
372 ;; SRFI-61. Rewrites into a standalone syntax-case macro would be
375 (syntax-rules (=> else)
376 ((_ "maybe-more" test consequent)
377 (if test consequent))
379 ((_ "maybe-more" test consequent clause ...)
380 (if test consequent (cond clause ...)))
382 ((_ (else else1 else2 ...))
383 (begin else1 else2 ...))
385 ((_ (test => receiver) more-clause ...)
387 (cond "maybe-more" t (receiver t) more-clause ...)))
389 ((_ (generator guard => receiver) more-clause ...)
390 (call-with-values (lambda () generator)
393 (apply guard t) (apply receiver t) more-clause ...))))
395 ((_ (test => receiver ...) more-clause ...)
396 (syntax-violation 'cond "wrong number of receiver expressions"
397 '(test => receiver ...)))
398 ((_ (generator guard => receiver ...) more-clause ...)
399 (syntax-violation 'cond "wrong number of receiver expressions"
400 '(generator guard => receiver ...)))
402 ((_ (test) more-clause ...)
404 (cond "maybe-more" t t more-clause ...)))
406 ((_ (test body1 body2 ...) more-clause ...)
408 test (begin body1 body2 ...) more-clause ...))))
414 (let ((atom-key (key ...)))
415 (case atom-key clauses ...)))
417 (else result1 result2 ...))
418 (begin result1 result2 ...))
420 ((atoms ...) result1 result2 ...))
421 (if (memv key '(atoms ...))
422 (begin result1 result2 ...)))
424 ((atoms ...) result1 result2 ...)
426 (if (memv key '(atoms ...))
427 (begin result1 result2 ...)
428 (case key clause clauses ...)))))
432 ((do ((var init step ...) ...)
445 (loop (do "step" var step ...)
455 ((_ exp) (make-promise (lambda () exp)))))
457 (include-from-path "ice-9/quasisyntax")
459 (define-syntax current-source-location
463 (with-syntax ((s (datum->syntax x (syntax-source x))))
472 (define-syntax define-macro
476 ((_ (macro . args) doc body1 body ...)
477 (string? (syntax->datum #'doc))
478 #'(define-macro macro doc (lambda args body1 body ...)))
479 ((_ (macro . args) body ...)
480 #'(define-macro macro #f (lambda args body ...)))
481 ((_ macro doc transformer)
482 (or (string? (syntax->datum #'doc))
483 (not (syntax->datum #'doc)))
484 #'(define-syntax macro
487 #((macro-type . defmacro)
488 (defmacro-args args))
491 (let ((v (syntax->datum #'args)))
492 (datum->syntax y (apply transformer v)))))))))))
494 (define-syntax defmacro
496 "Define a defmacro, with the old lispy defun syntax."
498 ((_ macro args doc body1 body ...)
499 (string? (syntax->datum #'doc))
500 #'(define-macro macro doc (lambda args body1 body ...)))
501 ((_ macro args body ...)
502 #'(define-macro macro #f (lambda args body ...))))))
510 ;;; Depends on: defmacro
513 (defmacro begin-deprecated forms
514 (if (include-deprecated-features)
520 ;;; {Trivial Functions}
523 (define (identity x) x)
524 (define (and=> value procedure) (and value (procedure value)))
525 (define call/cc call-with-current-continuation)
527 (defmacro false-if-exception (expr)
530 ;; avoid saving backtraces inside false-if-exception
531 (with-fluids ((the-last-stack (fluid-ref the-last-stack)))
537 ;;; {General Properties}
540 ;; This is a more modern interface to properties. It will replace all
541 ;; other property-like things eventually.
543 (define (make-object-property)
544 (let ((prop (primitive-make-property #f)))
545 (make-procedure-with-setter
546 (lambda (obj) (primitive-property-ref prop obj))
547 (lambda (obj val) (primitive-property-set! prop obj val)))))
551 ;;; {Symbol Properties}
554 (define (symbol-property sym prop)
555 (let ((pair (assoc prop (symbol-pref sym))))
556 (and pair (cdr pair))))
558 (define (set-symbol-property! sym prop val)
559 (let ((pair (assoc prop (symbol-pref sym))))
562 (symbol-pset! sym (acons prop val (symbol-pref sym))))))
564 (define (symbol-property-remove! sym prop)
565 (let ((pair (assoc prop (symbol-pref sym))))
567 (symbol-pset! sym (delq! pair (symbol-pref sym))))))
574 (define (array-shape a)
575 (map (lambda (ind) (if (number? ind) (list 0 (+ -1 ind)) ind))
576 (array-dimensions a)))
583 (define (kw-arg-ref args kw)
584 (let ((rem (member kw args)))
585 (and rem (pair? (cdr rem)) (cadr rem))))
592 (define (struct-layout s)
593 (struct-ref (struct-vtable s) vtable-index-layout))
600 ;; Printing records: by default, records are printed as
602 ;; #<type-name field1: val1 field2: val2 ...>
604 ;; You can change that by giving a custom printing function to
605 ;; MAKE-RECORD-TYPE (after the list of field symbols). This function
606 ;; will be called like
608 ;; (<printer> object port)
610 ;; It should print OBJECT to PORT.
612 (define (inherit-print-state old-port new-port)
613 (if (get-print-state old-port)
614 (port-with-print-state new-port (get-print-state old-port))
617 ;; 0: type-name, 1: fields, 2: constructor
618 (define record-type-vtable
619 ;; FIXME: This should just call make-vtable, not make-vtable-vtable; but for
620 ;; that we need to expose the bare vtable-vtable to Scheme.
621 (make-vtable-vtable "prprpw" 0
623 (cond ((eq? s record-type-vtable)
624 (display "#<record-type-vtable>" p))
626 (display "#<record-type " p)
627 (display (record-type-name s) p)
630 (define (record-type? obj)
631 (and (struct? obj) (eq? record-type-vtable (struct-vtable obj))))
633 (define* (make-record-type type-name fields #:optional printer)
634 ;; Pre-generate constructors for nfields < 20.
635 (define-syntax make-constructor
637 (define *max-static-argument-count* 20)
638 (define (make-formals n)
644 (string (integer->char (+ (char->integer #\a) i)))))
648 ((_ rtd exp) (not (identifier? #'exp))
650 (make-constructor rtd n)))
654 (if (< n *max-static-argument-count*)
655 (cons (with-syntax (((formal ...) (make-formals n))
659 (make-struct rtd 0 formal ...))))
664 (if (= (length args) nfields)
665 (apply make-struct rtd 0 args)
666 (scm-error 'wrong-number-of-args
667 (format #f "make-~a" type-name)
668 "Wrong number of arguments" '() #f)))))))))
670 (define (default-record-printer s p)
672 (display (record-type-name (record-type-descriptor s)) p)
673 (let loop ((fields (record-type-fields (record-type-descriptor s)))
676 ((not (null? fields))
678 (display (car fields) p)
680 (display (struct-ref s off) p)
681 (loop (cdr fields) (+ 1 off)))))
684 (let ((rtd (make-struct record-type-vtable 0
687 (map (lambda (f) "pw") fields)))
688 (or printer default-record-printer)
690 (copy-tree fields))))
691 (struct-set! rtd (+ vtable-offset-user 2)
692 (make-constructor rtd (length fields)))
693 ;; Temporary solution: Associate a name to the record type descriptor
694 ;; so that the object system can create a wrapper class for it.
695 (set-struct-vtable-name! rtd (if (symbol? type-name)
697 (string->symbol type-name)))
700 (define (record-type-name obj)
701 (if (record-type? obj)
702 (struct-ref obj vtable-offset-user)
703 (error 'not-a-record-type obj)))
705 (define (record-type-fields obj)
706 (if (record-type? obj)
707 (struct-ref obj (+ 1 vtable-offset-user))
708 (error 'not-a-record-type obj)))
710 (define* (record-constructor rtd #:optional field-names)
711 (if (not field-names)
712 (struct-ref rtd (+ 2 vtable-offset-user))
714 `(lambda ,field-names
715 (make-struct ',rtd 0 ,@(map (lambda (f)
716 (if (memq f field-names)
719 (record-type-fields rtd)))))))
721 (define (record-predicate rtd)
722 (lambda (obj) (and (struct? obj) (eq? rtd (struct-vtable obj)))))
724 (define (%record-type-error rtd obj) ;; private helper
725 (or (eq? rtd (record-type-descriptor obj))
726 (scm-error 'wrong-type-arg "%record-type-check"
727 "Wrong type record (want `~S'): ~S"
728 (list (record-type-name rtd) obj)
731 (define (record-accessor rtd field-name)
732 (let ((pos (list-index (record-type-fields rtd) field-name)))
734 (error 'no-such-field field-name))
736 (if (eq? (struct-vtable obj) rtd)
738 (%record-type-error rtd obj)))))
740 (define (record-modifier rtd field-name)
741 (let ((pos (list-index (record-type-fields rtd) field-name)))
743 (error 'no-such-field field-name))
745 (if (eq? (struct-vtable obj) rtd)
746 (struct-set! obj pos val)
747 (%record-type-error rtd obj)))))
749 (define (record? obj)
750 (and (struct? obj) (record-type? (struct-vtable obj))))
752 (define (record-type-descriptor obj)
755 (error 'not-a-record obj)))
764 (define (->bool x) (not (not x)))
771 (define (symbol-append . args)
772 (string->symbol (apply string-append (map symbol->string args))))
774 (define (list->symbol . args)
775 (string->symbol (apply list->string args)))
777 (define (symbol . args)
778 (string->symbol (apply string args)))
785 (define (list-index l k)
791 (loop (+ n 1) (cdr l))))))
795 (if (provided? 'posix)
796 (primitive-load-path "ice-9/posix"))
798 (if (provided? 'socket)
799 (primitive-load-path "ice-9/networking"))
801 ;; For reference, Emacs file-exists-p uses stat in this same way.
803 (if (provided? 'posix)
805 (->bool (stat str #f)))
807 (let ((port (catch 'system-error (lambda () (open-file str OPEN_READ))
809 (if port (begin (close-port port) #t)
812 (define file-is-directory?
813 (if (provided? 'posix)
815 (eq? (stat:type (stat str)) 'directory))
817 (let ((port (catch 'system-error
818 (lambda () (open-file (string-append str "/.")
821 (if port (begin (close-port port) #t)
824 (define (has-suffix? str suffix)
825 (string-suffix? suffix str))
827 (define (system-error-errno args)
828 (if (eq? (car args) 'system-error)
829 (car (list-ref args 4))
837 (define (error . args)
840 (scm-error 'misc-error #f "?" #f #f)
841 (let loop ((msg "~A")
843 (if (not (null? rest))
844 (loop (string-append msg " ~S")
846 (scm-error 'misc-error #f msg args #f)))))
848 ;; bad-throw is the hook that is called upon a throw to a an unhandled
849 ;; key (unless the throw has four arguments, in which case
850 ;; it's usually interpreted as an error throw.)
851 ;; If the key has a default handler (a throw-handler-default property),
852 ;; it is applied to the throw.
854 (define (bad-throw key . args)
855 (let ((default (symbol-property key 'throw-handler-default)))
856 (or (and default (apply default key args))
857 (apply error "unhandled-exception:" key args))))
861 (define (tm:sec obj) (vector-ref obj 0))
862 (define (tm:min obj) (vector-ref obj 1))
863 (define (tm:hour obj) (vector-ref obj 2))
864 (define (tm:mday obj) (vector-ref obj 3))
865 (define (tm:mon obj) (vector-ref obj 4))
866 (define (tm:year obj) (vector-ref obj 5))
867 (define (tm:wday obj) (vector-ref obj 6))
868 (define (tm:yday obj) (vector-ref obj 7))
869 (define (tm:isdst obj) (vector-ref obj 8))
870 (define (tm:gmtoff obj) (vector-ref obj 9))
871 (define (tm:zone obj) (vector-ref obj 10))
873 (define (set-tm:sec obj val) (vector-set! obj 0 val))
874 (define (set-tm:min obj val) (vector-set! obj 1 val))
875 (define (set-tm:hour obj val) (vector-set! obj 2 val))
876 (define (set-tm:mday obj val) (vector-set! obj 3 val))
877 (define (set-tm:mon obj val) (vector-set! obj 4 val))
878 (define (set-tm:year obj val) (vector-set! obj 5 val))
879 (define (set-tm:wday obj val) (vector-set! obj 6 val))
880 (define (set-tm:yday obj val) (vector-set! obj 7 val))
881 (define (set-tm:isdst obj val) (vector-set! obj 8 val))
882 (define (set-tm:gmtoff obj val) (vector-set! obj 9 val))
883 (define (set-tm:zone obj val) (vector-set! obj 10 val))
885 (define (tms:clock obj) (vector-ref obj 0))
886 (define (tms:utime obj) (vector-ref obj 1))
887 (define (tms:stime obj) (vector-ref obj 2))
888 (define (tms:cutime obj) (vector-ref obj 3))
889 (define (tms:cstime obj) (vector-ref obj 4))
891 (define file-position ftell)
892 (define* (file-set-position port offset #:optional (whence SEEK_SET))
893 (seek port offset whence))
895 (define (move->fdes fd/port fd)
896 (cond ((integer? fd/port)
897 (dup->fdes fd/port fd)
901 (primitive-move->fdes fd/port fd)
902 (set-port-revealed! fd/port 1)
905 (define (release-port-handle port)
906 (let ((revealed (port-revealed port)))
908 (set-port-revealed! port (- revealed 1)))))
913 (fdopen (dup->fdes port/fd) mode))
914 ((port/fd mode new-fd)
915 (let ((port (fdopen (dup->fdes port/fd new-fd) mode)))
916 (set-port-revealed! port 1)
922 (dup->port port/fd "r"))
924 (dup->port port/fd "r" new-fd))))
929 (dup->port port/fd "w"))
931 (dup->port port/fd "w" new-fd))))
936 (if (integer? port/fd)
938 (dup->port port/fd (port-mode port/fd))))
940 (if (integer? port/fd)
941 (dup->fdes port/fd new-fd)
942 (dup->port port/fd (port-mode port/fd) new-fd)))))
944 (define (duplicate-port port modes)
945 (dup->port port modes))
947 (define (fdes->inport fdes)
948 (let loop ((rest-ports (fdes->ports fdes)))
949 (cond ((null? rest-ports)
950 (let ((result (fdopen fdes "r")))
951 (set-port-revealed! result 1)
953 ((input-port? (car rest-ports))
954 (set-port-revealed! (car rest-ports)
955 (+ (port-revealed (car rest-ports)) 1))
958 (loop (cdr rest-ports))))))
960 (define (fdes->outport fdes)
961 (let loop ((rest-ports (fdes->ports fdes)))
962 (cond ((null? rest-ports)
963 (let ((result (fdopen fdes "w")))
964 (set-port-revealed! result 1)
966 ((output-port? (car rest-ports))
967 (set-port-revealed! (car rest-ports)
968 (+ (port-revealed (car rest-ports)) 1))
971 (loop (cdr rest-ports))))))
973 (define (port->fdes port)
974 (set-port-revealed! port (+ (port-revealed port) 1))
977 (define (setenv name value)
979 (putenv (string-append name "=" value))
982 (define (unsetenv name)
983 "Remove the entry for NAME from the environment."
991 ;;; Here for backward compatability
993 (define scheme-file-suffix (lambda () ".scm"))
995 (define (in-vicinity vicinity file)
996 (let ((tail (let ((len (string-length vicinity)))
999 (string-ref vicinity (- len 1))))))
1000 (string-append vicinity
1009 ;;; {Help for scm_shell}
1011 ;;; The argument-processing code used by Guile-based shells generates
1012 ;;; Scheme code based on the argument list. This page contains help
1013 ;;; functions for the code it generates.
1016 (define (command-line) (program-arguments))
1018 ;; This is mostly for the internal use of the code generated by
1019 ;; scm_compile_shell_switches.
1021 (define (turn-on-debugging)
1022 (debug-enable 'debug)
1023 (debug-enable 'backtrace)
1024 (read-enable 'positions))
1026 (define (load-user-init)
1027 (let* ((home (or (getenv "HOME")
1028 (false-if-exception (passwd:dir (getpwuid (getuid))))
1029 "/")) ;; fallback for cygwin etc.
1030 (init-file (in-vicinity home ".guile")))
1031 (if (file-exists? init-file)
1032 (primitive-load init-file))))
1036 ;;; {The interpreter stack}
1039 ;; %stacks defined in stacks.c
1040 (define (%start-stack tag thunk)
1041 (let ((prompt-tag (make-prompt-tag "start-stack")))
1045 (with-fluids ((%stacks (acons tag prompt-tag
1046 (or (fluid-ref %stacks) '()))))
1049 (%start-stack tag (lambda () (apply k args)))))))
1050 (define-syntax start-stack
1053 (%start-stack tag (lambda () exp)))))
1057 ;;; {Loading by paths}
1060 ;;; Load a Scheme source file named NAME, searching for it in the
1061 ;;; directories listed in %load-path, and applying each of the file
1062 ;;; name extensions listed in %load-extensions.
1063 (define (load-from-path name)
1064 (start-stack 'load-stack
1065 (primitive-load-path name)))
1067 (define %load-verbosely #f)
1068 (define (assert-load-verbosity v) (set! %load-verbosely v))
1070 (define (%load-announce file)
1072 (with-output-to-port (current-error-port)
1075 (display "loading ")
1080 (set! %load-hook %load-announce)
1082 (define* (load name #:optional reader)
1083 ;; Returns the .go file corresponding to `name'. Does not search load
1084 ;; paths, only the fallback path. If the .go file is missing or out of
1085 ;; date, and autocompilation is enabled, will try autocompilation, just
1086 ;; as primitive-load-path does internally. primitive-load is
1087 ;; unaffected. Returns #f if autocompilation failed or was disabled.
1089 ;; NB: Unless we need to compile the file, this function should not cause
1090 ;; (system base compile) to be loaded up. For that reason compiled-file-name
1091 ;; partially duplicates functionality from (system base compile).
1092 (define (compiled-file-name canon-path)
1093 (and %compile-fallback-path
1095 %compile-fallback-path
1096 ;; no need for '/' separator here, canon-path is absolute
1098 (cond ((or (null? %load-compiled-extensions)
1099 (string-null? (car %load-compiled-extensions)))
1100 (warn "invalid %load-compiled-extensions"
1101 %load-compiled-extensions)
1103 (else (car %load-compiled-extensions))))))
1104 (define (fresh-compiled-file-name go-path)
1107 (let* ((scmstat (stat name))
1108 (gostat (stat go-path #f)))
1109 (if (and gostat (= (stat:mtime gostat) (stat:mtime scmstat)))
1113 (format (current-error-port)
1114 ";;; note: source file ~a\n;;; newer than compiled ~a\n"
1117 (%load-should-autocompile
1118 (%warn-autocompilation-enabled)
1119 (format (current-error-port) ";;; compiling ~a\n" name)
1120 ;; This use of @ is (ironically?) boot-safe, as modules have
1121 ;; not been booted yet, so the resolve-module call in psyntax
1122 ;; doesn't try to load a module, and compile-file will be
1123 ;; treated as a function, not a macro.
1124 (let ((cfn ((@ (system base compile) compile-file) name
1125 #:env (current-module))))
1126 (format (current-error-port) ";;; compiled ~a\n" cfn)
1130 (format (current-error-port)
1131 ";;; WARNING: compilation of ~a failed:\n;;; key ~a, throw_args ~s\n"
1134 (with-fluids ((current-reader reader))
1135 (let ((cfn (and=> (and=> (false-if-exception (canonicalize-path name))
1137 fresh-compiled-file-name)))
1140 (start-stack 'load-stack
1141 (primitive-load name))))))
1145 ;;; {Reader Extensions}
1147 ;;; Reader code for various "#c" forms.
1150 (define read-eval? (make-fluid))
1151 (fluid-set! read-eval? #f)
1152 (read-hash-extend #\.
1154 (if (fluid-ref read-eval?)
1155 (eval (read port) (interaction-environment))
1157 "#. read expansion found and read-eval? is #f."))))
1161 ;;; {Command Line Options}
1164 (define (get-option argv kw-opts kw-args return)
1167 (return #f #f argv))
1169 ((or (not (eq? #\- (string-ref (car argv) 0)))
1170 (eq? (string-length (car argv)) 1))
1171 (return 'normal-arg (car argv) (cdr argv)))
1173 ((eq? #\- (string-ref (car argv) 1))
1174 (let* ((kw-arg-pos (or (string-index (car argv) #\=)
1175 (string-length (car argv))))
1176 (kw (symbol->keyword (substring (car argv) 2 kw-arg-pos)))
1177 (kw-opt? (member kw kw-opts))
1178 (kw-arg? (member kw kw-args))
1179 (arg (or (and (not (eq? kw-arg-pos (string-length (car argv))))
1180 (substring (car argv)
1182 (string-length (car argv))))
1184 (begin (set! argv (cdr argv)) (car argv))))))
1185 (if (or kw-opt? kw-arg?)
1186 (return kw arg (cdr argv))
1187 (return 'usage-error kw (cdr argv)))))
1190 (let* ((char (substring (car argv) 1 2))
1191 (kw (symbol->keyword char)))
1194 ((member kw kw-opts)
1195 (let* ((rest-car (substring (car argv) 2 (string-length (car argv))))
1196 (new-argv (if (= 0 (string-length rest-car))
1198 (cons (string-append "-" rest-car) (cdr argv)))))
1199 (return kw #f new-argv)))
1201 ((member kw kw-args)
1202 (let* ((rest-car (substring (car argv) 2 (string-length (car argv))))
1203 (arg (if (= 0 (string-length rest-car))
1206 (new-argv (if (= 0 (string-length rest-car))
1209 (return kw arg new-argv)))
1211 (else (return 'usage-error kw argv)))))))
1213 (define (for-next-option proc argv kw-opts kw-args)
1214 (let loop ((argv argv))
1215 (get-option argv kw-opts kw-args
1216 (lambda (opt opt-arg argv)
1217 (and opt (proc opt opt-arg argv loop))))))
1219 (define (display-usage-report kw-desc)
1222 (or (eq? (car kw) #t)
1223 (eq? (car kw) 'else)
1224 (let* ((opt-desc kw)
1225 (help (cadr opt-desc))
1226 (opts (car opt-desc))
1227 (opts-proper (if (string? (car opts)) (cdr opts) opts))
1228 (arg-name (if (string? (car opts))
1229 (string-append "<" (car opts) ">")
1231 (left-part (string-append
1232 (with-output-to-string
1234 (map (lambda (x) (display (keyword->symbol x)) (display " "))
1237 (middle-part (if (and (< (string-length left-part) 30)
1238 (< (string-length help) 40))
1239 (make-string (- 30 (string-length left-part)) #\ )
1242 (display middle-part)
1249 (define (transform-usage-lambda cases)
1250 (let* ((raw-usage (delq! 'else (map car cases)))
1251 (usage-sans-specials (map (lambda (x)
1252 (or (and (not (list? x)) x)
1253 (and (symbol? (car x)) #t)
1254 (and (boolean? (car x)) #t)
1257 (usage-desc (delq! #t usage-sans-specials))
1258 (kw-desc (map car usage-desc))
1259 (kw-opts (apply append (map (lambda (x) (and (not (string? (car x))) x)) kw-desc)))
1260 (kw-args (apply append (map (lambda (x) (and (string? (car x)) (cdr x))) kw-desc)))
1261 (transmogrified-cases (map (lambda (case)
1262 (cons (let ((opts (car case)))
1263 (if (or (boolean? opts) (eq? 'else opts))
1266 ((symbol? (car opts)) opts)
1267 ((boolean? (car opts)) opts)
1268 ((string? (caar opts)) (cdar opts))
1269 (else (car opts)))))
1272 `(let ((%display-usage (lambda () (display-usage-report ',usage-desc))))
1274 (let %next-arg ((%argv %argv))
1278 (lambda (%opt %arg %new-argv)
1280 ,@ transmogrified-cases))))))))
1285 ;;; {Low Level Modules}
1287 ;;; These are the low level data structures for modules.
1289 ;;; Every module object is of the type 'module-type', which is a record
1290 ;;; consisting of the following members:
1292 ;;; - eval-closure: the function that defines for its module the strategy that
1293 ;;; shall be followed when looking up symbols in the module.
1295 ;;; An eval-closure is a function taking two arguments: the symbol to be
1296 ;;; looked up and a boolean value telling whether a binding for the symbol
1297 ;;; should be created if it does not exist yet. If the symbol lookup
1298 ;;; succeeded (either because an existing binding was found or because a new
1299 ;;; binding was created), a variable object representing the binding is
1300 ;;; returned. Otherwise, the value #f is returned. Note that the eval
1301 ;;; closure does not take the module to be searched as an argument: During
1302 ;;; construction of the eval-closure, the eval-closure has to store the
1303 ;;; module it belongs to in its environment. This means, that any
1304 ;;; eval-closure can belong to only one module.
1306 ;;; The eval-closure of a module can be defined arbitrarily. However, three
1307 ;;; special cases of eval-closures are to be distinguished: During startup
1308 ;;; the module system is not yet activated. In this phase, no modules are
1309 ;;; defined and all bindings are automatically stored by the system in the
1310 ;;; pre-modules-obarray. Since no eval-closures exist at this time, the
1311 ;;; functions which require an eval-closure as their argument need to be
1312 ;;; passed the value #f.
1314 ;;; The other two special cases of eval-closures are the
1315 ;;; standard-eval-closure and the standard-interface-eval-closure. Both
1316 ;;; behave equally for the case that no new binding is to be created. The
1317 ;;; difference between the two comes in, when the boolean argument to the
1318 ;;; eval-closure indicates that a new binding shall be created if it is not
1321 ;;; Given that no new binding shall be created, both standard eval-closures
1322 ;;; define the following standard strategy of searching bindings in the
1323 ;;; module: First, the module's obarray is searched for the symbol. Second,
1324 ;;; if no binding for the symbol was found in the module's obarray, the
1325 ;;; module's binder procedure is exececuted. If this procedure did not
1326 ;;; return a binding for the symbol, the modules referenced in the module's
1327 ;;; uses list are recursively searched for a binding of the symbol. If the
1328 ;;; binding can not be found in these modules also, the symbol lookup has
1331 ;;; If a new binding shall be created, the standard-interface-eval-closure
1332 ;;; immediately returns indicating failure. That is, it does not even try
1333 ;;; to look up the symbol. In contrast, the standard-eval-closure would
1334 ;;; first search the obarray, and if no binding was found there, would
1335 ;;; create a new binding in the obarray, therefore not calling the binder
1336 ;;; procedure or searching the modules in the uses list.
1338 ;;; The explanation of the following members obarray, binder and uses
1339 ;;; assumes that the symbol lookup follows the strategy that is defined in
1340 ;;; the standard-eval-closure and the standard-interface-eval-closure.
1342 ;;; - obarray: a hash table that maps symbols to variable objects. In this
1343 ;;; hash table, the definitions are found that are local to the module (that
1344 ;;; is, not imported from other modules). When looking up bindings in the
1345 ;;; module, this hash table is searched first.
1347 ;;; - binder: either #f or a function taking a module and a symbol argument.
1348 ;;; If it is a function it is called after the obarray has been
1349 ;;; unsuccessfully searched for a binding. It then can provide bindings
1350 ;;; that would otherwise not be found locally in the module.
1352 ;;; - uses: a list of modules from which non-local bindings can be inherited.
1353 ;;; These modules are the third place queried for bindings after the obarray
1354 ;;; has been unsuccessfully searched and the binder function did not deliver
1355 ;;; a result either.
1357 ;;; - transformer: either #f or a function taking a scheme expression as
1358 ;;; delivered by read. If it is a function, it will be called to perform
1359 ;;; syntax transformations (e. g. makro expansion) on the given scheme
1360 ;;; expression. The output of the transformer function will then be passed
1361 ;;; to Guile's internal memoizer. This means that the output must be valid
1362 ;;; scheme code. The only exception is, that the output may make use of the
1363 ;;; syntax extensions provided to identify the modules that a binding
1366 ;;; - name: the name of the module. This is used for all kinds of printing
1367 ;;; outputs. In certain places the module name also serves as a way of
1368 ;;; identification. When adding a module to the uses list of another
1369 ;;; module, it is made sure that the new uses list will not contain two
1370 ;;; modules of the same name.
1372 ;;; - kind: classification of the kind of module. The value is (currently?)
1373 ;;; only used for printing. It has no influence on how a module is treated.
1374 ;;; Currently the following values are used when setting the module kind:
1375 ;;; 'module, 'directory, 'interface, 'custom-interface. If no explicit kind
1376 ;;; is set, it defaults to 'module.
1378 ;;; - duplicates-handlers: a list of procedures that get called to make a
1379 ;;; choice between two duplicate bindings when name clashes occur. See the
1380 ;;; `duplicate-handlers' global variable below.
1382 ;;; - observers: a list of procedures that get called when the module is
1385 ;;; - weak-observers: a weak-key hash table of procedures that get called
1386 ;;; when the module is modified. See `module-observe-weak' for details.
1388 ;;; In addition, the module may (must?) contain a binding for
1389 ;;; `%module-public-interface'. This variable should be bound to a module
1390 ;;; representing the exported interface of a module. See the
1391 ;;; `module-public-interface' and `module-export!' procedures.
1393 ;;; !!! warning: The interface to lazy binder procedures is going
1394 ;;; to be changed in an incompatible way to permit all the basic
1395 ;;; module ops to be virtualized.
1397 ;;; (make-module size use-list lazy-binding-proc) => module
1398 ;;; module-{obarray,uses,binder}[|-set!]
1399 ;;; (module? obj) => [#t|#f]
1400 ;;; (module-locally-bound? module symbol) => [#t|#f]
1401 ;;; (module-bound? module symbol) => [#t|#f]
1402 ;;; (module-symbol-locally-interned? module symbol) => [#t|#f]
1403 ;;; (module-symbol-interned? module symbol) => [#t|#f]
1404 ;;; (module-local-variable module symbol) => [#<variable ...> | #f]
1405 ;;; (module-variable module symbol) => [#<variable ...> | #f]
1406 ;;; (module-symbol-binding module symbol opt-value)
1407 ;;; => [ <obj> | opt-value | an error occurs ]
1408 ;;; (module-make-local-var! module symbol) => #<variable...>
1409 ;;; (module-add! module symbol var) => unspecified
1410 ;;; (module-remove! module symbol) => unspecified
1411 ;;; (module-for-each proc module) => unspecified
1412 ;;; (make-scm-module) => module ; a lazy copy of the symhash module
1413 ;;; (set-current-module module) => unspecified
1414 ;;; (current-module) => #<module...>
1420 ;;; {Printing Modules}
1423 ;; This is how modules are printed. You can re-define it.
1424 (define (%print-module mod port)
1426 (display (or (module-kind mod) "module") port)
1428 (display (module-name mod) port)
1430 (display (number->string (object-address mod) 16) port)
1434 ;; Locally extend the syntax to allow record accessors to be defined at
1435 ;; compile-time. Cache the rtd locally to the constructor, the getters and
1436 ;; the setters, in order to allow for redefinition of the record type; not
1437 ;; relevant in the case of modules, but perhaps if we make this public, it
1440 ((define-record-type
1442 (define (make-id scope . fragments)
1443 (datum->syntax #'scope
1444 (apply symbol-append
1446 (if (symbol? x) x (syntax->datum x)))
1449 (define (getter rtd type-name field slot)
1450 #`(define #,(make-id rtd type-name '- field)
1452 (lambda (#,type-name)
1453 (if (eq? (struct-vtable #,type-name) rtd)
1454 (struct-ref #,type-name #,slot)
1455 (%record-type-error rtd #,type-name))))))
1457 (define (setter rtd type-name field slot)
1458 #`(define #,(make-id rtd 'set- type-name '- field '!)
1460 (lambda (#,type-name val)
1461 (if (eq? (struct-vtable #,type-name) rtd)
1462 (struct-set! #,type-name #,slot val)
1463 (%record-type-error rtd #,type-name))))))
1465 (define (accessors rtd type-name fields n exp)
1466 (syntax-case fields ()
1468 (((field #:no-accessors) field* ...) (identifier? #'field)
1469 (accessors rtd type-name #'(field* ...) (1+ n)
1471 (((field #:no-setter) field* ...) (identifier? #'field)
1472 (accessors rtd type-name #'(field* ...) (1+ n)
1474 #,(getter rtd type-name #'field n))))
1475 (((field #:no-getter) field* ...) (identifier? #'field)
1476 (accessors rtd type-name #'(field* ...) (1+ n)
1478 #,(setter rtd type-name #'field n))))
1479 ((field field* ...) (identifier? #'field)
1480 (accessors rtd type-name #'(field* ...) (1+ n)
1482 #,(getter rtd type-name #'field n)
1483 #,(setter rtd type-name #'field n))))))
1485 (define (predicate rtd type-name fields exp)
1487 rtd type-name fields 0
1490 (define (#,(make-id rtd type-name '?) obj)
1491 (and (struct? obj) (eq? (struct-vtable obj) #,rtd))))))
1493 (define (field-list fields)
1494 (syntax-case fields ()
1496 (((f . opts) . rest) (identifier? #'f)
1497 (cons #'f (field-list #'rest)))
1498 ((f . rest) (identifier? #'f)
1499 (cons #'f (field-list #'rest)))))
1501 (define (constructor rtd type-name fields exp)
1502 (let ((ctor (make-id rtd type-name '-constructor))
1503 (args (field-list fields)))
1504 (predicate rtd type-name fields
1509 (make-struct rtd 0 #,@args))))
1510 (struct-set! #,rtd (+ vtable-offset-user 2)
1513 (define (type type-name printer fields)
1514 (define (make-layout)
1515 (let lp ((fields fields) (slots '()))
1516 (syntax-case fields ()
1517 (() (datum->syntax #'here
1519 (apply string-append slots))))
1520 ((_ . rest) (lp #'rest (cons "pw" slots))))))
1522 (let ((rtd (make-id type-name type-name '-type)))
1523 (constructor rtd type-name fields
1526 (make-struct record-type-vtable 0
1530 '#,(field-list fields)))
1531 (set-struct-vtable-name! #,rtd '#,type-name)))))
1534 ((_ type-name printer (field ...))
1535 (type #'type-name #'printer #'(field ...)))))))
1539 ;; A module is characterized by an obarray in which local symbols
1540 ;; are interned, a list of modules, "uses", from which non-local
1541 ;; bindings can be inherited, and an optional lazy-binder which
1542 ;; is a (CLOSURE module symbol) which, as a last resort, can provide
1543 ;; bindings that would otherwise not be found locally in the module.
1545 ;; NOTE: If you change the set of fields or their order, you also need to
1546 ;; change the constants in libguile/modules.h.
1548 ;; NOTE: The getter `module-eval-closure' is used in libguile/modules.c.
1549 ;; NOTE: The getter `module-transfomer' is defined libguile/modules.c.
1550 ;; NOTE: The getter `module-name' is defined later, due to boot reasons.
1551 ;; NOTE: The getter `module-public-interface' is used in libguile/modules.c.
1553 (define-record-type module
1554 (lambda (obj port) (%print-module obj port))
1559 (transformer #:no-getter)
1563 (import-obarray #:no-setter)
1565 (weak-observers #:no-setter)
1573 ;; make-module &opt size uses binder
1575 ;; Create a new module, perhaps with a particular size of obarray,
1576 ;; initial uses list, or binding procedure.
1581 (define (parse-arg index default)
1582 (if (> (length args) index)
1583 (list-ref args index)
1586 (define %default-import-size
1587 ;; Typical number of imported bindings actually used by a module.
1590 (if (> (length args) 3)
1591 (error "Too many args to make-module." args))
1593 (let ((size (parse-arg 0 31))
1594 (uses (parse-arg 1 '()))
1595 (binder (parse-arg 2 #f)))
1597 (if (not (integer? size))
1598 (error "Illegal size to make-module." size))
1599 (if (not (and (list? uses)
1600 (and-map module? uses)))
1601 (error "Incorrect use list." uses))
1602 (if (and binder (not (procedure? binder)))
1604 "Lazy-binder expected to be a procedure or #f." binder))
1606 (let ((module (module-constructor (make-hash-table size)
1607 uses binder #f macroexpand
1609 (make-hash-table %default-import-size)
1611 (make-weak-key-hash-table 31) #f
1612 (make-hash-table 7) #f #f #f)))
1614 ;; We can't pass this as an argument to module-constructor,
1615 ;; because we need it to close over a pointer to the module
1617 (set-module-eval-closure! module (standard-eval-closure module))
1624 ;;; {Observer protocol}
1627 (define (module-observe module proc)
1628 (set-module-observers! module (cons proc (module-observers module)))
1631 (define* (module-observe-weak module observer-id #:optional (proc observer-id))
1632 ;; Register PROC as an observer of MODULE under name OBSERVER-ID (which can
1633 ;; be any Scheme object). PROC is invoked and passed MODULE any time
1634 ;; MODULE is modified. PROC gets unregistered when OBSERVER-ID gets GC'd
1635 ;; (thus, it is never unregistered if OBSERVER-ID is an immediate value,
1638 ;; The two-argument version is kept for backward compatibility: when called
1639 ;; with two arguments, the observer gets unregistered when closure PROC
1640 ;; gets GC'd (making it impossible to use an anonymous lambda for PROC).
1641 (hashq-set! (module-weak-observers module) observer-id proc))
1643 (define (module-unobserve token)
1644 (let ((module (car token))
1647 (hash-remove! (module-weak-observers module) id)
1648 (set-module-observers! module (delq1! id (module-observers module)))))
1651 (define module-defer-observers #f)
1652 (define module-defer-observers-mutex (make-mutex 'recursive))
1653 (define module-defer-observers-table (make-hash-table))
1655 (define (module-modified m)
1656 (if module-defer-observers
1657 (hash-set! module-defer-observers-table m #t)
1658 (module-call-observers m)))
1660 ;;; This function can be used to delay calls to observers so that they
1661 ;;; can be called once only in the face of massive updating of modules.
1663 (define (call-with-deferred-observers thunk)
1666 (lock-mutex module-defer-observers-mutex)
1667 (set! module-defer-observers #t))
1670 (set! module-defer-observers #f)
1671 (hash-for-each (lambda (m dummy)
1672 (module-call-observers m))
1673 module-defer-observers-table)
1674 (hash-clear! module-defer-observers-table)
1675 (unlock-mutex module-defer-observers-mutex))))
1677 (define (module-call-observers m)
1678 (for-each (lambda (proc) (proc m)) (module-observers m))
1680 ;; We assume that weak observers don't (un)register themselves as they are
1681 ;; called since this would preclude proper iteration over the hash table
1683 (hash-for-each (lambda (id proc) (proc m)) (module-weak-observers m)))
1687 ;;; {Module Searching in General}
1689 ;;; We sometimes want to look for properties of a symbol
1690 ;;; just within the obarray of one module. If the property
1691 ;;; holds, then it is said to hold ``locally'' as in, ``The symbol
1692 ;;; DISPLAY is locally rebound in the module `safe-guile'.''
1695 ;;; Other times, we want to test for a symbol property in the obarray
1696 ;;; of M and, if it is not found there, try each of the modules in the
1697 ;;; uses list of M. This is the normal way of testing for some
1698 ;;; property, so we state these properties without qualification as
1699 ;;; in: ``The symbol 'fnord is interned in module M because it is
1700 ;;; interned locally in module M2 which is a member of the uses list
1704 ;; module-search fn m
1706 ;; return the first non-#f result of FN applied to M and then to
1707 ;; the modules in the uses of m, and so on recursively. If all applications
1708 ;; return #f, then so does this function.
1710 (define (module-search fn m v)
1713 (or (module-search fn (car pos) v)
1716 (loop (module-uses m))))
1719 ;;; {Is a symbol bound in a module?}
1721 ;;; Symbol S in Module M is bound if S is interned in M and if the binding
1722 ;;; of S in M has been set to some well-defined value.
1725 ;; module-locally-bound? module symbol
1727 ;; Is a symbol bound (interned and defined) locally in a given module?
1729 (define (module-locally-bound? m v)
1730 (let ((var (module-local-variable m v)))
1732 (variable-bound? var))))
1734 ;; module-bound? module symbol
1736 ;; Is a symbol bound (interned and defined) anywhere in a given module
1739 (define (module-bound? m v)
1740 (let ((var (module-variable m v)))
1742 (variable-bound? var))))
1744 ;;; {Is a symbol interned in a module?}
1746 ;;; Symbol S in Module M is interned if S occurs in
1747 ;;; of S in M has been set to some well-defined value.
1749 ;;; It is possible to intern a symbol in a module without providing
1750 ;;; an initial binding for the corresponding variable. This is done
1752 ;;; (module-add! module symbol (make-undefined-variable))
1754 ;;; In that case, the symbol is interned in the module, but not
1755 ;;; bound there. The unbound symbol shadows any binding for that
1756 ;;; symbol that might otherwise be inherited from a member of the uses list.
1759 (define (module-obarray-get-handle ob key)
1760 ((if (symbol? key) hashq-get-handle hash-get-handle) ob key))
1762 (define (module-obarray-ref ob key)
1763 ((if (symbol? key) hashq-ref hash-ref) ob key))
1765 (define (module-obarray-set! ob key val)
1766 ((if (symbol? key) hashq-set! hash-set!) ob key val))
1768 (define (module-obarray-remove! ob key)
1769 ((if (symbol? key) hashq-remove! hash-remove!) ob key))
1771 ;; module-symbol-locally-interned? module symbol
1773 ;; is a symbol interned (not neccessarily defined) locally in a given module
1774 ;; or its uses? Interned symbols shadow inherited bindings even if
1775 ;; they are not themselves bound to a defined value.
1777 (define (module-symbol-locally-interned? m v)
1778 (not (not (module-obarray-get-handle (module-obarray m) v))))
1780 ;; module-symbol-interned? module symbol
1782 ;; is a symbol interned (not neccessarily defined) anywhere in a given module
1783 ;; or its uses? Interned symbols shadow inherited bindings even if
1784 ;; they are not themselves bound to a defined value.
1786 (define (module-symbol-interned? m v)
1787 (module-search module-symbol-locally-interned? m v))
1790 ;;; {Mapping modules x symbols --> variables}
1793 ;; module-local-variable module symbol
1794 ;; return the local variable associated with a MODULE and SYMBOL.
1796 ;;; This function is very important. It is the only function that can
1797 ;;; return a variable from a module other than the mutators that store
1798 ;;; new variables in modules. Therefore, this function is the location
1799 ;;; of the "lazy binder" hack.
1801 ;;; If symbol is defined in MODULE, and if the definition binds symbol
1802 ;;; to a variable, return that variable object.
1804 ;;; If the symbols is not found at first, but the module has a lazy binder,
1805 ;;; then try the binder.
1807 ;;; If the symbol is not found at all, return #f.
1809 ;;; (This is now written in C, see `modules.c'.)
1812 ;;; {Mapping modules x symbols --> bindings}
1814 ;;; These are similar to the mapping to variables, except that the
1815 ;;; variable is dereferenced.
1818 ;; module-symbol-binding module symbol opt-value
1820 ;; return the binding of a variable specified by name within
1821 ;; a given module, signalling an error if the variable is unbound.
1822 ;; If the OPT-VALUE is passed, then instead of signalling an error,
1823 ;; return OPT-VALUE.
1825 (define (module-symbol-local-binding m v . opt-val)
1826 (let ((var (module-local-variable m v)))
1827 (if (and var (variable-bound? var))
1829 (if (not (null? opt-val))
1831 (error "Locally unbound variable." v)))))
1833 ;; module-symbol-binding module symbol opt-value
1835 ;; return the binding of a variable specified by name within
1836 ;; a given module, signalling an error if the variable is unbound.
1837 ;; If the OPT-VALUE is passed, then instead of signalling an error,
1838 ;; return OPT-VALUE.
1840 (define (module-symbol-binding m v . opt-val)
1841 (let ((var (module-variable m v)))
1842 (if (and var (variable-bound? var))
1844 (if (not (null? opt-val))
1846 (error "Unbound variable." v)))))
1851 ;;; {Adding Variables to Modules}
1854 ;; module-make-local-var! module symbol
1856 ;; ensure a variable for V in the local namespace of M.
1857 ;; If no variable was already there, then create a new and uninitialzied
1860 ;; This function is used in modules.c.
1862 (define (module-make-local-var! m v)
1863 (or (let ((b (module-obarray-ref (module-obarray m) v)))
1866 ;; Mark as modified since this function is called when
1867 ;; the standard eval closure defines a binding
1871 ;; Create a new local variable.
1872 (let ((local-var (make-undefined-variable)))
1873 (module-add! m v local-var)
1876 ;; module-ensure-local-variable! module symbol
1878 ;; Ensure that there is a local variable in MODULE for SYMBOL. If
1879 ;; there is no binding for SYMBOL, create a new uninitialized
1880 ;; variable. Return the local variable.
1882 (define (module-ensure-local-variable! module symbol)
1883 (or (module-local-variable module symbol)
1884 (let ((var (make-undefined-variable)))
1885 (module-add! module symbol var)
1888 ;; module-add! module symbol var
1890 ;; ensure a particular variable for V in the local namespace of M.
1892 (define (module-add! m v var)
1893 (if (not (variable? var))
1894 (error "Bad variable to module-add!" var))
1895 (module-obarray-set! (module-obarray m) v var)
1896 (module-modified m))
1900 ;; make sure that a symbol is undefined in the local namespace of M.
1902 (define (module-remove! m v)
1903 (module-obarray-remove! (module-obarray m) v)
1904 (module-modified m))
1906 (define (module-clear! m)
1907 (hash-clear! (module-obarray m))
1908 (module-modified m))
1910 ;; MODULE-FOR-EACH -- exported
1912 ;; Call PROC on each symbol in MODULE, with arguments of (SYMBOL VARIABLE).
1914 (define (module-for-each proc module)
1915 (hash-for-each proc (module-obarray module)))
1917 (define (module-map proc module)
1918 (hash-map->list proc (module-obarray module)))
1922 ;; Modules exist in a separate namespace from values, because you generally do
1923 ;; not want the name of a submodule, which you might not even use, to collide
1924 ;; with local variables that happen to be named the same as the submodule.
1926 (define (module-ref-submodule module name)
1927 (or (hashq-ref (module-submodules module) name)
1928 (and (module-submodule-binder module)
1929 ((module-submodule-binder module) module name))))
1931 (define (module-define-submodule! module name submodule)
1932 (hashq-set! (module-submodules module) name submodule))
1936 ;;; {Low Level Bootstrapping}
1941 ;; A root module uses the pre-modules-obarray as its obarray. This
1942 ;; special obarray accumulates all bindings that have been established
1943 ;; before the module system is fully booted.
1945 ;; (The obarray continues to be used by code that has been closed over
1946 ;; before the module system has been booted.)
1948 (define (make-root-module)
1949 (let ((m (make-module 0)))
1950 (set-module-obarray! m (%get-pre-modules-obarray))
1955 ;; The root interface is a module that uses the same obarray as the
1956 ;; root module. It does not allow new definitions, tho.
1958 (define (make-scm-module)
1959 (let ((m (make-module 0)))
1960 (set-module-obarray! m (%get-pre-modules-obarray))
1961 (set-module-eval-closure! m (standard-interface-eval-closure m))
1967 ;;; {Module-based Loading}
1970 (define (save-module-excursion thunk)
1971 (let ((inner-module (current-module))
1973 (dynamic-wind (lambda ()
1974 (set! outer-module (current-module))
1975 (set-current-module inner-module)
1976 (set! inner-module #f))
1979 (set! inner-module (current-module))
1980 (set-current-module outer-module)
1981 (set! outer-module #f)))))
1983 (define basic-load load)
1985 (define* (load-module filename #:optional reader)
1986 (save-module-excursion
1988 (let ((oldname (and (current-load-port)
1989 (port-filename (current-load-port)))))
1990 (basic-load (if (and oldname
1991 (> (string-length filename) 0)
1992 (not (char=? (string-ref filename 0) #\/))
1993 (not (string=? (dirname oldname) ".")))
1994 (string-append (dirname oldname) "/" filename)
2001 ;;; {MODULE-REF -- exported}
2004 ;; Returns the value of a variable called NAME in MODULE or any of its
2005 ;; used modules. If there is no such variable, then if the optional third
2006 ;; argument DEFAULT is present, it is returned; otherwise an error is signaled.
2008 (define (module-ref module name . rest)
2009 (let ((variable (module-variable module name)))
2010 (if (and variable (variable-bound? variable))
2011 (variable-ref variable)
2013 (error "No variable named" name 'in module)
2014 (car rest) ; default value
2017 ;; MODULE-SET! -- exported
2019 ;; Sets the variable called NAME in MODULE (or in a module that MODULE uses)
2020 ;; to VALUE; if there is no such variable, an error is signaled.
2022 (define (module-set! module name value)
2023 (let ((variable (module-variable module name)))
2025 (variable-set! variable value)
2026 (error "No variable named" name 'in module))))
2028 ;; MODULE-DEFINE! -- exported
2030 ;; Sets the variable called NAME in MODULE to VALUE; if there is no such
2031 ;; variable, it is added first.
2033 (define (module-define! module name value)
2034 (let ((variable (module-local-variable module name)))
2037 (variable-set! variable value)
2038 (module-modified module))
2039 (let ((variable (make-variable value)))
2040 (module-add! module name variable)))))
2042 ;; MODULE-DEFINED? -- exported
2044 ;; Return #t iff NAME is defined in MODULE (or in a module that MODULE
2047 (define (module-defined? module name)
2048 (let ((variable (module-variable module name)))
2049 (and variable (variable-bound? variable))))
2051 ;; MODULE-USE! module interface
2053 ;; Add INTERFACE to the list of interfaces used by MODULE.
2055 (define (module-use! module interface)
2056 (if (not (or (eq? module interface)
2057 (memq interface (module-uses module))))
2059 ;; Newly used modules must be appended rather than consed, so that
2060 ;; `module-variable' traverses the use list starting from the first
2062 (set-module-uses! module
2063 (append (filter (lambda (m)
2065 (equal? (module-name m)
2066 (module-name interface))))
2067 (module-uses module))
2069 (hash-clear! (module-import-obarray module))
2070 (module-modified module))))
2072 ;; MODULE-USE-INTERFACES! module interfaces
2074 ;; Same as MODULE-USE! but add multiple interfaces and check for duplicates
2076 (define (module-use-interfaces! module interfaces)
2077 (set-module-uses! module
2078 (append (module-uses module) interfaces))
2079 (hash-clear! (module-import-obarray module))
2080 (module-modified module))
2084 ;;; {Recursive Namespaces}
2086 ;;; A hierarchical namespace emerges if we consider some module to be
2087 ;;; root, and submodules of that module to be nested namespaces.
2089 ;;; The routines here manage variable names in hierarchical namespace.
2090 ;;; Each variable name is a list of elements, looked up in successively nested
2093 ;;; (nested-ref some-root-module '(foo bar baz))
2094 ;;; => <value of a variable named baz in the submodule bar of
2095 ;;; the submodule foo of some-root-module>
2100 ;;; ;; a-root is a module
2101 ;;; ;; name is a list of symbols
2103 ;;; nested-ref a-root name
2104 ;;; nested-set! a-root name val
2105 ;;; nested-define! a-root name val
2106 ;;; nested-remove! a-root name
2108 ;;; These functions manipulate values in namespaces. For referencing the
2109 ;;; namespaces themselves, use the following:
2111 ;;; nested-ref-module a-root name
2112 ;;; nested-define-module! a-root name mod
2114 ;;; (current-module) is a natural choice for a root so for convenience there are
2117 ;;; local-ref name == nested-ref (current-module) name
2118 ;;; local-set! name val == nested-set! (current-module) name val
2119 ;;; local-define name val == nested-define! (current-module) name val
2120 ;;; local-remove name == nested-remove! (current-module) name
2121 ;;; local-ref-module name == nested-ref-module (current-module) name
2122 ;;; local-define-module! name m == nested-define-module! (current-module) name m
2126 (define (nested-ref root names)
2129 (let loop ((cur root)
2133 (module-ref cur head #f)
2134 (let ((cur (module-ref-submodule cur head)))
2136 (loop cur (car tail) (cdr tail))))))))
2138 (define (nested-set! root names val)
2139 (let loop ((cur root)
2143 (module-set! cur head val)
2144 (let ((cur (module-ref-submodule cur head)))
2146 (error "failed to resolve module" names)
2147 (loop cur (car tail) (cdr tail)))))))
2149 (define (nested-define! root names val)
2150 (let loop ((cur root)
2154 (module-define! cur head val)
2155 (let ((cur (module-ref-submodule cur head)))
2157 (error "failed to resolve module" names)
2158 (loop cur (car tail) (cdr tail)))))))
2160 (define (nested-remove! root names)
2161 (let loop ((cur root)
2165 (module-remove! cur head)
2166 (let ((cur (module-ref-submodule cur head)))
2168 (error "failed to resolve module" names)
2169 (loop cur (car tail) (cdr tail)))))))
2172 (define (nested-ref-module root names)
2173 (let loop ((cur root)
2177 (let ((cur (module-ref-submodule cur (car names))))
2179 (loop cur (cdr names)))))))
2181 (define (nested-define-module! root names module)
2183 (error "can't redefine root module" root module)
2184 (let loop ((cur root)
2188 (module-define-submodule! cur head module)
2189 (let ((cur (or (module-ref-submodule cur head)
2190 (let ((m (make-module 31)))
2191 (set-module-kind! m 'directory)
2192 (set-module-name! m (append (module-name cur)
2194 (module-define-submodule! cur head m)
2196 (loop cur (car tail) (cdr tail)))))))
2199 (define (local-ref names) (nested-ref (current-module) names))
2200 (define (local-set! names val) (nested-set! (current-module) names val))
2201 (define (local-define names val) (nested-define! (current-module) names val))
2202 (define (local-remove names) (nested-remove! (current-module) names))
2203 (define (local-ref-module names) (nested-ref-module (current-module) names))
2204 (define (local-define-module names mod) (nested-define-module! (current-module) names mod))
2210 ;;; {The (guile) module}
2212 ;;; The standard module, which has the core Guile bindings. Also called the
2213 ;;; "root module", as it is imported by many other modules, but it is not
2214 ;;; necessarily the root of anything; and indeed, the module named '() might be
2215 ;;; better thought of as a root.
2218 (define (set-system-module! m s)
2219 (set-procedure-property! (module-eval-closure m) 'system-module s))
2220 (define the-root-module (make-root-module))
2221 (define the-scm-module (make-scm-module))
2222 (set-module-public-interface! the-root-module the-scm-module)
2223 (set-module-name! the-root-module '(guile))
2224 (set-module-name! the-scm-module '(guile))
2225 (set-module-kind! the-scm-module 'interface)
2226 (set-system-module! the-root-module #t)
2227 (set-system-module! the-scm-module #t)
2232 ;; Now that we have a root module, even though modules aren't fully booted,
2233 ;; expand the definition of resolve-module.
2235 (define (resolve-module name . args)
2236 (if (equal? name '(guile))
2238 (error "unexpected module to resolve during module boot" name)))
2240 ;; Cheat. These bindings are needed by modules.c, but we don't want
2241 ;; to move their real definition here because that would be unnatural.
2243 (define process-define-module #f)
2244 (define process-use-modules #f)
2245 (define module-export! #f)
2246 (define default-duplicate-binding-procedures #f)
2248 ;; This boots the module system. All bindings needed by modules.c
2249 ;; must have been defined by now.
2251 (set-current-module the-root-module)
2256 ;; Now that modules are booted, give module-name its final definition.
2259 (let ((accessor (record-accessor module-type 'name)))
2262 (let ((name (list (gensym))))
2263 ;; Name MOD and bind it in the module root so that it's visible to
2264 ;; `resolve-module'. This is important as `psyntax' stores module
2265 ;; names and relies on being able to `resolve-module' them.
2266 (set-module-name! mod name)
2267 (nested-define-module! (resolve-module '() #f) name mod)
2270 (define (make-modules-in module name)
2271 (or (nested-ref-module module name)
2272 (let ((m (make-module 31)))
2273 (set-module-kind! m 'directory)
2274 (set-module-name! m (append (module-name module) name))
2275 (nested-define-module! module name m)
2278 (define (beautify-user-module! module)
2279 (let ((interface (module-public-interface module)))
2280 (if (or (not interface)
2281 (eq? interface module))
2282 (let ((interface (make-module 31)))
2283 (set-module-name! interface (module-name module))
2284 (set-module-version! interface (module-version module))
2285 (set-module-kind! interface 'interface)
2286 (set-module-public-interface! module interface))))
2287 (if (and (not (memq the-scm-module (module-uses module)))
2288 (not (eq? module the-root-module)))
2289 ;; Import the default set of bindings (from the SCM module) in MODULE.
2290 (module-use! module the-scm-module)))
2292 (define (version-matches? version-ref target)
2293 (define (any pred lst)
2294 (and (not (null? lst)) (or (pred (car lst)) (any pred (cdr lst)))))
2295 (define (every pred lst)
2296 (or (null? lst) (and (pred (car lst)) (every pred (cdr lst)))))
2297 (define (sub-versions-match? v-refs t)
2298 (define (sub-version-matches? v-ref t)
2299 (define (curried-sub-version-matches? v)
2300 (sub-version-matches? v t))
2301 (cond ((number? v-ref) (eqv? v-ref t))
2303 (let ((cv (car v-ref)))
2304 (cond ((eq? cv '>=) (>= t (cadr v-ref)))
2305 ((eq? cv '<=) (<= t (cadr v-ref)))
2307 (every curried-sub-version-matches? (cdr v-ref)))
2309 (any curried-sub-version-matches? (cdr v-ref)))
2310 ((eq? cv 'not) (not (sub-version-matches? (cadr v-ref) t)))
2311 (else (error "Incompatible sub-version reference" cv)))))
2312 (else (error "Incompatible sub-version reference" v-ref))))
2314 (and (not (null? t))
2315 (sub-version-matches? (car v-refs) (car t))
2316 (sub-versions-match? (cdr v-refs) (cdr t)))))
2317 (define (curried-version-matches? v)
2318 (version-matches? v target))
2319 (or (null? version-ref)
2320 (let ((cv (car version-ref)))
2321 (cond ((eq? cv 'and) (every curried-version-matches? (cdr version-ref)))
2322 ((eq? cv 'or) (any curried-version-matches? (cdr version-ref)))
2323 ((eq? cv 'not) (not (version-matches? (cadr version-ref) target)))
2324 (else (sub-versions-match? version-ref target))))))
2326 (define (find-versioned-module dir-hint name version-ref roots)
2327 (define (subdir-pair-less pair1 pair2)
2328 (define (numlist-less lst1 lst2)
2330 (and (not (null? lst1))
2331 (cond ((> (car lst1) (car lst2)) #t)
2332 ((< (car lst1) (car lst2)) #f)
2333 (else (numlist-less (cdr lst1) (cdr lst2)))))))
2334 (not (numlist-less (car pair2) (car pair1))))
2335 (define (match-version-and-file pair)
2336 (and (version-matches? version-ref (car pair))
2338 (filter (lambda (file)
2339 (let ((s (false-if-exception (stat file))))
2340 (and s (eq? (stat:type s) 'regular))))
2342 (string-append (cdr pair) name ext))
2343 %load-extensions))))
2344 (and (not (null? filenames))
2345 (cons (car pair) (car filenames))))))
2347 (define (match-version-recursive root-pairs leaf-pairs)
2348 (define (filter-subdirs root-pairs ret)
2349 (define (filter-subdir root-pair dstrm subdir-pairs)
2350 (let ((entry (readdir dstrm)))
2351 (if (eof-object? entry)
2353 (let* ((subdir (string-append (cdr root-pair) entry))
2354 (num (string->number entry))
2355 (num (and num (exact? num) (append (car root-pair)
2357 (if (and num (eq? (stat:type (stat subdir)) 'directory))
2359 root-pair dstrm (cons (cons num (string-append subdir "/"))
2361 (filter-subdir root-pair dstrm subdir-pairs))))))
2363 (or (and (null? root-pairs) ret)
2364 (let* ((rp (car root-pairs))
2365 (dstrm (false-if-exception (opendir (cdr rp)))))
2367 (let ((subdir-pairs (filter-subdir rp dstrm '())))
2369 (filter-subdirs (cdr root-pairs)
2370 (or (and (null? subdir-pairs) ret)
2371 (append ret subdir-pairs))))
2372 (filter-subdirs (cdr root-pairs) ret)))))
2374 (or (and (null? root-pairs) leaf-pairs)
2375 (let ((matching-subdir-pairs (filter-subdirs root-pairs '())))
2376 (match-version-recursive
2377 matching-subdir-pairs
2378 (append leaf-pairs (filter pair? (map match-version-and-file
2379 matching-subdir-pairs)))))))
2380 (define (make-root-pair root)
2381 (cons '() (string-append root "/" dir-hint)))
2383 (let* ((root-pairs (map make-root-pair roots))
2384 (matches (if (null? version-ref)
2385 (filter pair? (map match-version-and-file root-pairs))
2387 (matches (append matches (match-version-recursive root-pairs '()))))
2388 (and (null? matches) (error "No matching modules found."))
2389 (cdar (sort matches subdir-pair-less))))
2391 (define (make-fresh-user-module)
2392 (let ((m (make-module)))
2393 (beautify-user-module! m)
2396 ;; NOTE: This binding is used in libguile/modules.c.
2398 (define resolve-module
2399 (let ((root (make-module)))
2400 (set-module-name! root '())
2401 ;; Define the-root-module as '(guile).
2402 (module-define-submodule! root 'guile the-root-module)
2404 (lambda* (name #:optional (autoload #t) (version #f) #:key (ensure #t))
2405 (let ((already (nested-ref-module root name)))
2408 (or (not autoload) (module-public-interface already)))
2409 ;; A hit, a palpable hit.
2411 (not (version-matches? version (module-version already))))
2412 (error "incompatible module version already loaded" name))
2415 ;; Try to autoload the module, and recurse.
2416 (try-load-module name version)
2417 (resolve-module name #f #:ensure ensure))
2419 ;; No module found (or if one was, it had no public interface), and
2420 ;; we're not autoloading. Make an empty module if #:ensure is true.
2423 (make-modules-in root name)))))))))
2426 (define (try-load-module name version)
2427 (try-module-autoload name version))
2429 (define (purify-module! module)
2430 "Removes bindings in MODULE which are inherited from the (guile) module."
2431 (let ((use-list (module-uses module)))
2432 (if (and (pair? use-list)
2433 (eq? (car (last-pair use-list)) the-scm-module))
2434 (set-module-uses! module (reverse (cdr (reverse use-list)))))))
2436 ;; Return a module that is an interface to the module designated by
2439 ;; `resolve-interface' takes four keyword arguments:
2441 ;; #:select SELECTION
2443 ;; SELECTION is a list of binding-specs to be imported; A binding-spec
2444 ;; is either a symbol or a pair of symbols (ORIG . SEEN), where ORIG
2445 ;; is the name in the used module and SEEN is the name in the using
2446 ;; module. Note that SEEN is also passed through RENAMER, below. The
2447 ;; default is to select all bindings. If you specify no selection but
2448 ;; a renamer, only the bindings that already exist in the used module
2449 ;; are made available in the interface. Bindings that are added later
2450 ;; are not picked up.
2454 ;; BINDINGS is a list of bindings which should not be imported.
2458 ;; PREFIX is a symbol that will be appended to each exported name.
2459 ;; The default is to not perform any renaming.
2461 ;; #:renamer RENAMER
2463 ;; RENAMER is a procedure that takes a symbol and returns its new
2464 ;; name. The default is not perform any renaming.
2466 ;; Signal "no code for module" error if module name is not resolvable
2467 ;; or its public interface is not available. Signal "no binding"
2468 ;; error if selected binding does not exist in the used module.
2470 (define* (resolve-interface name #:key
2475 (symbol-prefix-proc prefix)
2478 (let* ((module (resolve-module name #t version))
2479 (public-i (and module (module-public-interface module))))
2480 (and (or (not module) (not public-i))
2481 (error "no code for module" name))
2482 (if (and (not select) (null? hide) (eq? renamer identity))
2484 (let ((selection (or select (module-map (lambda (sym var) sym)
2486 (custom-i (make-module 31)))
2487 (set-module-kind! custom-i 'custom-interface)
2488 (set-module-name! custom-i name)
2489 ;; XXX - should use a lazy binder so that changes to the
2490 ;; used module are picked up automatically.
2491 (for-each (lambda (bspec)
2492 (let* ((direct? (symbol? bspec))
2493 (orig (if direct? bspec (car bspec)))
2494 (seen (if direct? bspec (cdr bspec)))
2495 (var (or (module-local-variable public-i orig)
2496 (module-local-variable module orig)
2498 ;; fixme: format manually for now
2500 #f "no binding `~A' in module ~A"
2502 (if (memq orig hide)
2503 (set! hide (delq! orig hide))
2504 (module-add! custom-i
2508 ;; Check that we are not hiding bindings which don't exist
2509 (for-each (lambda (binding)
2510 (if (not (module-local-variable public-i binding))
2513 #f "no binding `~A' to hide in module ~A"
2518 (define (symbol-prefix-proc prefix)
2520 (symbol-append prefix symbol)))
2522 ;; This function is called from "modules.c". If you change it, be
2523 ;; sure to update "modules.c" as well.
2525 (define (process-define-module args)
2526 (let* ((module-id (car args))
2527 (module (resolve-module module-id #f))
2529 (unrecognized (lambda (arg)
2530 (error "unrecognized define-module argument" arg))))
2531 (beautify-user-module! module)
2532 (let loop ((kws kws)
2533 (reversed-interfaces '())
2540 (call-with-deferred-observers
2542 (module-use-interfaces! module (reverse reversed-interfaces))
2543 (module-export! module exports)
2544 (module-replace! module replacements)
2545 (module-re-export! module re-exports)
2546 (if (not (null? autoloads))
2547 (apply module-autoload! module autoloads))))
2549 ((#:use-module #:use-syntax)
2550 (or (pair? (cdr kws))
2553 ((equal? (caadr kws) '(ice-9 syncase))
2554 (issue-deprecation-warning
2555 "(ice-9 syncase) is deprecated. Support for syntax-case is now in Guile core.")
2563 (let* ((interface-args (cadr kws))
2564 (interface (apply resolve-interface interface-args)))
2565 (and (eq? (car kws) #:use-syntax)
2566 (or (symbol? (caar interface-args))
2567 (error "invalid module name for use-syntax"
2568 (car interface-args)))
2569 (set-module-transformer!
2571 (module-ref interface
2572 (car (last-pair (car interface-args)))
2575 (cons interface reversed-interfaces)
2581 (or (and (pair? (cdr kws)) (pair? (cddr kws)))
2588 (let ((name (cadr kws))
2589 (bindings (caddr kws)))
2590 (cons* name bindings autoloads))))
2592 (set-system-module! module #t)
2593 (loop (cdr kws) reversed-interfaces exports re-exports
2594 replacements autoloads))
2596 (purify-module! module)
2597 (loop (cdr kws) reversed-interfaces exports re-exports
2598 replacements autoloads))
2600 (or (pair? (cdr kws))
2602 (let ((version (cadr kws)))
2603 (set-module-version! module version)
2604 (set-module-version! (module-public-interface module) version))
2605 (loop (cddr kws) reversed-interfaces exports re-exports
2606 replacements autoloads))
2608 (if (not (pair? (cdr kws)))
2610 (set-module-duplicates-handlers!
2612 (lookup-duplicates-handlers (cadr kws)))
2613 (loop (cddr kws) reversed-interfaces exports re-exports
2614 replacements autoloads))
2615 ((#:export #:export-syntax)
2616 (or (pair? (cdr kws))
2620 (append (cadr kws) exports)
2624 ((#:re-export #:re-export-syntax)
2625 (or (pair? (cdr kws))
2630 (append (cadr kws) re-exports)
2633 ((#:replace #:replace-syntax)
2634 (or (pair? (cdr kws))
2640 (append (cadr kws) replacements)
2643 (or (pair? (cdr kws))
2645 (set-module-filename! module (cadr kws))
2653 (unrecognized kws)))))
2654 (run-hook module-defined-hook module)
2657 ;; `module-defined-hook' is a hook that is run whenever a new module
2658 ;; is defined. Its members are called with one argument, the new
2660 (define module-defined-hook (make-hook 1))
2667 (define (make-autoload-interface module name bindings)
2668 (let ((b (lambda (a sym definep)
2669 (and (memq sym bindings)
2670 (let ((i (module-public-interface (resolve-module name))))
2672 (error "missing interface for module" name))
2673 (let ((autoload (memq a (module-uses module))))
2674 ;; Replace autoload-interface with actual interface if
2675 ;; that has not happened yet.
2676 (if (pair? autoload)
2677 (set-car! autoload i)))
2678 (module-local-variable i sym))))))
2679 (module-constructor (make-hash-table 0) '() b #f #f name 'autoload #f
2680 (make-hash-table 0) '() (make-weak-value-hash-table 31) #f
2681 (make-hash-table 0) #f #f #f)))
2683 (define (module-autoload! module . args)
2684 "Have @var{module} automatically load the module named @var{name} when one
2685 of the symbols listed in @var{bindings} is looked up. @var{args} should be a
2686 list of module-name/binding-list pairs, e.g., as in @code{(module-autoload!
2687 module '(ice-9 q) '(make-q q-length))}."
2688 (let loop ((args args))
2692 (error "invalid name+binding autoload list" args))
2694 (let ((name (car args))
2695 (bindings (cadr args)))
2696 (module-use! module (make-autoload-interface module
2698 (loop (cddr args)))))))
2703 ;;; {Autoloading modules}
2706 (define autoloads-in-progress '())
2708 ;; This function is called from "modules.c". If you change it, be
2709 ;; sure to update "modules.c" as well.
2711 (define* (try-module-autoload module-name #:optional version)
2712 (let* ((reverse-name (reverse module-name))
2713 (name (symbol->string (car reverse-name)))
2714 (dir-hint-module-name (reverse (cdr reverse-name)))
2715 (dir-hint (apply string-append
2717 (string-append (symbol->string elt) "/"))
2718 dir-hint-module-name))))
2719 (resolve-module dir-hint-module-name #f)
2720 (and (not (autoload-done-or-in-progress? dir-hint name))
2723 (lambda () (autoload-in-progress! dir-hint name))
2725 (with-fluids ((current-reader #f))
2726 (save-module-excursion
2729 (load (find-versioned-module
2730 dir-hint name version %load-path))
2731 (primitive-load-path (in-vicinity dir-hint name) #f))
2733 (lambda () (set-autoloaded! dir-hint name didit)))
2738 ;;; {Dynamic linking of modules}
2741 (define autoloads-done '((guile . guile)))
2743 (define (autoload-done-or-in-progress? p m)
2744 (let ((n (cons p m)))
2745 (->bool (or (member n autoloads-done)
2746 (member n autoloads-in-progress)))))
2748 (define (autoload-done! p m)
2749 (let ((n (cons p m)))
2750 (set! autoloads-in-progress
2751 (delete! n autoloads-in-progress))
2752 (or (member n autoloads-done)
2753 (set! autoloads-done (cons n autoloads-done)))))
2755 (define (autoload-in-progress! p m)
2756 (let ((n (cons p m)))
2757 (set! autoloads-done
2758 (delete! n autoloads-done))
2759 (set! autoloads-in-progress (cons n autoloads-in-progress))))
2761 (define (set-autoloaded! p m done?)
2763 (autoload-done! p m)
2764 (let ((n (cons p m)))
2765 (set! autoloads-done (delete! n autoloads-done))
2766 (set! autoloads-in-progress (delete! n autoloads-in-progress)))))
2770 ;;; {Run-time options}
2773 (defmacro define-option-interface (option-group)
2774 (let* ((option-name 'car)
2775 (option-value 'cadr)
2776 (option-documentation 'caddr)
2778 ;; Below follow the macros defining the run-time option interfaces.
2780 (make-options (lambda (interface)
2782 (cond ((null? args) (,interface))
2784 (,interface (car args)) (,interface))
2787 (display (,option-name option))
2788 (if (< (string-length
2789 (symbol->string (,option-name option)))
2793 (display (,option-value option))
2795 (display (,option-documentation option))
2797 (,interface #t)))))))
2799 (make-enable (lambda (interface)
2801 (,interface (append flags (,interface)))
2804 (make-disable (lambda (interface)
2806 (let ((options (,interface)))
2807 (for-each (lambda (flag)
2808 (set! options (delq! flag options)))
2810 (,interface options)
2812 (let* ((interface (car option-group))
2813 (options/enable/disable (cadr option-group)))
2815 (define ,(car options/enable/disable)
2816 ,(make-options interface))
2817 (define ,(cadr options/enable/disable)
2818 ,(make-enable interface))
2819 (define ,(caddr options/enable/disable)
2820 ,(make-disable interface))
2821 (defmacro ,(caaddr option-group) (opt val)
2822 `(,',(car options/enable/disable)
2823 (append (,',(car options/enable/disable))
2824 (list ',opt ,val))))))))
2826 (define-option-interface
2827 (eval-options-interface
2828 (eval-options eval-enable eval-disable)
2831 (define-option-interface
2832 (debug-options-interface
2833 (debug-options debug-enable debug-disable)
2836 (define-option-interface
2837 (evaluator-traps-interface
2838 (traps trap-enable trap-disable)
2841 (define-option-interface
2842 (read-options-interface
2843 (read-options read-enable read-disable)
2846 (define-option-interface
2847 (print-options-interface
2848 (print-options print-enable print-disable)
2856 (define (repl read evaler print)
2857 (let loop ((source (read (current-input-port))))
2858 (print (evaler source))
2859 (loop (read (current-input-port)))))
2861 ;; A provisional repl that acts like the SCM repl:
2863 (define scm-repl-silent #f)
2864 (define (assert-repl-silence v) (set! scm-repl-silent v))
2866 (define *unspecified* (if #f #f))
2867 (define (unspecified? v) (eq? v *unspecified*))
2869 (define scm-repl-print-unspecified #f)
2870 (define (assert-repl-print-unspecified v) (set! scm-repl-print-unspecified v))
2872 (define scm-repl-verbose #f)
2873 (define (assert-repl-verbosity v) (set! scm-repl-verbose v))
2875 (define scm-repl-prompt "guile> ")
2877 (define (set-repl-prompt! v) (set! scm-repl-prompt v))
2879 (define (default-pre-unwind-handler key . args)
2880 ;; Narrow by two more frames: this one, and the throw handler.
2882 (apply throw key args))
2885 (define (pre-unwind-handler-dispatch key . args)
2886 (apply default-pre-unwind-handler key args)))
2888 (define abort-hook (make-hook))
2890 ;; these definitions are used if running a script.
2891 ;; otherwise redefined in error-catching-loop.
2892 (define (set-batch-mode?! arg) #t)
2893 (define (batch-mode?) #t)
2895 ;;(define the-last-stack (make-fluid)) Defined by scm_init_backtrace ()
2896 (define before-signal-stack (make-fluid))
2897 ;; FIXME: stack-saved? is broken in the presence of threads.
2898 (define stack-saved? #f)
2900 (define (save-stack . narrowing)
2901 (if (not stack-saved?)
2903 (let ((stacks (fluid-ref %stacks)))
2904 (fluid-set! the-last-stack
2905 ;; (make-stack obj inner outer inner outer ...)
2907 ;; In this case, cut away the make-stack frame, the
2908 ;; save-stack frame, and then narrow as specified by the
2909 ;; user, delimited by the nearest start-stack invocation,
2911 (apply make-stack #t
2913 (if (pair? stacks) (cdar stacks) 0)
2915 (set! stack-saved? #t))))
2917 (define before-error-hook (make-hook))
2918 (define after-error-hook (make-hook))
2919 (define before-backtrace-hook (make-hook))
2920 (define after-backtrace-hook (make-hook))
2922 (define has-shown-debugger-hint? #f)
2924 (define (handle-system-error key . args)
2925 (let ((cep (current-error-port)))
2926 (cond ((not (stack? (fluid-ref the-last-stack))))
2927 ((memq 'backtrace (debug-options-interface))
2928 (let ((highlights (if (or (eq? key 'wrong-type-arg)
2929 (eq? key 'out-of-range))
2932 (run-hook before-backtrace-hook)
2934 (display "Backtrace:\n")
2935 (display-backtrace (fluid-ref the-last-stack) cep
2938 (run-hook after-backtrace-hook))))
2939 (run-hook before-error-hook)
2940 (apply display-error (fluid-ref the-last-stack) cep args)
2941 (run-hook after-error-hook)
2943 (throw 'abort key)))
2945 (define (quit . args)
2946 (apply throw 'quit args))
2950 (define (gc-run-time)
2951 (cdr (assq 'gc-time-taken (gc-stats))))
2953 (define before-read-hook (make-hook))
2954 (define after-read-hook (make-hook))
2955 (define before-eval-hook (make-hook 1))
2956 (define after-eval-hook (make-hook 1))
2957 (define before-print-hook (make-hook 1))
2958 (define after-print-hook (make-hook 1))
2960 ;;; The default repl-reader function. We may override this if we've
2961 ;;; the readline library.
2963 (lambda* (prompt #:optional (reader (fluid-ref current-reader)))
2964 (if (not (char-ready?))
2965 (display (if (string? prompt) prompt (prompt))))
2967 (run-hook before-read-hook)
2968 ((or reader read) (current-input-port))))
2973 ;;; {IOTA functions: generating lists of numbers}
2977 (let loop ((count (1- n)) (result '()))
2978 (if (< count 0) result
2979 (loop (1- count) (cons count result)))))
2985 ;;; Similar to `begin' but returns a list of the results of all constituent
2986 ;;; forms instead of the result of the last form.
2987 ;;; (The definition relies on the current left-to-right
2988 ;;; order of evaluation of operands in applications.)
2991 (defmacro collect forms
2998 ;;; with `continue' and `break'.
3001 ;; The inner `do' loop avoids re-establishing a catch every iteration,
3002 ;; that's only necessary if continue is actually used. A new key is
3003 ;; generated every time, so break and continue apply to their originating
3004 ;; `while' even when recursing.
3006 ;; FIXME: This macro is unintentionally unhygienic with respect to let,
3007 ;; make-symbol, do, throw, catch, lambda, and not.
3009 (define-macro (while cond . body)
3010 (let ((keyvar (make-symbol "while-keyvar")))
3011 `(let ((,keyvar (make-symbol "while-key")))
3015 (let ((break (lambda () (throw ,keyvar #t)))
3016 (continue (lambda () (throw ,keyvar #f))))
3027 ;;; {Module System Macros}
3030 ;; Return a list of expressions that evaluate to the appropriate
3031 ;; arguments for resolve-interface according to SPEC.
3035 (if (memq 'prefix (read-options))
3036 (error "boot-9 must be compiled with #:kw, not :kw")))
3038 (define (keyword-like-symbol->keyword sym)
3039 (symbol->keyword (string->symbol (substring (symbol->string sym) 1))))
3041 ;; FIXME: we really need to clean up the guts of the module system.
3042 ;; We can compile to something better than process-define-module.
3043 (define-syntax define-module
3045 (define (keyword-like? stx)
3046 (let ((dat (syntax->datum stx)))
3048 (eqv? (string-ref (symbol->string dat) 0) #\:))))
3049 (define (->keyword sym)
3050 (symbol->keyword (string->symbol (substring (symbol->string sym) 1))))
3052 (define (quotify-iface args)
3053 (let loop ((in args) (out '()))
3056 ;; The user wanted #:foo, but wrote :foo. Fix it.
3057 ((sym . in) (keyword-like? #'sym)
3058 (loop #`(#,(->keyword (syntax->datum #'sym)) . in) out))
3059 ((kw . in) (not (keyword? (syntax->datum #'kw)))
3060 (syntax-violation 'define-module "expected keyword arg" x #'kw))
3061 ((#:renamer renamer . in)
3062 (loop #'in (cons* #'renamer #:renamer out)))
3064 (loop #'in (cons* #''val #'kw out))))))
3066 (define (quotify args)
3067 ;; Just quote everything except #:use-module and #:use-syntax. We
3068 ;; need to know about all arguments regardless since we want to turn
3069 ;; symbols that look like keywords into real keywords, and the
3070 ;; keyword args in a define-module form are not regular
3071 ;; (i.e. no-backtrace doesn't take a value).
3072 (let loop ((in args) (out '()))
3075 ;; The user wanted #:foo, but wrote :foo. Fix it.
3076 ((sym . in) (keyword-like? #'sym)
3077 (loop #`(#,(->keyword (syntax->datum #'sym)) . in) out))
3078 ((kw . in) (not (keyword? (syntax->datum #'kw)))
3079 (syntax-violation 'define-module "expected keyword arg" x #'kw))
3080 ((#:no-backtrace . in)
3081 (loop #'in (cons #:no-backtrace out)))
3083 (loop #'in (cons #:pure out)))
3085 (syntax-violation 'define-module "keyword arg without value" x #'kw))
3086 ((use-module (name name* ...) . in)
3087 (and (memq (syntax->datum #'use-module) '(#:use-module #:use-syntax))
3088 (and-map symbol? (syntax->datum #'(name name* ...))))
3090 (cons* #''((name name* ...))
3093 ((use-module ((name name* ...) arg ...) . in)
3094 (and (memq (syntax->datum #'use-module) '(#:use-module #:use-syntax))
3095 (and-map symbol? (syntax->datum #'(name name* ...))))
3097 (cons* #`(list '(name name* ...) #,@(quotify-iface #'(arg ...)))
3100 ((#:autoload name bindings . in)
3101 (loop #'in (cons* #''bindings #''name #:autoload out)))
3103 (loop #'in (cons* #''val #'kw out))))))
3106 ((_ (name name* ...) arg ...)
3107 (with-syntax (((quoted-arg ...) (quotify #'(arg ...))))
3108 #'(eval-when (eval load compile expand)
3109 (let ((m (process-define-module
3110 (list '(name name* ...)
3111 #:filename (assq-ref
3112 (or (current-source-location) '())
3115 (set-current-module m)
3118 ;; The guts of the use-modules macro. Add the interfaces of the named
3119 ;; modules to the use-list of the current module, in order.
3121 ;; This function is called by "modules.c". If you change it, be sure
3122 ;; to change scm_c_use_module as well.
3124 (define (process-use-modules module-interface-args)
3125 (let ((interfaces (map (lambda (mif-args)
3126 (or (apply resolve-interface mif-args)
3127 (error "no such module" mif-args)))
3128 module-interface-args)))
3129 (call-with-deferred-observers
3131 (module-use-interfaces! (current-module) interfaces)))))
3133 (define-syntax use-modules
3135 (define (keyword-like? stx)
3136 (let ((dat (syntax->datum stx)))
3138 (eqv? (string-ref (symbol->string dat) 0) #\:))))
3139 (define (->keyword sym)
3140 (symbol->keyword (string->symbol (substring (symbol->string sym) 1))))
3142 (define (quotify-iface args)
3143 (let loop ((in args) (out '()))
3146 ;; The user wanted #:foo, but wrote :foo. Fix it.
3147 ((sym . in) (keyword-like? #'sym)
3148 (loop #`(#,(->keyword (syntax->datum #'sym)) . in) out))
3149 ((kw . in) (not (keyword? (syntax->datum #'kw)))
3150 (syntax-violation 'define-module "expected keyword arg" x #'kw))
3151 ((#:renamer renamer . in)
3152 (loop #'in (cons* #'renamer #:renamer out)))
3154 (loop #'in (cons* #''val #'kw out))))))
3156 (define (quotify specs)
3157 (let lp ((in specs) (out '()))
3160 (((name name* ...) . in)
3161 (and-map symbol? (syntax->datum #'(name name* ...)))
3162 (lp #'in (cons #''((name name* ...)) out)))
3163 ((((name name* ...) arg ...) . in)
3164 (and-map symbol? (syntax->datum #'(name name* ...)))
3165 (with-syntax (((quoted-arg ...) (quotify-iface #'(arg ...))))
3166 (lp #'in (cons #`(list '(name name* ...) quoted-arg ...)
3171 (with-syntax (((quoted-args ...) (quotify #'(spec ...))))
3172 #'(eval-when (eval load compile expand)
3173 (process-use-modules (list quoted-args ...))
3176 (define-syntax use-syntax
3180 (eval-when (eval load compile expand)
3181 (issue-deprecation-warning
3182 "`use-syntax' is deprecated. Please contact guile-devel for more info."))
3183 (use-modules spec ...)))))
3185 (include-from-path "ice-9/r6rs-libraries")
3187 (define-syntax define-private
3192 (define-syntax define-public
3194 ((_ (name . args) . body)
3195 (define-public name (lambda args . body)))
3201 (define-syntax defmacro-public
3203 ((_ name args . body)
3205 (defmacro name args . body)
3206 (export-syntax name)))))
3208 ;; And now for the most important macro.
3211 ((_ formals body ...)
3212 (lambda formals body ...))))
3215 ;; Export a local variable
3217 ;; This function is called from "modules.c". If you change it, be
3218 ;; sure to update "modules.c" as well.
3220 (define (module-export! m names)
3221 (let ((public-i (module-public-interface m)))
3222 (for-each (lambda (name)
3223 (let* ((internal-name (if (pair? name) (car name) name))
3224 (external-name (if (pair? name) (cdr name) name))
3225 (var (module-ensure-local-variable! m internal-name)))
3226 (module-add! public-i external-name var)))
3229 (define (module-replace! m names)
3230 (let ((public-i (module-public-interface m)))
3231 (for-each (lambda (name)
3232 (let* ((internal-name (if (pair? name) (car name) name))
3233 (external-name (if (pair? name) (cdr name) name))
3234 (var (module-ensure-local-variable! m internal-name)))
3235 (set-object-property! var 'replace #t)
3236 (module-add! public-i external-name var)))
3239 ;; Export all local variables from a module
3241 (define (module-export-all! mod)
3242 (define (fresh-interface!)
3243 (let ((iface (make-module)))
3244 (set-module-name! iface (module-name mod))
3245 ;; for guile 2: (set-module-version! iface (module-version mod))
3246 (set-module-kind! iface 'interface)
3247 (set-module-public-interface! mod iface)
3249 (let ((iface (or (module-public-interface mod)
3250 (fresh-interface!))))
3251 (set-module-obarray! iface (module-obarray mod))))
3253 ;; Re-export a imported variable
3255 (define (module-re-export! m names)
3256 (let ((public-i (module-public-interface m)))
3257 (for-each (lambda (name)
3258 (let* ((internal-name (if (pair? name) (car name) name))
3259 (external-name (if (pair? name) (cdr name) name))
3260 (var (module-variable m internal-name)))
3262 (error "Undefined variable:" internal-name))
3263 ((eq? var (module-local-variable m internal-name))
3264 (error "re-exporting local variable:" internal-name))
3266 (module-add! public-i external-name var)))))
3269 (define-syntax export
3272 (eval-when (eval load compile expand)
3273 (call-with-deferred-observers
3275 (module-export! (current-module) '(name ...))))))))
3277 (define-syntax re-export
3280 (eval-when (eval load compile expand)
3281 (call-with-deferred-observers
3283 (module-re-export! (current-module) '(name ...))))))))
3285 (define-syntax export-syntax
3288 (export name ...))))
3290 (define-syntax re-export-syntax
3293 (re-export name ...))))
3295 (define load load-module)
3302 (define make-mutable-parameter
3303 (let ((make (lambda (fluid converter)
3307 (fluid-set! fluid (converter (car args))))))))
3308 (lambda* (init #:optional (converter identity))
3309 (let ((fluid (make-fluid)))
3310 (fluid-set! fluid (converter init))
3311 (make fluid converter)))))
3315 ;;; {Handling of duplicate imported bindings}
3318 ;; Duplicate handlers take the following arguments:
3320 ;; module importing module
3321 ;; name conflicting name
3322 ;; int1 old interface where name occurs
3323 ;; val1 value of binding in old interface
3324 ;; int2 new interface where name occurs
3325 ;; val2 value of binding in new interface
3326 ;; var previous resolution or #f
3327 ;; val value of previous resolution
3329 ;; A duplicate handler can take three alternative actions:
3331 ;; 1. return #f => leave responsibility to next handler
3332 ;; 2. exit with an error
3333 ;; 3. return a variable resolving the conflict
3336 (define duplicate-handlers
3337 (let ((m (make-module 7)))
3339 (define (check module name int1 val1 int2 val2 var val)
3340 (scm-error 'misc-error
3342 "~A: `~A' imported from both ~A and ~A"
3343 (list (module-name module)
3349 (define (warn module name int1 val1 int2 val2 var val)
3350 (format (current-error-port)
3351 "WARNING: ~A: `~A' imported from both ~A and ~A\n"
3352 (module-name module)
3358 (define (replace module name int1 val1 int2 val2 var val)
3359 (let ((old (or (and var (object-property var 'replace) var)
3360 (module-variable int1 name)))
3361 (new (module-variable int2 name)))
3362 (if (object-property old 'replace)
3363 (and (or (eq? old new)
3364 (not (object-property new 'replace)))
3366 (and (object-property new 'replace)
3369 (define (warn-override-core module name int1 val1 int2 val2 var val)
3370 (and (eq? int1 the-scm-module)
3372 (format (current-error-port)
3373 "WARNING: ~A: imported module ~A overrides core binding `~A'\n"
3374 (module-name module)
3377 (module-local-variable int2 name))))
3379 (define (first module name int1 val1 int2 val2 var val)
3380 (or var (module-local-variable int1 name)))
3382 (define (last module name int1 val1 int2 val2 var val)
3383 (module-local-variable int2 name))
3385 (define (noop module name int1 val1 int2 val2 var val)
3388 (set-module-name! m 'duplicate-handlers)
3389 (set-module-kind! m 'interface)
3390 (module-define! m 'check check)
3391 (module-define! m 'warn warn)
3392 (module-define! m 'replace replace)
3393 (module-define! m 'warn-override-core warn-override-core)
3394 (module-define! m 'first first)
3395 (module-define! m 'last last)
3396 (module-define! m 'merge-generics noop)
3397 (module-define! m 'merge-accessors noop)
3400 (define (lookup-duplicates-handlers handler-names)
3402 (map (lambda (handler-name)
3403 (or (module-symbol-local-binding
3404 duplicate-handlers handler-name #f)
3405 (error "invalid duplicate handler name:"
3407 (if (list? handler-names)
3409 (list handler-names)))))
3411 (define default-duplicate-binding-procedures
3412 (make-mutable-parameter #f))
3414 (define default-duplicate-binding-handler
3415 (make-mutable-parameter '(replace warn-override-core warn last)
3416 (lambda (handler-names)
3417 (default-duplicate-binding-procedures
3418 (lookup-duplicates-handlers handler-names))
3423 ;;; {`cond-expand' for SRFI-0 support.}
3425 ;;; This syntactic form expands into different commands or
3426 ;;; definitions, depending on the features provided by the Scheme
3432 ;;; --> (cond-expand <cond-expand-clause>+)
3433 ;;; | (cond-expand <cond-expand-clause>* (else <command-or-definition>))
3434 ;;; <cond-expand-clause>
3435 ;;; --> (<feature-requirement> <command-or-definition>*)
3436 ;;; <feature-requirement>
3437 ;;; --> <feature-identifier>
3438 ;;; | (and <feature-requirement>*)
3439 ;;; | (or <feature-requirement>*)
3440 ;;; | (not <feature-requirement>)
3441 ;;; <feature-identifier>
3442 ;;; --> <a symbol which is the name or alias of a SRFI>
3444 ;;; Additionally, this implementation provides the
3445 ;;; <feature-identifier>s `guile' and `r5rs', so that programs can
3446 ;;; determine the implementation type and the supported standard.
3448 ;;; Currently, the following feature identifiers are supported:
3450 ;;; guile r5rs srfi-0 srfi-4 srfi-6 srfi-13 srfi-14 srfi-55 srfi-61
3452 ;;; Remember to update the features list when adding more SRFIs.
3455 (define %cond-expand-features
3456 ;; Adjust the above comment when changing this.
3460 srfi-0 ;; cond-expand itself
3461 srfi-4 ;; homogenous numeric vectors
3462 srfi-6 ;; open-input-string etc, in the guile core
3463 srfi-13 ;; string library
3464 srfi-14 ;; character sets
3465 srfi-55 ;; require-extension
3466 srfi-61 ;; general cond clause
3469 ;; This table maps module public interfaces to the list of features.
3471 (define %cond-expand-table (make-hash-table 31))
3473 ;; Add one or more features to the `cond-expand' feature list of the
3476 (define (cond-expand-provide module features)
3477 (let ((mod (module-public-interface module)))
3479 (hashq-set! %cond-expand-table mod
3480 (append (hashq-ref %cond-expand-table mod '())
3483 (define-macro (cond-expand . clauses)
3484 (let ((syntax-error (lambda (cl)
3485 (error "invalid clause in `cond-expand'" cl))))
3491 (or (memq clause %cond-expand-features)
3492 (let lp ((uses (module-uses (current-module))))
3495 (hashq-ref %cond-expand-table
3501 ((eq? 'and (car clause))
3502 (let lp ((l (cdr clause)))
3506 (and (test-clause (car l)) (lp (cdr l))))
3508 (syntax-error clause)))))
3509 ((eq? 'or (car clause))
3510 (let lp ((l (cdr clause)))
3514 (or (test-clause (car l)) (lp (cdr l))))
3516 (syntax-error clause)))))
3517 ((eq? 'not (car clause))
3518 (cond ((not (pair? (cdr clause)))
3519 (syntax-error clause))
3520 ((pair? (cddr clause))
3521 ((syntax-error clause))))
3522 (not (test-clause (cadr clause))))
3524 (syntax-error clause))))
3526 (syntax-error clause))))))
3527 (let lp ((c clauses))
3530 (error "Unfulfilled `cond-expand'"))
3533 ((not (pair? (car c)))
3534 (syntax-error (car c)))
3535 ((test-clause (caar c))
3536 `(begin ,@(cdar c)))
3537 ((eq? (caar c) 'else)
3540 `(begin ,@(cdar c)))
3544 ;; This procedure gets called from the startup code with a list of
3545 ;; numbers, which are the numbers of the SRFIs to be loaded on startup.
3547 (define (use-srfis srfis)
3548 (process-use-modules
3550 (list (list 'srfi (string->symbol
3551 (string-append "srfi-" (number->string num))))))
3556 ;;; srfi-55: require-extension
3559 (define-macro (require-extension extension-spec)
3560 ;; This macro only handles the srfi extension, which, at present, is
3561 ;; the only one defined by the standard.
3562 (if (not (pair? extension-spec))
3563 (scm-error 'wrong-type-arg "require-extension"
3564 "Not an extension: ~S" (list extension-spec) #f))
3565 (let ((extension (car extension-spec))
3566 (extension-args (cdr extension-spec)))
3569 (let ((use-list '()))
3572 (if (not (integer? i))
3573 (scm-error 'wrong-type-arg "require-extension"
3574 "Invalid srfi name: ~S" (list i) #f))
3575 (let ((srfi-sym (string->symbol
3576 (string-append "srfi-" (number->string i)))))
3577 (if (not (memq srfi-sym %cond-expand-features))
3578 (set! use-list (cons `(use-modules (srfi ,srfi-sym))
3581 (if (pair? use-list)
3582 ;; i.e. (begin (use-modules x) (use-modules y) (use-modules z))
3583 `(begin ,@(reverse! use-list)))))
3586 'wrong-type-arg "require-extension"
3587 "Not a recognized extension type: ~S" (list extension) #f)))))
3591 ;;; {Load emacs interface support if emacs option is given.}
3594 (define (named-module-use! user usee)
3595 (module-use! (resolve-module user) (resolve-interface usee)))
3597 (define (load-emacs-interface)
3598 (and (provided? 'debug-extensions)
3599 (debug-enable 'backtrace))
3600 (named-module-use! '(guile-user) '(ice-9 emacs)))
3604 (define using-readline?
3605 (let ((using-readline? (make-fluid)))
3606 (make-procedure-with-setter
3607 (lambda () (fluid-ref using-readline?))
3608 (lambda (v) (fluid-set! using-readline? v)))))
3611 (let ((guile-user-module (resolve-module '(guile-user))))
3613 ;; Load emacs interface support if emacs option is given.
3614 (if (and (module-defined? guile-user-module 'use-emacs-interface)
3615 (module-ref guile-user-module 'use-emacs-interface))
3616 (load-emacs-interface))
3618 ;; Use some convenient modules (in reverse order)
3620 (set-current-module guile-user-module)
3621 (process-use-modules
3626 (if (provided? 'regex)
3629 (if (provided? 'threads)
3630 '(((ice-9 threads)))
3632 ;; load debugger on demand
3633 (module-autoload! guile-user-module '(system vm debug) '(debug))
3635 ;; Note: SIGFPE, SIGSEGV and SIGBUS are actually "query-only" (see
3636 ;; scmsigs.c scm_sigaction_for_thread), so the handlers setup here have
3638 (let ((old-handlers #f)
3639 ;; We can't use @ here, as modules have been booted, but in Guile's
3640 ;; build the srfi-1 helper lib hasn't been built yet, which will
3641 ;; result in an error when (system repl repl) is loaded at compile
3642 ;; time (to see if it is a macro or not).
3643 (start-repl (module-ref (resolve-module '(system repl repl))
3645 (signals (if (provided? 'posix)
3646 `((,SIGINT . "User interrupt")
3647 (,SIGFPE . "Arithmetic error")
3649 . "Bad memory access (Segmentation violation)"))
3651 ;; no SIGBUS on mingw
3652 (if (defined? 'SIGBUS)
3653 (set! signals (acons SIGBUS "Bad memory access (bus error)"
3660 (let ((make-handler (lambda (msg)
3662 ;; Make a backup copy of the stack
3663 (fluid-set! before-signal-stack
3664 (fluid-ref the-last-stack))
3672 (map (lambda (sig-msg)
3673 (sigaction (car sig-msg)
3674 (make-handler (cdr sig-msg))))
3677 ;; the protected thunk.
3679 (let ((status (start-repl 'scheme)))
3680 (run-hook exit-hook)
3685 (map (lambda (sig-msg old-handler)
3686 (if (not (car old-handler))
3687 ;; restore original C handler.
3688 (sigaction (car sig-msg) #f)
3689 ;; restore Scheme handler, SIG_IGN or SIG_DFL.
3690 (sigaction (car sig-msg)
3692 (cdr old-handler))))
3693 signals old-handlers))))))
3695 ;;; This hook is run at the very end of an interactive session.
3697 (define exit-hook (make-hook))
3701 ;;; {Deprecated stuff}
3705 (module-use! the-scm-module (resolve-interface '(ice-9 deprecated))))
3709 ;;; Place the user in the guile-user module.
3713 (module-use! the-scm-module (resolve-interface '(srfi srfi-4)))
3715 (define-module (guile-user)
3716 #:autoload (system base compile) (compile))
3718 ;; Remain in the `(guile)' module at compilation-time so that the
3719 ;; `-Wunused-toplevel' warning works as expected.
3720 (eval-when (compile) (set-current-module the-root-module))
3722 ;;; boot-9.scm ends here