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 ;; Input hook to syncase -- so that we might be able to pass annotated
341 ;; expressions in. Currently disabled. Maybe we should just use
342 ;; source-properties directly.
343 (define (annotation? x) #f)
345 ;; API provided by psyntax
346 (define syntax-violation #f)
347 (define datum->syntax #f)
348 (define syntax->datum #f)
349 (define syntax-source #f)
350 (define identifier? #f)
351 (define generate-temporaries #f)
352 (define bound-identifier=? #f)
353 (define free-identifier=? #f)
355 ;; $sc-dispatch is an implementation detail of psyntax. It is used by
356 ;; expanded macros, to dispatch an input against a set of patterns.
357 (define $sc-dispatch #f)
360 (primitive-load-path "ice-9/psyntax-pp")
361 ;; The binding for `macroexpand' has now been overridden, making psyntax the
368 ((_ x y ...) (if x (and y ...) #f))))
374 ((_ x y ...) (let ((t x)) (if t t (or y ...))))))
376 ;; The "maybe-more" bits are something of a hack, so that we can support
377 ;; SRFI-61. Rewrites into a standalone syntax-case macro would be
380 (syntax-rules (=> else)
381 ((_ "maybe-more" test consequent)
382 (if test consequent))
384 ((_ "maybe-more" test consequent clause ...)
385 (if test consequent (cond clause ...)))
387 ((_ (else else1 else2 ...))
388 (begin else1 else2 ...))
390 ((_ (test => receiver) more-clause ...)
392 (cond "maybe-more" t (receiver t) more-clause ...)))
394 ((_ (generator guard => receiver) more-clause ...)
395 (call-with-values (lambda () generator)
398 (apply guard t) (apply receiver t) more-clause ...))))
400 ((_ (test => receiver ...) more-clause ...)
401 (syntax-violation 'cond "wrong number of receiver expressions"
402 '(test => receiver ...)))
403 ((_ (generator guard => receiver ...) more-clause ...)
404 (syntax-violation 'cond "wrong number of receiver expressions"
405 '(generator guard => receiver ...)))
407 ((_ (test) more-clause ...)
409 (cond "maybe-more" t t more-clause ...)))
411 ((_ (test body1 body2 ...) more-clause ...)
413 test (begin body1 body2 ...) more-clause ...))))
419 (let ((atom-key (key ...)))
420 (case atom-key clauses ...)))
422 (else result1 result2 ...))
423 (begin result1 result2 ...))
425 ((atoms ...) result1 result2 ...))
426 (if (memv key '(atoms ...))
427 (begin result1 result2 ...)))
429 ((atoms ...) result1 result2 ...)
431 (if (memv key '(atoms ...))
432 (begin result1 result2 ...)
433 (case key clause clauses ...)))))
437 ((do ((var init step ...) ...)
450 (loop (do "step" var step ...)
460 ((_ exp) (make-promise (lambda () exp)))))
462 (include-from-path "ice-9/quasisyntax")
464 (define-syntax current-source-location
468 (with-syntax ((s (datum->syntax x (syntax-source x))))
477 (define-syntax define-macro
481 ((_ (macro . args) doc body1 body ...)
482 (string? (syntax->datum #'doc))
483 #'(define-macro macro doc (lambda args body1 body ...)))
484 ((_ (macro . args) body ...)
485 #'(define-macro macro #f (lambda args body ...)))
486 ((_ macro doc transformer)
487 (or (string? (syntax->datum #'doc))
488 (not (syntax->datum #'doc)))
489 #'(define-syntax macro
492 #((macro-type . defmacro)
493 (defmacro-args args))
496 (let ((v (syntax->datum #'args)))
497 (datum->syntax y (apply transformer v)))))))))))
499 (define-syntax defmacro
501 "Define a defmacro, with the old lispy defun syntax."
503 ((_ macro args doc body1 body ...)
504 (string? (syntax->datum #'doc))
505 #'(define-macro macro doc (lambda args body1 body ...)))
506 ((_ macro args body ...)
507 #'(define-macro macro #f (lambda args body ...))))))
515 ;;; Depends on: defmacro
518 (defmacro begin-deprecated forms
519 (if (include-deprecated-features)
525 ;;; {Trivial Functions}
528 (define (identity x) x)
529 (define (and=> value procedure) (and value (procedure value)))
530 (define call/cc call-with-current-continuation)
532 ;;; apply-to-args is functionally redundant with apply and, worse,
533 ;;; is less general than apply since it only takes two arguments.
535 ;;; On the other hand, apply-to-args is a syntacticly convenient way to
536 ;;; perform binding in many circumstances when the "let" family of
537 ;;; of forms don't cut it. E.g.:
539 ;;; (apply-to-args (return-3d-mouse-coords)
544 (define (apply-to-args args fn) (apply fn args))
546 (defmacro false-if-exception (expr)
549 ;; avoid saving backtraces inside false-if-exception
550 (with-fluids ((the-last-stack (fluid-ref the-last-stack)))
556 ;;; {General Properties}
559 ;; This is a more modern interface to properties. It will replace all
560 ;; other property-like things eventually.
562 (define (make-object-property)
563 (let ((prop (primitive-make-property #f)))
564 (make-procedure-with-setter
565 (lambda (obj) (primitive-property-ref prop obj))
566 (lambda (obj val) (primitive-property-set! prop obj val)))))
570 ;;; {Symbol Properties}
573 (define (symbol-property sym prop)
574 (let ((pair (assoc prop (symbol-pref sym))))
575 (and pair (cdr pair))))
577 (define (set-symbol-property! sym prop val)
578 (let ((pair (assoc prop (symbol-pref sym))))
581 (symbol-pset! sym (acons prop val (symbol-pref sym))))))
583 (define (symbol-property-remove! sym prop)
584 (let ((pair (assoc prop (symbol-pref sym))))
586 (symbol-pset! sym (delq! pair (symbol-pref sym))))))
593 (define (array-shape a)
594 (map (lambda (ind) (if (number? ind) (list 0 (+ -1 ind)) ind))
595 (array-dimensions a)))
602 (define (kw-arg-ref args kw)
603 (let ((rem (member kw args)))
604 (and rem (pair? (cdr rem)) (cadr rem))))
611 (define (struct-layout s)
612 (struct-ref (struct-vtable s) vtable-index-layout))
619 ;; Printing records: by default, records are printed as
621 ;; #<type-name field1: val1 field2: val2 ...>
623 ;; You can change that by giving a custom printing function to
624 ;; MAKE-RECORD-TYPE (after the list of field symbols). This function
625 ;; will be called like
627 ;; (<printer> object port)
629 ;; It should print OBJECT to PORT.
631 (define (inherit-print-state old-port new-port)
632 (if (get-print-state old-port)
633 (port-with-print-state new-port (get-print-state old-port))
636 ;; 0: type-name, 1: fields, 2: constructor
637 (define record-type-vtable
638 ;; FIXME: This should just call make-vtable, not make-vtable-vtable; but for
639 ;; that we need to expose the bare vtable-vtable to Scheme.
640 (make-vtable-vtable "prprpw" 0
642 (cond ((eq? s record-type-vtable)
643 (display "#<record-type-vtable>" p))
645 (display "#<record-type " p)
646 (display (record-type-name s) p)
649 (define (record-type? obj)
650 (and (struct? obj) (eq? record-type-vtable (struct-vtable obj))))
652 (define* (make-record-type type-name fields #:optional printer)
653 ;; Pre-generate constructors for nfields < 20.
654 (define-syntax make-constructor
656 (define *max-static-argument-count* 20)
657 (define (make-formals n)
663 (string (integer->char (+ (char->integer #\a) i)))))
667 ((_ rtd exp) (not (identifier? #'exp))
669 (make-constructor rtd n)))
673 (if (< n *max-static-argument-count*)
674 (cons (with-syntax (((formal ...) (make-formals n))
678 (make-struct rtd 0 formal ...))))
683 (if (= (length args) nfields)
684 (apply make-struct rtd 0 args)
685 (scm-error 'wrong-number-of-args
686 (format #f "make-~a" type-name)
687 "Wrong number of arguments" '() #f)))))))))
689 (define (default-record-printer s p)
691 (display (record-type-name (record-type-descriptor s)) p)
692 (let loop ((fields (record-type-fields (record-type-descriptor s)))
695 ((not (null? fields))
697 (display (car fields) p)
699 (display (struct-ref s off) p)
700 (loop (cdr fields) (+ 1 off)))))
703 (let ((rtd (make-struct record-type-vtable 0
706 (map (lambda (f) "pw") fields)))
707 (or printer default-record-printer)
709 (copy-tree fields))))
710 (struct-set! rtd (+ vtable-offset-user 2)
711 (make-constructor rtd (length fields)))
712 ;; Temporary solution: Associate a name to the record type descriptor
713 ;; so that the object system can create a wrapper class for it.
714 (set-struct-vtable-name! rtd (if (symbol? type-name)
716 (string->symbol type-name)))
719 (define (record-type-name obj)
720 (if (record-type? obj)
721 (struct-ref obj vtable-offset-user)
722 (error 'not-a-record-type obj)))
724 (define (record-type-fields obj)
725 (if (record-type? obj)
726 (struct-ref obj (+ 1 vtable-offset-user))
727 (error 'not-a-record-type obj)))
729 (define* (record-constructor rtd #:optional field-names)
730 (if (not field-names)
731 (struct-ref rtd (+ 2 vtable-offset-user))
733 `(lambda ,field-names
734 (make-struct ',rtd 0 ,@(map (lambda (f)
735 (if (memq f field-names)
738 (record-type-fields rtd)))))))
740 (define (record-predicate rtd)
741 (lambda (obj) (and (struct? obj) (eq? rtd (struct-vtable obj)))))
743 (define (%record-type-error rtd obj) ;; private helper
744 (or (eq? rtd (record-type-descriptor obj))
745 (scm-error 'wrong-type-arg "%record-type-check"
746 "Wrong type record (want `~S'): ~S"
747 (list (record-type-name rtd) obj)
750 (define (record-accessor rtd field-name)
751 (let ((pos (list-index (record-type-fields rtd) field-name)))
753 (error 'no-such-field field-name))
755 (if (eq? (struct-vtable obj) rtd)
757 (%record-type-error rtd obj)))))
759 (define (record-modifier rtd field-name)
760 (let ((pos (list-index (record-type-fields rtd) field-name)))
762 (error 'no-such-field field-name))
764 (if (eq? (struct-vtable obj) rtd)
765 (struct-set! obj pos val)
766 (%record-type-error rtd obj)))))
768 (define (record? obj)
769 (and (struct? obj) (record-type? (struct-vtable obj))))
771 (define (record-type-descriptor obj)
774 (error 'not-a-record obj)))
783 (define (->bool x) (not (not x)))
790 (define (symbol-append . args)
791 (string->symbol (apply string-append (map symbol->string args))))
793 (define (list->symbol . args)
794 (string->symbol (apply list->string args)))
796 (define (symbol . args)
797 (string->symbol (apply string args)))
804 (define (list-index l k)
810 (loop (+ n 1) (cdr l))))))
814 (if (provided? 'posix)
815 (primitive-load-path "ice-9/posix"))
817 (if (provided? 'socket)
818 (primitive-load-path "ice-9/networking"))
820 ;; For reference, Emacs file-exists-p uses stat in this same way.
822 (if (provided? 'posix)
824 (->bool (stat str #f)))
826 (let ((port (catch 'system-error (lambda () (open-file str OPEN_READ))
828 (if port (begin (close-port port) #t)
831 (define file-is-directory?
832 (if (provided? 'posix)
834 (eq? (stat:type (stat str)) 'directory))
836 (let ((port (catch 'system-error
837 (lambda () (open-file (string-append str "/.")
840 (if port (begin (close-port port) #t)
843 (define (has-suffix? str suffix)
844 (string-suffix? suffix str))
846 (define (system-error-errno args)
847 (if (eq? (car args) 'system-error)
848 (car (list-ref args 4))
856 (define (error . args)
859 (scm-error 'misc-error #f "?" #f #f)
860 (let loop ((msg "~A")
862 (if (not (null? rest))
863 (loop (string-append msg " ~S")
865 (scm-error 'misc-error #f msg args #f)))))
867 ;; bad-throw is the hook that is called upon a throw to a an unhandled
868 ;; key (unless the throw has four arguments, in which case
869 ;; it's usually interpreted as an error throw.)
870 ;; If the key has a default handler (a throw-handler-default property),
871 ;; it is applied to the throw.
873 (define (bad-throw key . args)
874 (let ((default (symbol-property key 'throw-handler-default)))
875 (or (and default (apply default key args))
876 (apply error "unhandled-exception:" key args))))
880 (define (tm:sec obj) (vector-ref obj 0))
881 (define (tm:min obj) (vector-ref obj 1))
882 (define (tm:hour obj) (vector-ref obj 2))
883 (define (tm:mday obj) (vector-ref obj 3))
884 (define (tm:mon obj) (vector-ref obj 4))
885 (define (tm:year obj) (vector-ref obj 5))
886 (define (tm:wday obj) (vector-ref obj 6))
887 (define (tm:yday obj) (vector-ref obj 7))
888 (define (tm:isdst obj) (vector-ref obj 8))
889 (define (tm:gmtoff obj) (vector-ref obj 9))
890 (define (tm:zone obj) (vector-ref obj 10))
892 (define (set-tm:sec obj val) (vector-set! obj 0 val))
893 (define (set-tm:min obj val) (vector-set! obj 1 val))
894 (define (set-tm:hour obj val) (vector-set! obj 2 val))
895 (define (set-tm:mday obj val) (vector-set! obj 3 val))
896 (define (set-tm:mon obj val) (vector-set! obj 4 val))
897 (define (set-tm:year obj val) (vector-set! obj 5 val))
898 (define (set-tm:wday obj val) (vector-set! obj 6 val))
899 (define (set-tm:yday obj val) (vector-set! obj 7 val))
900 (define (set-tm:isdst obj val) (vector-set! obj 8 val))
901 (define (set-tm:gmtoff obj val) (vector-set! obj 9 val))
902 (define (set-tm:zone obj val) (vector-set! obj 10 val))
904 (define (tms:clock obj) (vector-ref obj 0))
905 (define (tms:utime obj) (vector-ref obj 1))
906 (define (tms:stime obj) (vector-ref obj 2))
907 (define (tms:cutime obj) (vector-ref obj 3))
908 (define (tms:cstime obj) (vector-ref obj 4))
910 (define file-position ftell)
911 (define* (file-set-position port offset #:optional (whence SEEK_SET))
912 (seek port offset whence))
914 (define (move->fdes fd/port fd)
915 (cond ((integer? fd/port)
916 (dup->fdes fd/port fd)
920 (primitive-move->fdes fd/port fd)
921 (set-port-revealed! fd/port 1)
924 (define (release-port-handle port)
925 (let ((revealed (port-revealed port)))
927 (set-port-revealed! port (- revealed 1)))))
932 (fdopen (dup->fdes port/fd) mode))
933 ((port/fd mode new-fd)
934 (let ((port (fdopen (dup->fdes port/fd new-fd) mode)))
935 (set-port-revealed! port 1)
941 (dup->port port/fd "r"))
943 (dup->port port/fd "r" new-fd))))
948 (dup->port port/fd "w"))
950 (dup->port port/fd "w" new-fd))))
955 (if (integer? port/fd)
957 (dup->port port/fd (port-mode port/fd))))
959 (if (integer? port/fd)
960 (dup->fdes port/fd new-fd)
961 (dup->port port/fd (port-mode port/fd) new-fd)))))
963 (define (duplicate-port port modes)
964 (dup->port port modes))
966 (define (fdes->inport fdes)
967 (let loop ((rest-ports (fdes->ports fdes)))
968 (cond ((null? rest-ports)
969 (let ((result (fdopen fdes "r")))
970 (set-port-revealed! result 1)
972 ((input-port? (car rest-ports))
973 (set-port-revealed! (car rest-ports)
974 (+ (port-revealed (car rest-ports)) 1))
977 (loop (cdr rest-ports))))))
979 (define (fdes->outport fdes)
980 (let loop ((rest-ports (fdes->ports fdes)))
981 (cond ((null? rest-ports)
982 (let ((result (fdopen fdes "w")))
983 (set-port-revealed! result 1)
985 ((output-port? (car rest-ports))
986 (set-port-revealed! (car rest-ports)
987 (+ (port-revealed (car rest-ports)) 1))
990 (loop (cdr rest-ports))))))
992 (define (port->fdes port)
993 (set-port-revealed! port (+ (port-revealed port) 1))
996 (define (setenv name value)
998 (putenv (string-append name "=" value))
1001 (define (unsetenv name)
1002 "Remove the entry for NAME from the environment."
1010 ;;; Here for backward compatability
1012 (define scheme-file-suffix (lambda () ".scm"))
1014 (define (in-vicinity vicinity file)
1015 (let ((tail (let ((len (string-length vicinity)))
1018 (string-ref vicinity (- len 1))))))
1019 (string-append vicinity
1028 ;;; {Help for scm_shell}
1030 ;;; The argument-processing code used by Guile-based shells generates
1031 ;;; Scheme code based on the argument list. This page contains help
1032 ;;; functions for the code it generates.
1035 (define (command-line) (program-arguments))
1037 ;; This is mostly for the internal use of the code generated by
1038 ;; scm_compile_shell_switches.
1040 (define (turn-on-debugging)
1041 (debug-enable 'debug)
1042 (debug-enable 'backtrace)
1043 (read-enable 'positions))
1045 (define (load-user-init)
1046 (let* ((home (or (getenv "HOME")
1047 (false-if-exception (passwd:dir (getpwuid (getuid))))
1048 "/")) ;; fallback for cygwin etc.
1049 (init-file (in-vicinity home ".guile")))
1050 (if (file-exists? init-file)
1051 (primitive-load init-file))))
1055 ;;; {The interpreter stack}
1058 ;; %stacks defined in stacks.c
1059 (define (%start-stack tag thunk)
1060 (let ((prompt-tag (make-prompt-tag "start-stack")))
1064 (with-fluids ((%stacks (acons tag prompt-tag
1065 (or (fluid-ref %stacks) '()))))
1068 (%start-stack tag (lambda () (apply k args)))))))
1069 (define-syntax start-stack
1072 (%start-stack tag (lambda () exp)))))
1076 ;;; {Loading by paths}
1079 ;;; Load a Scheme source file named NAME, searching for it in the
1080 ;;; directories listed in %load-path, and applying each of the file
1081 ;;; name extensions listed in %load-extensions.
1082 (define (load-from-path name)
1083 (start-stack 'load-stack
1084 (primitive-load-path name)))
1086 (define %load-verbosely #f)
1087 (define (assert-load-verbosity v) (set! %load-verbosely v))
1089 (define (%load-announce file)
1091 (with-output-to-port (current-error-port)
1094 (display "loading ")
1099 (set! %load-hook %load-announce)
1101 (define* (load name #:optional reader)
1102 ;; Returns the .go file corresponding to `name'. Does not search load
1103 ;; paths, only the fallback path. If the .go file is missing or out of
1104 ;; date, and autocompilation is enabled, will try autocompilation, just
1105 ;; as primitive-load-path does internally. primitive-load is
1106 ;; unaffected. Returns #f if autocompilation failed or was disabled.
1108 ;; NB: Unless we need to compile the file, this function should not cause
1109 ;; (system base compile) to be loaded up. For that reason compiled-file-name
1110 ;; partially duplicates functionality from (system base compile).
1111 (define (compiled-file-name canon-path)
1112 (and %compile-fallback-path
1114 %compile-fallback-path
1115 ;; no need for '/' separator here, canon-path is absolute
1117 (cond ((or (null? %load-compiled-extensions)
1118 (string-null? (car %load-compiled-extensions)))
1119 (warn "invalid %load-compiled-extensions"
1120 %load-compiled-extensions)
1122 (else (car %load-compiled-extensions))))))
1123 (define (fresh-compiled-file-name go-path)
1126 (let* ((scmstat (stat name))
1127 (gostat (stat go-path #f)))
1128 (if (and gostat (= (stat:mtime gostat) (stat:mtime scmstat)))
1132 (format (current-error-port)
1133 ";;; note: source file ~a\n;;; newer than compiled ~a\n"
1136 (%load-should-autocompile
1137 (%warn-autocompilation-enabled)
1138 (format (current-error-port) ";;; compiling ~a\n" name)
1139 (let ((cfn ((@ (system base compile) compile-file) name
1140 #:env (current-module))))
1141 (format (current-error-port) ";;; compiled ~a\n" cfn)
1145 (format (current-error-port)
1146 ";;; WARNING: compilation of ~a failed:\n;;; key ~a, throw_args ~s\n"
1149 (with-fluids ((current-reader reader))
1150 (let ((cfn (and=> (and=> (false-if-exception (canonicalize-path name))
1152 fresh-compiled-file-name)))
1155 (start-stack 'load-stack
1156 (primitive-load name))))))
1160 ;;; {Reader Extensions}
1162 ;;; Reader code for various "#c" forms.
1165 (define read-eval? (make-fluid))
1166 (fluid-set! read-eval? #f)
1167 (read-hash-extend #\.
1169 (if (fluid-ref read-eval?)
1170 (eval (read port) (interaction-environment))
1172 "#. read expansion found and read-eval? is #f."))))
1176 ;;; {Command Line Options}
1179 (define (get-option argv kw-opts kw-args return)
1182 (return #f #f argv))
1184 ((or (not (eq? #\- (string-ref (car argv) 0)))
1185 (eq? (string-length (car argv)) 1))
1186 (return 'normal-arg (car argv) (cdr argv)))
1188 ((eq? #\- (string-ref (car argv) 1))
1189 (let* ((kw-arg-pos (or (string-index (car argv) #\=)
1190 (string-length (car argv))))
1191 (kw (symbol->keyword (substring (car argv) 2 kw-arg-pos)))
1192 (kw-opt? (member kw kw-opts))
1193 (kw-arg? (member kw kw-args))
1194 (arg (or (and (not (eq? kw-arg-pos (string-length (car argv))))
1195 (substring (car argv)
1197 (string-length (car argv))))
1199 (begin (set! argv (cdr argv)) (car argv))))))
1200 (if (or kw-opt? kw-arg?)
1201 (return kw arg (cdr argv))
1202 (return 'usage-error kw (cdr argv)))))
1205 (let* ((char (substring (car argv) 1 2))
1206 (kw (symbol->keyword char)))
1209 ((member kw kw-opts)
1210 (let* ((rest-car (substring (car argv) 2 (string-length (car argv))))
1211 (new-argv (if (= 0 (string-length rest-car))
1213 (cons (string-append "-" rest-car) (cdr argv)))))
1214 (return kw #f new-argv)))
1216 ((member kw kw-args)
1217 (let* ((rest-car (substring (car argv) 2 (string-length (car argv))))
1218 (arg (if (= 0 (string-length rest-car))
1221 (new-argv (if (= 0 (string-length rest-car))
1224 (return kw arg new-argv)))
1226 (else (return 'usage-error kw argv)))))))
1228 (define (for-next-option proc argv kw-opts kw-args)
1229 (let loop ((argv argv))
1230 (get-option argv kw-opts kw-args
1231 (lambda (opt opt-arg argv)
1232 (and opt (proc opt opt-arg argv loop))))))
1234 (define (display-usage-report kw-desc)
1237 (or (eq? (car kw) #t)
1238 (eq? (car kw) 'else)
1239 (let* ((opt-desc kw)
1240 (help (cadr opt-desc))
1241 (opts (car opt-desc))
1242 (opts-proper (if (string? (car opts)) (cdr opts) opts))
1243 (arg-name (if (string? (car opts))
1244 (string-append "<" (car opts) ">")
1246 (left-part (string-append
1247 (with-output-to-string
1249 (map (lambda (x) (display (keyword->symbol x)) (display " "))
1252 (middle-part (if (and (< (string-length left-part) 30)
1253 (< (string-length help) 40))
1254 (make-string (- 30 (string-length left-part)) #\ )
1257 (display middle-part)
1264 (define (transform-usage-lambda cases)
1265 (let* ((raw-usage (delq! 'else (map car cases)))
1266 (usage-sans-specials (map (lambda (x)
1267 (or (and (not (list? x)) x)
1268 (and (symbol? (car x)) #t)
1269 (and (boolean? (car x)) #t)
1272 (usage-desc (delq! #t usage-sans-specials))
1273 (kw-desc (map car usage-desc))
1274 (kw-opts (apply append (map (lambda (x) (and (not (string? (car x))) x)) kw-desc)))
1275 (kw-args (apply append (map (lambda (x) (and (string? (car x)) (cdr x))) kw-desc)))
1276 (transmogrified-cases (map (lambda (case)
1277 (cons (let ((opts (car case)))
1278 (if (or (boolean? opts) (eq? 'else opts))
1281 ((symbol? (car opts)) opts)
1282 ((boolean? (car opts)) opts)
1283 ((string? (caar opts)) (cdar opts))
1284 (else (car opts)))))
1287 `(let ((%display-usage (lambda () (display-usage-report ',usage-desc))))
1289 (let %next-arg ((%argv %argv))
1293 (lambda (%opt %arg %new-argv)
1295 ,@ transmogrified-cases))))))))
1300 ;;; {Low Level Modules}
1302 ;;; These are the low level data structures for modules.
1304 ;;; Every module object is of the type 'module-type', which is a record
1305 ;;; consisting of the following members:
1307 ;;; - eval-closure: the function that defines for its module the strategy that
1308 ;;; shall be followed when looking up symbols in the module.
1310 ;;; An eval-closure is a function taking two arguments: the symbol to be
1311 ;;; looked up and a boolean value telling whether a binding for the symbol
1312 ;;; should be created if it does not exist yet. If the symbol lookup
1313 ;;; succeeded (either because an existing binding was found or because a new
1314 ;;; binding was created), a variable object representing the binding is
1315 ;;; returned. Otherwise, the value #f is returned. Note that the eval
1316 ;;; closure does not take the module to be searched as an argument: During
1317 ;;; construction of the eval-closure, the eval-closure has to store the
1318 ;;; module it belongs to in its environment. This means, that any
1319 ;;; eval-closure can belong to only one module.
1321 ;;; The eval-closure of a module can be defined arbitrarily. However, three
1322 ;;; special cases of eval-closures are to be distinguished: During startup
1323 ;;; the module system is not yet activated. In this phase, no modules are
1324 ;;; defined and all bindings are automatically stored by the system in the
1325 ;;; pre-modules-obarray. Since no eval-closures exist at this time, the
1326 ;;; functions which require an eval-closure as their argument need to be
1327 ;;; passed the value #f.
1329 ;;; The other two special cases of eval-closures are the
1330 ;;; standard-eval-closure and the standard-interface-eval-closure. Both
1331 ;;; behave equally for the case that no new binding is to be created. The
1332 ;;; difference between the two comes in, when the boolean argument to the
1333 ;;; eval-closure indicates that a new binding shall be created if it is not
1336 ;;; Given that no new binding shall be created, both standard eval-closures
1337 ;;; define the following standard strategy of searching bindings in the
1338 ;;; module: First, the module's obarray is searched for the symbol. Second,
1339 ;;; if no binding for the symbol was found in the module's obarray, the
1340 ;;; module's binder procedure is exececuted. If this procedure did not
1341 ;;; return a binding for the symbol, the modules referenced in the module's
1342 ;;; uses list are recursively searched for a binding of the symbol. If the
1343 ;;; binding can not be found in these modules also, the symbol lookup has
1346 ;;; If a new binding shall be created, the standard-interface-eval-closure
1347 ;;; immediately returns indicating failure. That is, it does not even try
1348 ;;; to look up the symbol. In contrast, the standard-eval-closure would
1349 ;;; first search the obarray, and if no binding was found there, would
1350 ;;; create a new binding in the obarray, therefore not calling the binder
1351 ;;; procedure or searching the modules in the uses list.
1353 ;;; The explanation of the following members obarray, binder and uses
1354 ;;; assumes that the symbol lookup follows the strategy that is defined in
1355 ;;; the standard-eval-closure and the standard-interface-eval-closure.
1357 ;;; - obarray: a hash table that maps symbols to variable objects. In this
1358 ;;; hash table, the definitions are found that are local to the module (that
1359 ;;; is, not imported from other modules). When looking up bindings in the
1360 ;;; module, this hash table is searched first.
1362 ;;; - binder: either #f or a function taking a module and a symbol argument.
1363 ;;; If it is a function it is called after the obarray has been
1364 ;;; unsuccessfully searched for a binding. It then can provide bindings
1365 ;;; that would otherwise not be found locally in the module.
1367 ;;; - uses: a list of modules from which non-local bindings can be inherited.
1368 ;;; These modules are the third place queried for bindings after the obarray
1369 ;;; has been unsuccessfully searched and the binder function did not deliver
1370 ;;; a result either.
1372 ;;; - transformer: either #f or a function taking a scheme expression as
1373 ;;; delivered by read. If it is a function, it will be called to perform
1374 ;;; syntax transformations (e. g. makro expansion) on the given scheme
1375 ;;; expression. The output of the transformer function will then be passed
1376 ;;; to Guile's internal memoizer. This means that the output must be valid
1377 ;;; scheme code. The only exception is, that the output may make use of the
1378 ;;; syntax extensions provided to identify the modules that a binding
1381 ;;; - name: the name of the module. This is used for all kinds of printing
1382 ;;; outputs. In certain places the module name also serves as a way of
1383 ;;; identification. When adding a module to the uses list of another
1384 ;;; module, it is made sure that the new uses list will not contain two
1385 ;;; modules of the same name.
1387 ;;; - kind: classification of the kind of module. The value is (currently?)
1388 ;;; only used for printing. It has no influence on how a module is treated.
1389 ;;; Currently the following values are used when setting the module kind:
1390 ;;; 'module, 'directory, 'interface, 'custom-interface. If no explicit kind
1391 ;;; is set, it defaults to 'module.
1393 ;;; - duplicates-handlers: a list of procedures that get called to make a
1394 ;;; choice between two duplicate bindings when name clashes occur. See the
1395 ;;; `duplicate-handlers' global variable below.
1397 ;;; - observers: a list of procedures that get called when the module is
1400 ;;; - weak-observers: a weak-key hash table of procedures that get called
1401 ;;; when the module is modified. See `module-observe-weak' for details.
1403 ;;; In addition, the module may (must?) contain a binding for
1404 ;;; `%module-public-interface'. This variable should be bound to a module
1405 ;;; representing the exported interface of a module. See the
1406 ;;; `module-public-interface' and `module-export!' procedures.
1408 ;;; !!! warning: The interface to lazy binder procedures is going
1409 ;;; to be changed in an incompatible way to permit all the basic
1410 ;;; module ops to be virtualized.
1412 ;;; (make-module size use-list lazy-binding-proc) => module
1413 ;;; module-{obarray,uses,binder}[|-set!]
1414 ;;; (module? obj) => [#t|#f]
1415 ;;; (module-locally-bound? module symbol) => [#t|#f]
1416 ;;; (module-bound? module symbol) => [#t|#f]
1417 ;;; (module-symbol-locally-interned? module symbol) => [#t|#f]
1418 ;;; (module-symbol-interned? module symbol) => [#t|#f]
1419 ;;; (module-local-variable module symbol) => [#<variable ...> | #f]
1420 ;;; (module-variable module symbol) => [#<variable ...> | #f]
1421 ;;; (module-symbol-binding module symbol opt-value)
1422 ;;; => [ <obj> | opt-value | an error occurs ]
1423 ;;; (module-make-local-var! module symbol) => #<variable...>
1424 ;;; (module-add! module symbol var) => unspecified
1425 ;;; (module-remove! module symbol) => unspecified
1426 ;;; (module-for-each proc module) => unspecified
1427 ;;; (make-scm-module) => module ; a lazy copy of the symhash module
1428 ;;; (set-current-module module) => unspecified
1429 ;;; (current-module) => #<module...>
1435 ;;; {Printing Modules}
1438 ;; This is how modules are printed. You can re-define it.
1439 (define (%print-module mod port)
1441 (display (or (module-kind mod) "module") port)
1443 (display (module-name mod) port)
1445 (display (number->string (object-address mod) 16) port)
1449 ;; Locally extend the syntax to allow record accessors to be defined at
1450 ;; compile-time. Cache the rtd locally to the constructor, the getters and
1451 ;; the setters, in order to allow for redefinition of the record type; not
1452 ;; relevant in the case of modules, but perhaps if we make this public, it
1455 ((define-record-type
1457 (define (make-id scope . fragments)
1458 (datum->syntax #'scope
1459 (apply symbol-append
1461 (if (symbol? x) x (syntax->datum x)))
1464 (define (getter rtd type-name field slot)
1465 #`(define #,(make-id rtd type-name '- field)
1467 (lambda (#,type-name)
1468 (if (eq? (struct-vtable #,type-name) rtd)
1469 (struct-ref #,type-name #,slot)
1470 (%record-type-error rtd #,type-name))))))
1472 (define (setter rtd type-name field slot)
1473 #`(define #,(make-id rtd 'set- type-name '- field '!)
1475 (lambda (#,type-name val)
1476 (if (eq? (struct-vtable #,type-name) rtd)
1477 (struct-set! #,type-name #,slot val)
1478 (%record-type-error rtd #,type-name))))))
1480 (define (accessors rtd type-name fields n exp)
1481 (syntax-case fields ()
1483 (((field #:no-accessors) field* ...) (identifier? #'field)
1484 (accessors rtd type-name #'(field* ...) (1+ n)
1486 (((field #:no-setter) field* ...) (identifier? #'field)
1487 (accessors rtd type-name #'(field* ...) (1+ n)
1489 #,(getter rtd type-name #'field n))))
1490 (((field #:no-getter) field* ...) (identifier? #'field)
1491 (accessors rtd type-name #'(field* ...) (1+ n)
1493 #,(setter rtd type-name #'field n))))
1494 ((field field* ...) (identifier? #'field)
1495 (accessors rtd type-name #'(field* ...) (1+ n)
1497 #,(getter rtd type-name #'field n)
1498 #,(setter rtd type-name #'field n))))))
1500 (define (predicate rtd type-name fields exp)
1502 rtd type-name fields 0
1505 (define (#,(make-id rtd type-name '?) obj)
1506 (and (struct? obj) (eq? (struct-vtable obj) #,rtd))))))
1508 (define (field-list fields)
1509 (syntax-case fields ()
1511 (((f . opts) . rest) (identifier? #'f)
1512 (cons #'f (field-list #'rest)))
1513 ((f . rest) (identifier? #'f)
1514 (cons #'f (field-list #'rest)))))
1516 (define (constructor rtd type-name fields exp)
1517 (let ((ctor (make-id rtd type-name '-constructor))
1518 (args (field-list fields)))
1519 (predicate rtd type-name fields
1524 (make-struct rtd 0 #,@args))))
1525 (struct-set! #,rtd (+ vtable-offset-user 2)
1528 (define (type type-name printer fields)
1529 (define (make-layout)
1530 (let lp ((fields fields) (slots '()))
1531 (syntax-case fields ()
1532 (() (datum->syntax #'here
1534 (apply string-append slots))))
1535 ((_ . rest) (lp #'rest (cons "pw" slots))))))
1537 (let ((rtd (make-id type-name type-name '-type)))
1538 (constructor rtd type-name fields
1541 (make-struct record-type-vtable 0
1545 '#,(field-list fields)))
1546 (set-struct-vtable-name! #,rtd '#,type-name)))))
1549 ((_ type-name printer (field ...))
1550 (type #'type-name #'printer #'(field ...)))))))
1554 ;; A module is characterized by an obarray in which local symbols
1555 ;; are interned, a list of modules, "uses", from which non-local
1556 ;; bindings can be inherited, and an optional lazy-binder which
1557 ;; is a (CLOSURE module symbol) which, as a last resort, can provide
1558 ;; bindings that would otherwise not be found locally in the module.
1560 ;; NOTE: If you change the set of fields or their order, you also need to
1561 ;; change the constants in libguile/modules.h.
1563 ;; NOTE: The getter `module-eval-closure' is used in libguile/modules.c.
1564 ;; NOTE: The getter `module-transfomer' is defined libguile/modules.c.
1565 ;; NOTE: The getter `module-name' is defined later, due to boot reasons.
1566 ;; NOTE: The getter `module-public-interface' is used in libguile/modules.c.
1568 (define-record-type module
1569 (lambda (obj port) (%print-module obj port))
1574 (transformer #:no-getter)
1578 (import-obarray #:no-setter)
1580 (weak-observers #:no-setter)
1588 ;; make-module &opt size uses binder
1590 ;; Create a new module, perhaps with a particular size of obarray,
1591 ;; initial uses list, or binding procedure.
1596 (define (parse-arg index default)
1597 (if (> (length args) index)
1598 (list-ref args index)
1601 (define %default-import-size
1602 ;; Typical number of imported bindings actually used by a module.
1605 (if (> (length args) 3)
1606 (error "Too many args to make-module." args))
1608 (let ((size (parse-arg 0 31))
1609 (uses (parse-arg 1 '()))
1610 (binder (parse-arg 2 #f)))
1612 (if (not (integer? size))
1613 (error "Illegal size to make-module." size))
1614 (if (not (and (list? uses)
1615 (and-map module? uses)))
1616 (error "Incorrect use list." uses))
1617 (if (and binder (not (procedure? binder)))
1619 "Lazy-binder expected to be a procedure or #f." binder))
1621 (let ((module (module-constructor (make-hash-table size)
1622 uses binder #f macroexpand
1624 (make-hash-table %default-import-size)
1626 (make-weak-key-hash-table 31) #f
1627 (make-hash-table 7) #f #f #f)))
1629 ;; We can't pass this as an argument to module-constructor,
1630 ;; because we need it to close over a pointer to the module
1632 (set-module-eval-closure! module (standard-eval-closure module))
1639 ;;; {Observer protocol}
1642 (define (module-observe module proc)
1643 (set-module-observers! module (cons proc (module-observers module)))
1646 (define* (module-observe-weak module observer-id #:optional (proc observer-id))
1647 ;; Register PROC as an observer of MODULE under name OBSERVER-ID (which can
1648 ;; be any Scheme object). PROC is invoked and passed MODULE any time
1649 ;; MODULE is modified. PROC gets unregistered when OBSERVER-ID gets GC'd
1650 ;; (thus, it is never unregistered if OBSERVER-ID is an immediate value,
1653 ;; The two-argument version is kept for backward compatibility: when called
1654 ;; with two arguments, the observer gets unregistered when closure PROC
1655 ;; gets GC'd (making it impossible to use an anonymous lambda for PROC).
1656 (hashq-set! (module-weak-observers module) observer-id proc))
1658 (define (module-unobserve token)
1659 (let ((module (car token))
1662 (hash-remove! (module-weak-observers module) id)
1663 (set-module-observers! module (delq1! id (module-observers module)))))
1666 (define module-defer-observers #f)
1667 (define module-defer-observers-mutex (make-mutex 'recursive))
1668 (define module-defer-observers-table (make-hash-table))
1670 (define (module-modified m)
1671 (if module-defer-observers
1672 (hash-set! module-defer-observers-table m #t)
1673 (module-call-observers m)))
1675 ;;; This function can be used to delay calls to observers so that they
1676 ;;; can be called once only in the face of massive updating of modules.
1678 (define (call-with-deferred-observers thunk)
1681 (lock-mutex module-defer-observers-mutex)
1682 (set! module-defer-observers #t))
1685 (set! module-defer-observers #f)
1686 (hash-for-each (lambda (m dummy)
1687 (module-call-observers m))
1688 module-defer-observers-table)
1689 (hash-clear! module-defer-observers-table)
1690 (unlock-mutex module-defer-observers-mutex))))
1692 (define (module-call-observers m)
1693 (for-each (lambda (proc) (proc m)) (module-observers m))
1695 ;; We assume that weak observers don't (un)register themselves as they are
1696 ;; called since this would preclude proper iteration over the hash table
1698 (hash-for-each (lambda (id proc) (proc m)) (module-weak-observers m)))
1702 ;;; {Module Searching in General}
1704 ;;; We sometimes want to look for properties of a symbol
1705 ;;; just within the obarray of one module. If the property
1706 ;;; holds, then it is said to hold ``locally'' as in, ``The symbol
1707 ;;; DISPLAY is locally rebound in the module `safe-guile'.''
1710 ;;; Other times, we want to test for a symbol property in the obarray
1711 ;;; of M and, if it is not found there, try each of the modules in the
1712 ;;; uses list of M. This is the normal way of testing for some
1713 ;;; property, so we state these properties without qualification as
1714 ;;; in: ``The symbol 'fnord is interned in module M because it is
1715 ;;; interned locally in module M2 which is a member of the uses list
1719 ;; module-search fn m
1721 ;; return the first non-#f result of FN applied to M and then to
1722 ;; the modules in the uses of m, and so on recursively. If all applications
1723 ;; return #f, then so does this function.
1725 (define (module-search fn m v)
1728 (or (module-search fn (car pos) v)
1731 (loop (module-uses m))))
1734 ;;; {Is a symbol bound in a module?}
1736 ;;; Symbol S in Module M is bound if S is interned in M and if the binding
1737 ;;; of S in M has been set to some well-defined value.
1740 ;; module-locally-bound? module symbol
1742 ;; Is a symbol bound (interned and defined) locally in a given module?
1744 (define (module-locally-bound? m v)
1745 (let ((var (module-local-variable m v)))
1747 (variable-bound? var))))
1749 ;; module-bound? module symbol
1751 ;; Is a symbol bound (interned and defined) anywhere in a given module
1754 (define (module-bound? m v)
1755 (let ((var (module-variable m v)))
1757 (variable-bound? var))))
1759 ;;; {Is a symbol interned in a module?}
1761 ;;; Symbol S in Module M is interned if S occurs in
1762 ;;; of S in M has been set to some well-defined value.
1764 ;;; It is possible to intern a symbol in a module without providing
1765 ;;; an initial binding for the corresponding variable. This is done
1767 ;;; (module-add! module symbol (make-undefined-variable))
1769 ;;; In that case, the symbol is interned in the module, but not
1770 ;;; bound there. The unbound symbol shadows any binding for that
1771 ;;; symbol that might otherwise be inherited from a member of the uses list.
1774 (define (module-obarray-get-handle ob key)
1775 ((if (symbol? key) hashq-get-handle hash-get-handle) ob key))
1777 (define (module-obarray-ref ob key)
1778 ((if (symbol? key) hashq-ref hash-ref) ob key))
1780 (define (module-obarray-set! ob key val)
1781 ((if (symbol? key) hashq-set! hash-set!) ob key val))
1783 (define (module-obarray-remove! ob key)
1784 ((if (symbol? key) hashq-remove! hash-remove!) ob key))
1786 ;; module-symbol-locally-interned? module symbol
1788 ;; is a symbol interned (not neccessarily defined) locally in a given module
1789 ;; or its uses? Interned symbols shadow inherited bindings even if
1790 ;; they are not themselves bound to a defined value.
1792 (define (module-symbol-locally-interned? m v)
1793 (not (not (module-obarray-get-handle (module-obarray m) v))))
1795 ;; module-symbol-interned? module symbol
1797 ;; is a symbol interned (not neccessarily defined) anywhere in a given module
1798 ;; or its uses? Interned symbols shadow inherited bindings even if
1799 ;; they are not themselves bound to a defined value.
1801 (define (module-symbol-interned? m v)
1802 (module-search module-symbol-locally-interned? m v))
1805 ;;; {Mapping modules x symbols --> variables}
1808 ;; module-local-variable module symbol
1809 ;; return the local variable associated with a MODULE and SYMBOL.
1811 ;;; This function is very important. It is the only function that can
1812 ;;; return a variable from a module other than the mutators that store
1813 ;;; new variables in modules. Therefore, this function is the location
1814 ;;; of the "lazy binder" hack.
1816 ;;; If symbol is defined in MODULE, and if the definition binds symbol
1817 ;;; to a variable, return that variable object.
1819 ;;; If the symbols is not found at first, but the module has a lazy binder,
1820 ;;; then try the binder.
1822 ;;; If the symbol is not found at all, return #f.
1824 ;;; (This is now written in C, see `modules.c'.)
1827 ;;; {Mapping modules x symbols --> bindings}
1829 ;;; These are similar to the mapping to variables, except that the
1830 ;;; variable is dereferenced.
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-local-binding m v . opt-val)
1841 (let ((var (module-local-variable m v)))
1842 (if (and var (variable-bound? var))
1844 (if (not (null? opt-val))
1846 (error "Locally unbound variable." v)))))
1848 ;; module-symbol-binding module symbol opt-value
1850 ;; return the binding of a variable specified by name within
1851 ;; a given module, signalling an error if the variable is unbound.
1852 ;; If the OPT-VALUE is passed, then instead of signalling an error,
1853 ;; return OPT-VALUE.
1855 (define (module-symbol-binding m v . opt-val)
1856 (let ((var (module-variable m v)))
1857 (if (and var (variable-bound? var))
1859 (if (not (null? opt-val))
1861 (error "Unbound variable." v)))))
1866 ;;; {Adding Variables to Modules}
1869 ;; module-make-local-var! module symbol
1871 ;; ensure a variable for V in the local namespace of M.
1872 ;; If no variable was already there, then create a new and uninitialzied
1875 ;; This function is used in modules.c.
1877 (define (module-make-local-var! m v)
1878 (or (let ((b (module-obarray-ref (module-obarray m) v)))
1881 ;; Mark as modified since this function is called when
1882 ;; the standard eval closure defines a binding
1886 ;; Create a new local variable.
1887 (let ((local-var (make-undefined-variable)))
1888 (module-add! m v local-var)
1891 ;; module-ensure-local-variable! module symbol
1893 ;; Ensure that there is a local variable in MODULE for SYMBOL. If
1894 ;; there is no binding for SYMBOL, create a new uninitialized
1895 ;; variable. Return the local variable.
1897 (define (module-ensure-local-variable! module symbol)
1898 (or (module-local-variable module symbol)
1899 (let ((var (make-undefined-variable)))
1900 (module-add! module symbol var)
1903 ;; module-add! module symbol var
1905 ;; ensure a particular variable for V in the local namespace of M.
1907 (define (module-add! m v var)
1908 (if (not (variable? var))
1909 (error "Bad variable to module-add!" var))
1910 (module-obarray-set! (module-obarray m) v var)
1911 (module-modified m))
1915 ;; make sure that a symbol is undefined in the local namespace of M.
1917 (define (module-remove! m v)
1918 (module-obarray-remove! (module-obarray m) v)
1919 (module-modified m))
1921 (define (module-clear! m)
1922 (hash-clear! (module-obarray m))
1923 (module-modified m))
1925 ;; MODULE-FOR-EACH -- exported
1927 ;; Call PROC on each symbol in MODULE, with arguments of (SYMBOL VARIABLE).
1929 (define (module-for-each proc module)
1930 (hash-for-each proc (module-obarray module)))
1932 (define (module-map proc module)
1933 (hash-map->list proc (module-obarray module)))
1937 ;; Modules exist in a separate namespace from values, because you generally do
1938 ;; not want the name of a submodule, which you might not even use, to collide
1939 ;; with local variables that happen to be named the same as the submodule.
1941 (define (module-ref-submodule module name)
1942 (or (hashq-ref (module-submodules module) name)
1943 (and (module-submodule-binder module)
1944 ((module-submodule-binder module) module name))))
1946 (define (module-define-submodule! module name submodule)
1947 (hashq-set! (module-submodules module) name submodule))
1951 ;;; {Low Level Bootstrapping}
1956 ;; A root module uses the pre-modules-obarray as its obarray. This
1957 ;; special obarray accumulates all bindings that have been established
1958 ;; before the module system is fully booted.
1960 ;; (The obarray continues to be used by code that has been closed over
1961 ;; before the module system has been booted.)
1963 (define (make-root-module)
1964 (let ((m (make-module 0)))
1965 (set-module-obarray! m (%get-pre-modules-obarray))
1970 ;; The root interface is a module that uses the same obarray as the
1971 ;; root module. It does not allow new definitions, tho.
1973 (define (make-scm-module)
1974 (let ((m (make-module 0)))
1975 (set-module-obarray! m (%get-pre-modules-obarray))
1976 (set-module-eval-closure! m (standard-interface-eval-closure m))
1982 ;;; {Module-based Loading}
1985 (define (save-module-excursion thunk)
1986 (let ((inner-module (current-module))
1988 (dynamic-wind (lambda ()
1989 (set! outer-module (current-module))
1990 (set-current-module inner-module)
1991 (set! inner-module #f))
1994 (set! inner-module (current-module))
1995 (set-current-module outer-module)
1996 (set! outer-module #f)))))
1998 (define basic-load load)
2000 (define* (load-module filename #:optional reader)
2001 (save-module-excursion
2003 (let ((oldname (and (current-load-port)
2004 (port-filename (current-load-port)))))
2005 (basic-load (if (and oldname
2006 (> (string-length filename) 0)
2007 (not (char=? (string-ref filename 0) #\/))
2008 (not (string=? (dirname oldname) ".")))
2009 (string-append (dirname oldname) "/" filename)
2016 ;;; {MODULE-REF -- exported}
2019 ;; Returns the value of a variable called NAME in MODULE or any of its
2020 ;; used modules. If there is no such variable, then if the optional third
2021 ;; argument DEFAULT is present, it is returned; otherwise an error is signaled.
2023 (define (module-ref module name . rest)
2024 (let ((variable (module-variable module name)))
2025 (if (and variable (variable-bound? variable))
2026 (variable-ref variable)
2028 (error "No variable named" name 'in module)
2029 (car rest) ; default value
2032 ;; MODULE-SET! -- exported
2034 ;; Sets the variable called NAME in MODULE (or in a module that MODULE uses)
2035 ;; to VALUE; if there is no such variable, an error is signaled.
2037 (define (module-set! module name value)
2038 (let ((variable (module-variable module name)))
2040 (variable-set! variable value)
2041 (error "No variable named" name 'in module))))
2043 ;; MODULE-DEFINE! -- exported
2045 ;; Sets the variable called NAME in MODULE to VALUE; if there is no such
2046 ;; variable, it is added first.
2048 (define (module-define! module name value)
2049 (let ((variable (module-local-variable module name)))
2052 (variable-set! variable value)
2053 (module-modified module))
2054 (let ((variable (make-variable value)))
2055 (module-add! module name variable)))))
2057 ;; MODULE-DEFINED? -- exported
2059 ;; Return #t iff NAME is defined in MODULE (or in a module that MODULE
2062 (define (module-defined? module name)
2063 (let ((variable (module-variable module name)))
2064 (and variable (variable-bound? variable))))
2066 ;; MODULE-USE! module interface
2068 ;; Add INTERFACE to the list of interfaces used by MODULE.
2070 (define (module-use! module interface)
2071 (if (not (or (eq? module interface)
2072 (memq interface (module-uses module))))
2074 ;; Newly used modules must be appended rather than consed, so that
2075 ;; `module-variable' traverses the use list starting from the first
2077 (set-module-uses! module
2078 (append (filter (lambda (m)
2080 (equal? (module-name m)
2081 (module-name interface))))
2082 (module-uses module))
2084 (hash-clear! (module-import-obarray module))
2085 (module-modified module))))
2087 ;; MODULE-USE-INTERFACES! module interfaces
2089 ;; Same as MODULE-USE! but add multiple interfaces and check for duplicates
2091 (define (module-use-interfaces! module interfaces)
2092 (set-module-uses! module
2093 (append (module-uses module) interfaces))
2094 (hash-clear! (module-import-obarray module))
2095 (module-modified module))
2099 ;;; {Recursive Namespaces}
2101 ;;; A hierarchical namespace emerges if we consider some module to be
2102 ;;; root, and submodules of that module to be nested namespaces.
2104 ;;; The routines here manage variable names in hierarchical namespace.
2105 ;;; Each variable name is a list of elements, looked up in successively nested
2108 ;;; (nested-ref some-root-module '(foo bar baz))
2109 ;;; => <value of a variable named baz in the submodule bar of
2110 ;;; the submodule foo of some-root-module>
2115 ;;; ;; a-root is a module
2116 ;;; ;; name is a list of symbols
2118 ;;; nested-ref a-root name
2119 ;;; nested-set! a-root name val
2120 ;;; nested-define! a-root name val
2121 ;;; nested-remove! a-root name
2123 ;;; These functions manipulate values in namespaces. For referencing the
2124 ;;; namespaces themselves, use the following:
2126 ;;; nested-ref-module a-root name
2127 ;;; nested-define-module! a-root name mod
2129 ;;; (current-module) is a natural choice for a root so for convenience there are
2132 ;;; local-ref name == nested-ref (current-module) name
2133 ;;; local-set! name val == nested-set! (current-module) name val
2134 ;;; local-define name val == nested-define! (current-module) name val
2135 ;;; local-remove name == nested-remove! (current-module) name
2136 ;;; local-ref-module name == nested-ref-module (current-module) name
2137 ;;; local-define-module! name m == nested-define-module! (current-module) name m
2141 (define (nested-ref root names)
2144 (let loop ((cur root)
2148 (module-ref cur head #f)
2149 (let ((cur (module-ref-submodule cur head)))
2151 (loop cur (car tail) (cdr tail))))))))
2153 (define (nested-set! root names val)
2154 (let loop ((cur root)
2158 (module-set! cur head val)
2159 (let ((cur (module-ref-submodule cur head)))
2161 (error "failed to resolve module" names)
2162 (loop cur (car tail) (cdr tail)))))))
2164 (define (nested-define! root names val)
2165 (let loop ((cur root)
2169 (module-define! cur head val)
2170 (let ((cur (module-ref-submodule cur head)))
2172 (error "failed to resolve module" names)
2173 (loop cur (car tail) (cdr tail)))))))
2175 (define (nested-remove! root names)
2176 (let loop ((cur root)
2180 (module-remove! cur head)
2181 (let ((cur (module-ref-submodule cur head)))
2183 (error "failed to resolve module" names)
2184 (loop cur (car tail) (cdr tail)))))))
2187 (define (nested-ref-module root names)
2188 (let loop ((cur root)
2192 (let ((cur (module-ref-submodule cur (car names))))
2194 (loop cur (cdr names)))))))
2196 (define (nested-define-module! root names module)
2198 (error "can't redefine root module" root module)
2199 (let loop ((cur root)
2203 (module-define-submodule! cur head module)
2204 (let ((cur (or (module-ref-submodule cur head)
2205 (let ((m (make-module 31)))
2206 (set-module-kind! m 'directory)
2207 (set-module-name! m (append (module-name cur)
2209 (module-define-submodule! cur head m)
2211 (loop cur (car tail) (cdr tail)))))))
2214 (define (local-ref names) (nested-ref (current-module) names))
2215 (define (local-set! names val) (nested-set! (current-module) names val))
2216 (define (local-define names val) (nested-define! (current-module) names val))
2217 (define (local-remove names) (nested-remove! (current-module) names))
2218 (define (local-ref-module names) (nested-ref-module (current-module) names))
2219 (define (local-define-module names mod) (nested-define-module! (current-module) names mod))
2225 ;;; {The (guile) module}
2227 ;;; The standard module, which has the core Guile bindings. Also called the
2228 ;;; "root module", as it is imported by many other modules, but it is not
2229 ;;; necessarily the root of anything; and indeed, the module named '() might be
2230 ;;; better thought of as a root.
2233 (define (set-system-module! m s)
2234 (set-procedure-property! (module-eval-closure m) 'system-module s))
2235 (define the-root-module (make-root-module))
2236 (define the-scm-module (make-scm-module))
2237 (set-module-public-interface! the-root-module the-scm-module)
2238 (set-module-name! the-root-module '(guile))
2239 (set-module-name! the-scm-module '(guile))
2240 (set-module-kind! the-scm-module 'interface)
2241 (set-system-module! the-root-module #t)
2242 (set-system-module! the-scm-module #t)
2247 ;; Now that we have a root module, even though modules aren't fully booted,
2248 ;; expand the definition of resolve-module.
2250 (define (resolve-module name . args)
2251 (if (equal? name '(guile))
2253 (error "unexpected module to resolve during module boot" name)))
2255 ;; Cheat. These bindings are needed by modules.c, but we don't want
2256 ;; to move their real definition here because that would be unnatural.
2258 (define process-define-module #f)
2259 (define process-use-modules #f)
2260 (define module-export! #f)
2261 (define default-duplicate-binding-procedures #f)
2263 ;; This boots the module system. All bindings needed by modules.c
2264 ;; must have been defined by now.
2266 (set-current-module the-root-module)
2271 ;; Now that modules are booted, give module-name its final definition.
2274 (let ((accessor (record-accessor module-type 'name)))
2277 (let ((name (list (gensym))))
2278 ;; Name MOD and bind it in the module root so that it's visible to
2279 ;; `resolve-module'. This is important as `psyntax' stores module
2280 ;; names and relies on being able to `resolve-module' them.
2281 (set-module-name! mod name)
2282 (nested-define-module! (resolve-module '() #f) name mod)
2285 (define (make-modules-in module name)
2286 (or (nested-ref-module module name)
2287 (let ((m (make-module 31)))
2288 (set-module-kind! m 'directory)
2289 (set-module-name! m (append (module-name module) name))
2290 (nested-define-module! module name m)
2293 (define (beautify-user-module! module)
2294 (let ((interface (module-public-interface module)))
2295 (if (or (not interface)
2296 (eq? interface module))
2297 (let ((interface (make-module 31)))
2298 (set-module-name! interface (module-name module))
2299 (set-module-version! interface (module-version module))
2300 (set-module-kind! interface 'interface)
2301 (set-module-public-interface! module interface))))
2302 (if (and (not (memq the-scm-module (module-uses module)))
2303 (not (eq? module the-root-module)))
2304 ;; Import the default set of bindings (from the SCM module) in MODULE.
2305 (module-use! module the-scm-module)))
2307 (define (version-matches? version-ref target)
2308 (define (any pred lst)
2309 (and (not (null? lst)) (or (pred (car lst)) (any pred (cdr lst)))))
2310 (define (every pred lst)
2311 (or (null? lst) (and (pred (car lst)) (every pred (cdr lst)))))
2312 (define (sub-versions-match? v-refs t)
2313 (define (sub-version-matches? v-ref t)
2314 (define (curried-sub-version-matches? v)
2315 (sub-version-matches? v t))
2316 (cond ((number? v-ref) (eqv? v-ref t))
2318 (let ((cv (car v-ref)))
2319 (cond ((eq? cv '>=) (>= t (cadr v-ref)))
2320 ((eq? cv '<=) (<= t (cadr v-ref)))
2322 (every curried-sub-version-matches? (cdr v-ref)))
2324 (any curried-sub-version-matches? (cdr v-ref)))
2325 ((eq? cv 'not) (not (sub-version-matches? (cadr v-ref) t)))
2326 (else (error "Incompatible sub-version reference" cv)))))
2327 (else (error "Incompatible sub-version reference" v-ref))))
2329 (and (not (null? t))
2330 (sub-version-matches? (car v-refs) (car t))
2331 (sub-versions-match? (cdr v-refs) (cdr t)))))
2332 (define (curried-version-matches? v)
2333 (version-matches? v target))
2334 (or (null? version-ref)
2335 (let ((cv (car version-ref)))
2336 (cond ((eq? cv 'and) (every curried-version-matches? (cdr version-ref)))
2337 ((eq? cv 'or) (any curried-version-matches? (cdr version-ref)))
2338 ((eq? cv 'not) (not (version-matches? (cadr version-ref) target)))
2339 (else (sub-versions-match? version-ref target))))))
2341 (define (find-versioned-module dir-hint name version-ref roots)
2342 (define (subdir-pair-less pair1 pair2)
2343 (define (numlist-less lst1 lst2)
2345 (and (not (null? lst1))
2346 (cond ((> (car lst1) (car lst2)) #t)
2347 ((< (car lst1) (car lst2)) #f)
2348 (else (numlist-less (cdr lst1) (cdr lst2)))))))
2349 (not (numlist-less (car pair2) (car pair1))))
2350 (define (match-version-and-file pair)
2351 (and (version-matches? version-ref (car pair))
2353 (filter (lambda (file)
2354 (let ((s (false-if-exception (stat file))))
2355 (and s (eq? (stat:type s) 'regular))))
2357 (string-append (cdr pair) name ext))
2358 %load-extensions))))
2359 (and (not (null? filenames))
2360 (cons (car pair) (car filenames))))))
2362 (define (match-version-recursive root-pairs leaf-pairs)
2363 (define (filter-subdirs root-pairs ret)
2364 (define (filter-subdir root-pair dstrm subdir-pairs)
2365 (let ((entry (readdir dstrm)))
2366 (if (eof-object? entry)
2368 (let* ((subdir (string-append (cdr root-pair) entry))
2369 (num (string->number entry))
2370 (num (and num (exact? num) (append (car root-pair)
2372 (if (and num (eq? (stat:type (stat subdir)) 'directory))
2374 root-pair dstrm (cons (cons num (string-append subdir "/"))
2376 (filter-subdir root-pair dstrm subdir-pairs))))))
2378 (or (and (null? root-pairs) ret)
2379 (let* ((rp (car root-pairs))
2380 (dstrm (false-if-exception (opendir (cdr rp)))))
2382 (let ((subdir-pairs (filter-subdir rp dstrm '())))
2384 (filter-subdirs (cdr root-pairs)
2385 (or (and (null? subdir-pairs) ret)
2386 (append ret subdir-pairs))))
2387 (filter-subdirs (cdr root-pairs) ret)))))
2389 (or (and (null? root-pairs) leaf-pairs)
2390 (let ((matching-subdir-pairs (filter-subdirs root-pairs '())))
2391 (match-version-recursive
2392 matching-subdir-pairs
2393 (append leaf-pairs (filter pair? (map match-version-and-file
2394 matching-subdir-pairs)))))))
2395 (define (make-root-pair root)
2396 (cons '() (string-append root "/" dir-hint)))
2398 (let* ((root-pairs (map make-root-pair roots))
2399 (matches (if (null? version-ref)
2400 (filter pair? (map match-version-and-file root-pairs))
2402 (matches (append matches (match-version-recursive root-pairs '()))))
2403 (and (null? matches) (error "No matching modules found."))
2404 (cdar (sort matches subdir-pair-less))))
2406 (define (make-fresh-user-module)
2407 (let ((m (make-module)))
2408 (beautify-user-module! m)
2411 ;; NOTE: This binding is used in libguile/modules.c.
2413 (define resolve-module
2414 (let ((root (make-module)))
2415 (set-module-name! root '())
2416 ;; Define the-root-module as '(guile).
2417 (module-define-submodule! root 'guile the-root-module)
2419 (lambda* (name #:optional (autoload #t) (version #f))
2420 (let ((already (nested-ref-module root name)))
2423 (or (not autoload) (module-public-interface already)))
2424 ;; A hit, a palpable hit.
2426 (not (version-matches? version (module-version already))))
2427 (error "incompatible module version already loaded" name))
2430 ;; Try to autoload the module, and recurse.
2431 (try-load-module name version)
2432 (resolve-module name #f))
2434 ;; No module found (or if one was, it had no public interface), and
2435 ;; we're not autoloading. Here's the weird semantics: we ensure
2436 ;; there's an empty module.
2437 (or already (make-modules-in root name))))))))
2440 (define (try-load-module name version)
2441 (try-module-autoload name version))
2443 (define (purify-module! module)
2444 "Removes bindings in MODULE which are inherited from the (guile) module."
2445 (let ((use-list (module-uses module)))
2446 (if (and (pair? use-list)
2447 (eq? (car (last-pair use-list)) the-scm-module))
2448 (set-module-uses! module (reverse (cdr (reverse use-list)))))))
2450 ;; Return a module that is an interface to the module designated by
2453 ;; `resolve-interface' takes four keyword arguments:
2455 ;; #:select SELECTION
2457 ;; SELECTION is a list of binding-specs to be imported; A binding-spec
2458 ;; is either a symbol or a pair of symbols (ORIG . SEEN), where ORIG
2459 ;; is the name in the used module and SEEN is the name in the using
2460 ;; module. Note that SEEN is also passed through RENAMER, below. The
2461 ;; default is to select all bindings. If you specify no selection but
2462 ;; a renamer, only the bindings that already exist in the used module
2463 ;; are made available in the interface. Bindings that are added later
2464 ;; are not picked up.
2468 ;; BINDINGS is a list of bindings which should not be imported.
2472 ;; PREFIX is a symbol that will be appended to each exported name.
2473 ;; The default is to not perform any renaming.
2475 ;; #:renamer RENAMER
2477 ;; RENAMER is a procedure that takes a symbol and returns its new
2478 ;; name. The default is not perform any renaming.
2480 ;; Signal "no code for module" error if module name is not resolvable
2481 ;; or its public interface is not available. Signal "no binding"
2482 ;; error if selected binding does not exist in the used module.
2484 (define* (resolve-interface name #:key
2489 (symbol-prefix-proc prefix)
2492 (let* ((module (resolve-module name #t version))
2493 (public-i (and module (module-public-interface module))))
2494 (and (or (not module) (not public-i))
2495 (error "no code for module" name))
2496 (if (and (not select) (null? hide) (eq? renamer identity))
2498 (let ((selection (or select (module-map (lambda (sym var) sym)
2500 (custom-i (make-module 31)))
2501 (set-module-kind! custom-i 'custom-interface)
2502 (set-module-name! custom-i name)
2503 ;; XXX - should use a lazy binder so that changes to the
2504 ;; used module are picked up automatically.
2505 (for-each (lambda (bspec)
2506 (let* ((direct? (symbol? bspec))
2507 (orig (if direct? bspec (car bspec)))
2508 (seen (if direct? bspec (cdr bspec)))
2509 (var (or (module-local-variable public-i orig)
2510 (module-local-variable module orig)
2512 ;; fixme: format manually for now
2514 #f "no binding `~A' in module ~A"
2516 (if (memq orig hide)
2517 (set! hide (delq! orig hide))
2518 (module-add! custom-i
2522 ;; Check that we are not hiding bindings which don't exist
2523 (for-each (lambda (binding)
2524 (if (not (module-local-variable public-i binding))
2527 #f "no binding `~A' to hide in module ~A"
2532 (define (symbol-prefix-proc prefix)
2534 (symbol-append prefix symbol)))
2536 ;; This function is called from "modules.c". If you change it, be
2537 ;; sure to update "modules.c" as well.
2539 (define (process-define-module args)
2540 (let* ((module-id (car args))
2541 (module (resolve-module module-id #f))
2543 (unrecognized (lambda (arg)
2544 (error "unrecognized define-module argument" arg))))
2545 (beautify-user-module! module)
2546 (let loop ((kws kws)
2547 (reversed-interfaces '())
2554 (call-with-deferred-observers
2556 (module-use-interfaces! module (reverse reversed-interfaces))
2557 (module-export! module exports)
2558 (module-replace! module replacements)
2559 (module-re-export! module re-exports)
2560 (if (not (null? autoloads))
2561 (apply module-autoload! module autoloads))))
2563 ((#:use-module #:use-syntax)
2564 (or (pair? (cdr kws))
2567 ((equal? (caadr kws) '(ice-9 syncase))
2568 (issue-deprecation-warning
2569 "(ice-9 syncase) is deprecated. Support for syntax-case is now in Guile core.")
2577 (let* ((interface-args (cadr kws))
2578 (interface (apply resolve-interface interface-args)))
2579 (and (eq? (car kws) #:use-syntax)
2580 (or (symbol? (caar interface-args))
2581 (error "invalid module name for use-syntax"
2582 (car interface-args)))
2583 (set-module-transformer!
2585 (module-ref interface
2586 (car (last-pair (car interface-args)))
2589 (cons interface reversed-interfaces)
2595 (or (and (pair? (cdr kws)) (pair? (cddr kws)))
2602 (let ((name (cadr kws))
2603 (bindings (caddr kws)))
2604 (cons* name bindings autoloads))))
2606 (set-system-module! module #t)
2607 (loop (cdr kws) reversed-interfaces exports re-exports
2608 replacements autoloads))
2610 (purify-module! module)
2611 (loop (cdr kws) reversed-interfaces exports re-exports
2612 replacements autoloads))
2614 (or (pair? (cdr kws))
2616 (let ((version (cadr kws)))
2617 (set-module-version! module version)
2618 (set-module-version! (module-public-interface module) version))
2619 (loop (cddr kws) reversed-interfaces exports re-exports
2620 replacements autoloads))
2622 (if (not (pair? (cdr kws)))
2624 (set-module-duplicates-handlers!
2626 (lookup-duplicates-handlers (cadr kws)))
2627 (loop (cddr kws) reversed-interfaces exports re-exports
2628 replacements autoloads))
2629 ((#:export #:export-syntax)
2630 (or (pair? (cdr kws))
2634 (append (cadr kws) exports)
2638 ((#:re-export #:re-export-syntax)
2639 (or (pair? (cdr kws))
2644 (append (cadr kws) re-exports)
2647 ((#:replace #:replace-syntax)
2648 (or (pair? (cdr kws))
2654 (append (cadr kws) replacements)
2657 (or (pair? (cdr kws))
2659 (set-module-filename! module (cadr kws))
2667 (unrecognized kws)))))
2668 (run-hook module-defined-hook module)
2671 ;; `module-defined-hook' is a hook that is run whenever a new module
2672 ;; is defined. Its members are called with one argument, the new
2674 (define module-defined-hook (make-hook 1))
2681 (define (make-autoload-interface module name bindings)
2682 (let ((b (lambda (a sym definep)
2683 (and (memq sym bindings)
2684 (let ((i (module-public-interface (resolve-module name))))
2686 (error "missing interface for module" name))
2687 (let ((autoload (memq a (module-uses module))))
2688 ;; Replace autoload-interface with actual interface if
2689 ;; that has not happened yet.
2690 (if (pair? autoload)
2691 (set-car! autoload i)))
2692 (module-local-variable i sym))))))
2693 (module-constructor (make-hash-table 0) '() b #f #f name 'autoload #f
2694 (make-hash-table 0) '() (make-weak-value-hash-table 31) #f
2695 (make-hash-table 0) #f #f #f)))
2697 (define (module-autoload! module . args)
2698 "Have @var{module} automatically load the module named @var{name} when one
2699 of the symbols listed in @var{bindings} is looked up. @var{args} should be a
2700 list of module-name/binding-list pairs, e.g., as in @code{(module-autoload!
2701 module '(ice-9 q) '(make-q q-length))}."
2702 (let loop ((args args))
2706 (error "invalid name+binding autoload list" args))
2708 (let ((name (car args))
2709 (bindings (cadr args)))
2710 (module-use! module (make-autoload-interface module
2712 (loop (cddr args)))))))
2717 ;;; {Autoloading modules}
2720 (define autoloads-in-progress '())
2722 ;; This function is called from "modules.c". If you change it, be
2723 ;; sure to update "modules.c" as well.
2725 (define* (try-module-autoload module-name #:optional version)
2726 (let* ((reverse-name (reverse module-name))
2727 (name (symbol->string (car reverse-name)))
2728 (dir-hint-module-name (reverse (cdr reverse-name)))
2729 (dir-hint (apply string-append
2731 (string-append (symbol->string elt) "/"))
2732 dir-hint-module-name))))
2733 (resolve-module dir-hint-module-name #f)
2734 (and (not (autoload-done-or-in-progress? dir-hint name))
2737 (lambda () (autoload-in-progress! dir-hint name))
2739 (with-fluids ((current-reader #f))
2740 (save-module-excursion
2743 (load (find-versioned-module
2744 dir-hint name version %load-path))
2745 (primitive-load-path (in-vicinity dir-hint name) #f))
2747 (lambda () (set-autoloaded! dir-hint name didit)))
2752 ;;; {Dynamic linking of modules}
2755 (define autoloads-done '((guile . guile)))
2757 (define (autoload-done-or-in-progress? p m)
2758 (let ((n (cons p m)))
2759 (->bool (or (member n autoloads-done)
2760 (member n autoloads-in-progress)))))
2762 (define (autoload-done! p m)
2763 (let ((n (cons p m)))
2764 (set! autoloads-in-progress
2765 (delete! n autoloads-in-progress))
2766 (or (member n autoloads-done)
2767 (set! autoloads-done (cons n autoloads-done)))))
2769 (define (autoload-in-progress! p m)
2770 (let ((n (cons p m)))
2771 (set! autoloads-done
2772 (delete! n autoloads-done))
2773 (set! autoloads-in-progress (cons n autoloads-in-progress))))
2775 (define (set-autoloaded! p m done?)
2777 (autoload-done! p m)
2778 (let ((n (cons p m)))
2779 (set! autoloads-done (delete! n autoloads-done))
2780 (set! autoloads-in-progress (delete! n autoloads-in-progress)))))
2784 ;;; {Run-time options}
2787 (defmacro define-option-interface (option-group)
2788 (let* ((option-name 'car)
2789 (option-value 'cadr)
2790 (option-documentation 'caddr)
2792 ;; Below follow the macros defining the run-time option interfaces.
2794 (make-options (lambda (interface)
2796 (cond ((null? args) (,interface))
2798 (,interface (car args)) (,interface))
2801 (display (,option-name option))
2802 (if (< (string-length
2803 (symbol->string (,option-name option)))
2807 (display (,option-value option))
2809 (display (,option-documentation option))
2811 (,interface #t)))))))
2813 (make-enable (lambda (interface)
2815 (,interface (append flags (,interface)))
2818 (make-disable (lambda (interface)
2820 (let ((options (,interface)))
2821 (for-each (lambda (flag)
2822 (set! options (delq! flag options)))
2824 (,interface options)
2826 (let* ((interface (car option-group))
2827 (options/enable/disable (cadr option-group)))
2829 (define ,(car options/enable/disable)
2830 ,(make-options interface))
2831 (define ,(cadr options/enable/disable)
2832 ,(make-enable interface))
2833 (define ,(caddr options/enable/disable)
2834 ,(make-disable interface))
2835 (defmacro ,(caaddr option-group) (opt val)
2836 `(,',(car options/enable/disable)
2837 (append (,',(car options/enable/disable))
2838 (list ',opt ,val))))))))
2840 (define-option-interface
2841 (eval-options-interface
2842 (eval-options eval-enable eval-disable)
2845 (define-option-interface
2846 (debug-options-interface
2847 (debug-options debug-enable debug-disable)
2850 (define-option-interface
2851 (evaluator-traps-interface
2852 (traps trap-enable trap-disable)
2855 (define-option-interface
2856 (read-options-interface
2857 (read-options read-enable read-disable)
2860 (define-option-interface
2861 (print-options-interface
2862 (print-options print-enable print-disable)
2870 (define (repl read evaler print)
2871 (let loop ((source (read (current-input-port))))
2872 (print (evaler source))
2873 (loop (read (current-input-port)))))
2875 ;; A provisional repl that acts like the SCM repl:
2877 (define scm-repl-silent #f)
2878 (define (assert-repl-silence v) (set! scm-repl-silent v))
2880 (define *unspecified* (if #f #f))
2881 (define (unspecified? v) (eq? v *unspecified*))
2883 (define scm-repl-print-unspecified #f)
2884 (define (assert-repl-print-unspecified v) (set! scm-repl-print-unspecified v))
2886 (define scm-repl-verbose #f)
2887 (define (assert-repl-verbosity v) (set! scm-repl-verbose v))
2889 (define scm-repl-prompt "guile> ")
2891 (define (set-repl-prompt! v) (set! scm-repl-prompt v))
2893 (define (default-pre-unwind-handler key . args)
2894 ;; Narrow by two more frames: this one, and the throw handler.
2896 (apply throw key args))
2899 (define (pre-unwind-handler-dispatch key . args)
2900 (apply default-pre-unwind-handler key args)))
2902 (define abort-hook (make-hook))
2904 ;; these definitions are used if running a script.
2905 ;; otherwise redefined in error-catching-loop.
2906 (define (set-batch-mode?! arg) #t)
2907 (define (batch-mode?) #t)
2909 ;;(define the-last-stack (make-fluid)) Defined by scm_init_backtrace ()
2910 (define before-signal-stack (make-fluid))
2911 ;; FIXME: stack-saved? is broken in the presence of threads.
2912 (define stack-saved? #f)
2914 (define (save-stack . narrowing)
2915 (if (not stack-saved?)
2917 (let ((stacks (fluid-ref %stacks)))
2918 (fluid-set! the-last-stack
2919 ;; (make-stack obj inner outer inner outer ...)
2921 ;; In this case, cut away the make-stack frame, the
2922 ;; save-stack frame, and then narrow as specified by the
2923 ;; user, delimited by the nearest start-stack invocation,
2925 (apply make-stack #t
2927 (if (pair? stacks) (cdar stacks) 0)
2929 (set! stack-saved? #t))))
2931 (define before-error-hook (make-hook))
2932 (define after-error-hook (make-hook))
2933 (define before-backtrace-hook (make-hook))
2934 (define after-backtrace-hook (make-hook))
2936 (define has-shown-debugger-hint? #f)
2938 (define (handle-system-error key . args)
2939 (let ((cep (current-error-port)))
2940 (cond ((not (stack? (fluid-ref the-last-stack))))
2941 ((memq 'backtrace (debug-options-interface))
2942 (let ((highlights (if (or (eq? key 'wrong-type-arg)
2943 (eq? key 'out-of-range))
2946 (run-hook before-backtrace-hook)
2948 (display "Backtrace:\n")
2949 (display-backtrace (fluid-ref the-last-stack) cep
2952 (run-hook after-backtrace-hook))))
2953 (run-hook before-error-hook)
2954 (apply display-error (fluid-ref the-last-stack) cep args)
2955 (run-hook after-error-hook)
2957 (throw 'abort key)))
2959 (define (quit . args)
2960 (apply throw 'quit args))
2964 (define (gc-run-time)
2965 (cdr (assq 'gc-time-taken (gc-stats))))
2967 (define before-read-hook (make-hook))
2968 (define after-read-hook (make-hook))
2969 (define before-eval-hook (make-hook 1))
2970 (define after-eval-hook (make-hook 1))
2971 (define before-print-hook (make-hook 1))
2972 (define after-print-hook (make-hook 1))
2974 ;;; The default repl-reader function. We may override this if we've
2975 ;;; the readline library.
2977 (lambda* (prompt #:optional (reader (fluid-ref current-reader)))
2978 (if (not (char-ready?))
2979 (display (if (string? prompt) prompt (prompt))))
2981 (run-hook before-read-hook)
2982 ((or reader read) (current-input-port))))
2987 ;;; {IOTA functions: generating lists of numbers}
2991 (let loop ((count (1- n)) (result '()))
2992 (if (< count 0) result
2993 (loop (1- count) (cons count result)))))
2999 ;;; Similar to `begin' but returns a list of the results of all constituent
3000 ;;; forms instead of the result of the last form.
3001 ;;; (The definition relies on the current left-to-right
3002 ;;; order of evaluation of operands in applications.)
3005 (defmacro collect forms
3012 ;;; with `continue' and `break'.
3015 ;; The inner `do' loop avoids re-establishing a catch every iteration,
3016 ;; that's only necessary if continue is actually used. A new key is
3017 ;; generated every time, so break and continue apply to their originating
3018 ;; `while' even when recursing.
3020 ;; FIXME: This macro is unintentionally unhygienic with respect to let,
3021 ;; make-symbol, do, throw, catch, lambda, and not.
3023 (define-macro (while cond . body)
3024 (let ((keyvar (make-symbol "while-keyvar")))
3025 `(let ((,keyvar (make-symbol "while-key")))
3029 (let ((break (lambda () (throw ,keyvar #t)))
3030 (continue (lambda () (throw ,keyvar #f))))
3041 ;;; {Module System Macros}
3044 ;; Return a list of expressions that evaluate to the appropriate
3045 ;; arguments for resolve-interface according to SPEC.
3049 (if (memq 'prefix (read-options))
3050 (error "boot-9 must be compiled with #:kw, not :kw")))
3052 (define (keyword-like-symbol->keyword sym)
3053 (symbol->keyword (string->symbol (substring (symbol->string sym) 1))))
3055 ;; FIXME: we really need to clean up the guts of the module system.
3056 ;; We can compile to something better than process-define-module.
3057 (define-syntax define-module
3059 (define (keyword-like? stx)
3060 (let ((dat (syntax->datum stx)))
3062 (eqv? (string-ref (symbol->string dat) 0) #\:))))
3063 (define (->keyword sym)
3064 (symbol->keyword (string->symbol (substring (symbol->string sym) 1))))
3066 (define (quotify-iface args)
3067 (let loop ((in args) (out '()))
3070 ;; The user wanted #:foo, but wrote :foo. Fix it.
3071 ((sym . in) (keyword-like? #'sym)
3072 (loop #`(#,(->keyword (syntax->datum #'sym)) . in) out))
3073 ((kw . in) (not (keyword? (syntax->datum #'kw)))
3074 (syntax-violation 'define-module "expected keyword arg" x #'kw))
3075 ((#:renamer renamer . in)
3076 (loop #'in (cons* #'renamer #:renamer out)))
3078 (loop #'in (cons* #''val #'kw out))))))
3080 (define (quotify args)
3081 ;; Just quote everything except #:use-module and #:use-syntax. We
3082 ;; need to know about all arguments regardless since we want to turn
3083 ;; symbols that look like keywords into real keywords, and the
3084 ;; keyword args in a define-module form are not regular
3085 ;; (i.e. no-backtrace doesn't take a value).
3086 (let loop ((in args) (out '()))
3089 ;; The user wanted #:foo, but wrote :foo. Fix it.
3090 ((sym . in) (keyword-like? #'sym)
3091 (loop #`(#,(->keyword (syntax->datum #'sym)) . in) out))
3092 ((kw . in) (not (keyword? (syntax->datum #'kw)))
3093 (syntax-violation 'define-module "expected keyword arg" x #'kw))
3094 ((#:no-backtrace . in)
3095 (loop #'in (cons #:no-backtrace out)))
3097 (loop #'in (cons #:pure out)))
3099 (syntax-violation 'define-module "keyword arg without value" x #'kw))
3100 ((use-module (name name* ...) . in)
3101 (and (memq (syntax->datum #'use-module) '(#:use-module #:use-syntax))
3102 (and-map symbol? (syntax->datum #'(name name* ...))))
3104 (cons* #''((name name* ...))
3107 ((use-module ((name name* ...) arg ...) . in)
3108 (and (memq (syntax->datum #'use-module) '(#:use-module #:use-syntax))
3109 (and-map symbol? (syntax->datum #'(name name* ...))))
3111 (cons* #`(list '(name name* ...) #,@(quotify-iface #'(arg ...)))
3114 ((#:autoload name bindings . in)
3115 (loop #'in (cons* #''bindings #''name #:autoload out)))
3117 (loop #'in (cons* #''val #'kw out))))))
3120 ((_ (name name* ...) arg ...)
3121 (with-syntax (((quoted-arg ...) (quotify #'(arg ...))))
3122 #'(eval-when (eval load compile expand)
3123 (let ((m (process-define-module
3124 (list '(name name* ...)
3125 #:filename (assq-ref
3126 (or (current-source-location) '())
3129 (set-current-module m)
3132 ;; The guts of the use-modules macro. Add the interfaces of the named
3133 ;; modules to the use-list of the current module, in order.
3135 ;; This function is called by "modules.c". If you change it, be sure
3136 ;; to change scm_c_use_module as well.
3138 (define (process-use-modules module-interface-args)
3139 (let ((interfaces (map (lambda (mif-args)
3140 (or (apply resolve-interface mif-args)
3141 (error "no such module" mif-args)))
3142 module-interface-args)))
3143 (call-with-deferred-observers
3145 (module-use-interfaces! (current-module) interfaces)))))
3147 (define-syntax use-modules
3149 (define (keyword-like? stx)
3150 (let ((dat (syntax->datum stx)))
3152 (eqv? (string-ref (symbol->string dat) 0) #\:))))
3153 (define (->keyword sym)
3154 (symbol->keyword (string->symbol (substring (symbol->string sym) 1))))
3156 (define (quotify-iface args)
3157 (let loop ((in args) (out '()))
3160 ;; The user wanted #:foo, but wrote :foo. Fix it.
3161 ((sym . in) (keyword-like? #'sym)
3162 (loop #`(#,(->keyword (syntax->datum #'sym)) . in) out))
3163 ((kw . in) (not (keyword? (syntax->datum #'kw)))
3164 (syntax-violation 'define-module "expected keyword arg" x #'kw))
3165 ((#:renamer renamer . in)
3166 (loop #'in (cons* #'renamer #:renamer out)))
3168 (loop #'in (cons* #''val #'kw out))))))
3170 (define (quotify specs)
3171 (let lp ((in specs) (out '()))
3174 (((name name* ...) . in)
3175 (and-map symbol? (syntax->datum #'(name name* ...)))
3176 (lp #'in (cons #''((name name* ...)) out)))
3177 ((((name name* ...) arg ...) . in)
3178 (and-map symbol? (syntax->datum #'(name name* ...)))
3179 (with-syntax (((quoted-arg ...) (quotify-iface #'(arg ...))))
3180 (lp #'in (cons #`(list '(name name* ...) quoted-arg ...)
3185 (with-syntax (((quoted-args ...) (quotify #'(spec ...))))
3186 #'(eval-when (eval load compile expand)
3187 (process-use-modules (list quoted-args ...))
3190 (define-syntax use-syntax
3194 (eval-when (eval load compile expand)
3195 (issue-deprecation-warning
3196 "`use-syntax' is deprecated. Please contact guile-devel for more info."))
3197 (use-modules spec ...)))))
3199 (include-from-path "ice-9/r6rs-libraries")
3201 (define-syntax define-private
3206 (define-syntax define-public
3208 ((_ (name . args) . body)
3209 (define-public name (lambda args . body)))
3215 (define-syntax defmacro-public
3217 ((_ name args . body)
3219 (defmacro name args . body)
3220 (export-syntax name)))))
3222 ;; And now for the most important macro.
3225 ((_ formals body ...)
3226 (lambda formals body ...))))
3229 ;; Export a local variable
3231 ;; This function is called from "modules.c". If you change it, be
3232 ;; sure to update "modules.c" as well.
3234 (define (module-export! m names)
3235 (let ((public-i (module-public-interface m)))
3236 (for-each (lambda (name)
3237 (let* ((internal-name (if (pair? name) (car name) name))
3238 (external-name (if (pair? name) (cdr name) name))
3239 (var (module-ensure-local-variable! m internal-name)))
3240 (module-add! public-i external-name var)))
3243 (define (module-replace! m names)
3244 (let ((public-i (module-public-interface m)))
3245 (for-each (lambda (name)
3246 (let* ((internal-name (if (pair? name) (car name) name))
3247 (external-name (if (pair? name) (cdr name) name))
3248 (var (module-ensure-local-variable! m internal-name)))
3249 (set-object-property! var 'replace #t)
3250 (module-add! public-i external-name var)))
3253 ;; Export all local variables from a module
3255 (define (module-export-all! mod)
3256 (define (fresh-interface!)
3257 (let ((iface (make-module)))
3258 (set-module-name! iface (module-name mod))
3259 ;; for guile 2: (set-module-version! iface (module-version mod))
3260 (set-module-kind! iface 'interface)
3261 (set-module-public-interface! mod iface)
3263 (let ((iface (or (module-public-interface mod)
3264 (fresh-interface!))))
3265 (set-module-obarray! iface (module-obarray mod))))
3267 ;; Re-export a imported variable
3269 (define (module-re-export! m names)
3270 (let ((public-i (module-public-interface m)))
3271 (for-each (lambda (name)
3272 (let* ((internal-name (if (pair? name) (car name) name))
3273 (external-name (if (pair? name) (cdr name) name))
3274 (var (module-variable m internal-name)))
3276 (error "Undefined variable:" internal-name))
3277 ((eq? var (module-local-variable m internal-name))
3278 (error "re-exporting local variable:" internal-name))
3280 (module-add! public-i external-name var)))))
3283 (define-syntax export
3286 (eval-when (eval load compile expand)
3287 (call-with-deferred-observers
3289 (module-export! (current-module) '(name ...))))))))
3291 (define-syntax re-export
3294 (eval-when (eval load compile expand)
3295 (call-with-deferred-observers
3297 (module-re-export! (current-module) '(name ...))))))))
3299 (define-syntax export-syntax
3302 (export name ...))))
3304 (define-syntax re-export-syntax
3307 (re-export name ...))))
3309 (define load load-module)
3316 (define make-mutable-parameter
3317 (let ((make (lambda (fluid converter)
3321 (fluid-set! fluid (converter (car args))))))))
3322 (lambda* (init #:optional (converter identity))
3323 (let ((fluid (make-fluid)))
3324 (fluid-set! fluid (converter init))
3325 (make fluid converter)))))
3329 ;;; {Handling of duplicate imported bindings}
3332 ;; Duplicate handlers take the following arguments:
3334 ;; module importing module
3335 ;; name conflicting name
3336 ;; int1 old interface where name occurs
3337 ;; val1 value of binding in old interface
3338 ;; int2 new interface where name occurs
3339 ;; val2 value of binding in new interface
3340 ;; var previous resolution or #f
3341 ;; val value of previous resolution
3343 ;; A duplicate handler can take three alternative actions:
3345 ;; 1. return #f => leave responsibility to next handler
3346 ;; 2. exit with an error
3347 ;; 3. return a variable resolving the conflict
3350 (define duplicate-handlers
3351 (let ((m (make-module 7)))
3353 (define (check module name int1 val1 int2 val2 var val)
3354 (scm-error 'misc-error
3356 "~A: `~A' imported from both ~A and ~A"
3357 (list (module-name module)
3363 (define (warn module name int1 val1 int2 val2 var val)
3364 (format (current-error-port)
3365 "WARNING: ~A: `~A' imported from both ~A and ~A\n"
3366 (module-name module)
3372 (define (replace module name int1 val1 int2 val2 var val)
3373 (let ((old (or (and var (object-property var 'replace) var)
3374 (module-variable int1 name)))
3375 (new (module-variable int2 name)))
3376 (if (object-property old 'replace)
3377 (and (or (eq? old new)
3378 (not (object-property new 'replace)))
3380 (and (object-property new 'replace)
3383 (define (warn-override-core module name int1 val1 int2 val2 var val)
3384 (and (eq? int1 the-scm-module)
3386 (format (current-error-port)
3387 "WARNING: ~A: imported module ~A overrides core binding `~A'\n"
3388 (module-name module)
3391 (module-local-variable int2 name))))
3393 (define (first module name int1 val1 int2 val2 var val)
3394 (or var (module-local-variable int1 name)))
3396 (define (last module name int1 val1 int2 val2 var val)
3397 (module-local-variable int2 name))
3399 (define (noop module name int1 val1 int2 val2 var val)
3402 (set-module-name! m 'duplicate-handlers)
3403 (set-module-kind! m 'interface)
3404 (module-define! m 'check check)
3405 (module-define! m 'warn warn)
3406 (module-define! m 'replace replace)
3407 (module-define! m 'warn-override-core warn-override-core)
3408 (module-define! m 'first first)
3409 (module-define! m 'last last)
3410 (module-define! m 'merge-generics noop)
3411 (module-define! m 'merge-accessors noop)
3414 (define (lookup-duplicates-handlers handler-names)
3416 (map (lambda (handler-name)
3417 (or (module-symbol-local-binding
3418 duplicate-handlers handler-name #f)
3419 (error "invalid duplicate handler name:"
3421 (if (list? handler-names)
3423 (list handler-names)))))
3425 (define default-duplicate-binding-procedures
3426 (make-mutable-parameter #f))
3428 (define default-duplicate-binding-handler
3429 (make-mutable-parameter '(replace warn-override-core warn last)
3430 (lambda (handler-names)
3431 (default-duplicate-binding-procedures
3432 (lookup-duplicates-handlers handler-names))
3437 ;;; {`cond-expand' for SRFI-0 support.}
3439 ;;; This syntactic form expands into different commands or
3440 ;;; definitions, depending on the features provided by the Scheme
3446 ;;; --> (cond-expand <cond-expand-clause>+)
3447 ;;; | (cond-expand <cond-expand-clause>* (else <command-or-definition>))
3448 ;;; <cond-expand-clause>
3449 ;;; --> (<feature-requirement> <command-or-definition>*)
3450 ;;; <feature-requirement>
3451 ;;; --> <feature-identifier>
3452 ;;; | (and <feature-requirement>*)
3453 ;;; | (or <feature-requirement>*)
3454 ;;; | (not <feature-requirement>)
3455 ;;; <feature-identifier>
3456 ;;; --> <a symbol which is the name or alias of a SRFI>
3458 ;;; Additionally, this implementation provides the
3459 ;;; <feature-identifier>s `guile' and `r5rs', so that programs can
3460 ;;; determine the implementation type and the supported standard.
3462 ;;; Currently, the following feature identifiers are supported:
3464 ;;; guile r5rs srfi-0 srfi-4 srfi-6 srfi-13 srfi-14 srfi-55 srfi-61
3466 ;;; Remember to update the features list when adding more SRFIs.
3469 (define %cond-expand-features
3470 ;; Adjust the above comment when changing this.
3474 srfi-0 ;; cond-expand itself
3475 srfi-4 ;; homogenous numeric vectors
3476 srfi-6 ;; open-input-string etc, in the guile core
3477 srfi-13 ;; string library
3478 srfi-14 ;; character sets
3479 srfi-55 ;; require-extension
3480 srfi-61 ;; general cond clause
3483 ;; This table maps module public interfaces to the list of features.
3485 (define %cond-expand-table (make-hash-table 31))
3487 ;; Add one or more features to the `cond-expand' feature list of the
3490 (define (cond-expand-provide module features)
3491 (let ((mod (module-public-interface module)))
3493 (hashq-set! %cond-expand-table mod
3494 (append (hashq-ref %cond-expand-table mod '())
3497 (define-macro (cond-expand . clauses)
3498 (let ((syntax-error (lambda (cl)
3499 (error "invalid clause in `cond-expand'" cl))))
3505 (or (memq clause %cond-expand-features)
3506 (let lp ((uses (module-uses (current-module))))
3509 (hashq-ref %cond-expand-table
3515 ((eq? 'and (car clause))
3516 (let lp ((l (cdr clause)))
3520 (and (test-clause (car l)) (lp (cdr l))))
3522 (syntax-error clause)))))
3523 ((eq? 'or (car clause))
3524 (let lp ((l (cdr clause)))
3528 (or (test-clause (car l)) (lp (cdr l))))
3530 (syntax-error clause)))))
3531 ((eq? 'not (car clause))
3532 (cond ((not (pair? (cdr clause)))
3533 (syntax-error clause))
3534 ((pair? (cddr clause))
3535 ((syntax-error clause))))
3536 (not (test-clause (cadr clause))))
3538 (syntax-error clause))))
3540 (syntax-error clause))))))
3541 (let lp ((c clauses))
3544 (error "Unfulfilled `cond-expand'"))
3547 ((not (pair? (car c)))
3548 (syntax-error (car c)))
3549 ((test-clause (caar c))
3550 `(begin ,@(cdar c)))
3551 ((eq? (caar c) 'else)
3554 `(begin ,@(cdar c)))
3558 ;; This procedure gets called from the startup code with a list of
3559 ;; numbers, which are the numbers of the SRFIs to be loaded on startup.
3561 (define (use-srfis srfis)
3562 (process-use-modules
3564 (list (list 'srfi (string->symbol
3565 (string-append "srfi-" (number->string num))))))
3570 ;;; srfi-55: require-extension
3573 (define-macro (require-extension extension-spec)
3574 ;; This macro only handles the srfi extension, which, at present, is
3575 ;; the only one defined by the standard.
3576 (if (not (pair? extension-spec))
3577 (scm-error 'wrong-type-arg "require-extension"
3578 "Not an extension: ~S" (list extension-spec) #f))
3579 (let ((extension (car extension-spec))
3580 (extension-args (cdr extension-spec)))
3583 (let ((use-list '()))
3586 (if (not (integer? i))
3587 (scm-error 'wrong-type-arg "require-extension"
3588 "Invalid srfi name: ~S" (list i) #f))
3589 (let ((srfi-sym (string->symbol
3590 (string-append "srfi-" (number->string i)))))
3591 (if (not (memq srfi-sym %cond-expand-features))
3592 (set! use-list (cons `(use-modules (srfi ,srfi-sym))
3595 (if (pair? use-list)
3596 ;; i.e. (begin (use-modules x) (use-modules y) (use-modules z))
3597 `(begin ,@(reverse! use-list)))))
3600 'wrong-type-arg "require-extension"
3601 "Not a recognized extension type: ~S" (list extension) #f)))))
3605 ;;; {Load emacs interface support if emacs option is given.}
3608 (define (named-module-use! user usee)
3609 (module-use! (resolve-module user) (resolve-interface usee)))
3611 (define (load-emacs-interface)
3612 (and (provided? 'debug-extensions)
3613 (debug-enable 'backtrace))
3614 (named-module-use! '(guile-user) '(ice-9 emacs)))
3618 (define using-readline?
3619 (let ((using-readline? (make-fluid)))
3620 (make-procedure-with-setter
3621 (lambda () (fluid-ref using-readline?))
3622 (lambda (v) (fluid-set! using-readline? v)))))
3625 (let ((guile-user-module (resolve-module '(guile-user))))
3627 ;; Load emacs interface support if emacs option is given.
3628 (if (and (module-defined? guile-user-module 'use-emacs-interface)
3629 (module-ref guile-user-module 'use-emacs-interface))
3630 (load-emacs-interface))
3632 ;; Use some convenient modules (in reverse order)
3634 (set-current-module guile-user-module)
3635 (process-use-modules
3640 (if (provided? 'regex)
3643 (if (provided? 'threads)
3644 '(((ice-9 threads)))
3646 ;; load debugger on demand
3647 (module-autoload! guile-user-module '(system vm debug) '(debug))
3649 ;; Note: SIGFPE, SIGSEGV and SIGBUS are actually "query-only" (see
3650 ;; scmsigs.c scm_sigaction_for_thread), so the handlers setup here have
3652 (let ((old-handlers #f)
3653 (start-repl (@ (system repl repl) start-repl))
3654 (signals (if (provided? 'posix)
3655 `((,SIGINT . "User interrupt")
3656 (,SIGFPE . "Arithmetic error")
3658 . "Bad memory access (Segmentation violation)"))
3660 ;; no SIGBUS on mingw
3661 (if (defined? 'SIGBUS)
3662 (set! signals (acons SIGBUS "Bad memory access (bus error)"
3669 (let ((make-handler (lambda (msg)
3671 ;; Make a backup copy of the stack
3672 (fluid-set! before-signal-stack
3673 (fluid-ref the-last-stack))
3681 (map (lambda (sig-msg)
3682 (sigaction (car sig-msg)
3683 (make-handler (cdr sig-msg))))
3686 ;; the protected thunk.
3688 (let ((status (start-repl 'scheme)))
3689 (run-hook exit-hook)
3694 (map (lambda (sig-msg old-handler)
3695 (if (not (car old-handler))
3696 ;; restore original C handler.
3697 (sigaction (car sig-msg) #f)
3698 ;; restore Scheme handler, SIG_IGN or SIG_DFL.
3699 (sigaction (car sig-msg)
3701 (cdr old-handler))))
3702 signals old-handlers))))))
3704 ;;; This hook is run at the very end of an interactive session.
3706 (define exit-hook (make-hook))
3710 ;;; {Deprecated stuff}
3714 (module-use! the-scm-module (resolve-interface '(ice-9 deprecated))))
3718 ;;; Place the user in the guile-user module.
3722 (module-use! the-scm-module (resolve-interface '(srfi srfi-4)))
3724 (define-module (guile-user)
3725 #:autoload (system base compile) (compile))
3727 ;; Remain in the `(guile)' module at compilation-time so that the
3728 ;; `-Wunused-toplevel' warning works as expected.
3729 (eval-when (compile) (set-current-module the-root-module))
3731 ;;; boot-9.scm ends here