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 identifier? #f)
350 (define generate-temporaries #f)
351 (define bound-identifier=? #f)
352 (define free-identifier=? #f)
354 ;; $sc-dispatch is an implementation detail of psyntax. It is used by
355 ;; expanded macros, to dispatch an input against a set of patterns.
356 (define $sc-dispatch #f)
359 (primitive-load-path "ice-9/psyntax-pp")
360 ;; The binding for `macroexpand' has now been overridden, making psyntax the
367 ((_ x y ...) (if x (and y ...) #f))))
373 ((_ x y ...) (let ((t x)) (if t t (or y ...))))))
375 ;; The "maybe-more" bits are something of a hack, so that we can support
376 ;; SRFI-61. Rewrites into a standalone syntax-case macro would be
379 (syntax-rules (=> else)
380 ((_ "maybe-more" test consequent)
381 (if test consequent))
383 ((_ "maybe-more" test consequent clause ...)
384 (if test consequent (cond clause ...)))
386 ((_ (else else1 else2 ...))
387 (begin else1 else2 ...))
389 ((_ (test => receiver) more-clause ...)
391 (cond "maybe-more" t (receiver t) more-clause ...)))
393 ((_ (generator guard => receiver) more-clause ...)
394 (call-with-values (lambda () generator)
397 (apply guard t) (apply receiver t) more-clause ...))))
399 ((_ (test => receiver ...) more-clause ...)
400 (syntax-violation 'cond "wrong number of receiver expressions"
401 '(test => receiver ...)))
402 ((_ (generator guard => receiver ...) more-clause ...)
403 (syntax-violation 'cond "wrong number of receiver expressions"
404 '(generator guard => receiver ...)))
406 ((_ (test) more-clause ...)
408 (cond "maybe-more" t t more-clause ...)))
410 ((_ (test body1 body2 ...) more-clause ...)
412 test (begin body1 body2 ...) more-clause ...))))
418 (let ((atom-key (key ...)))
419 (case atom-key clauses ...)))
421 (else result1 result2 ...))
422 (begin result1 result2 ...))
424 ((atoms ...) result1 result2 ...))
425 (if (memv key '(atoms ...))
426 (begin result1 result2 ...)))
428 ((atoms ...) result1 result2 ...)
430 (if (memv key '(atoms ...))
431 (begin result1 result2 ...)
432 (case key clause clauses ...)))))
436 ((do ((var init step ...) ...)
449 (loop (do "step" var step ...)
459 ((_ exp) (make-promise (lambda () exp)))))
461 (include-from-path "ice-9/quasisyntax")
468 (define-syntax define-macro
472 ((_ (macro . args) doc body1 body ...)
473 (string? (syntax->datum #'doc))
474 #'(define-macro macro doc (lambda args body1 body ...)))
475 ((_ (macro . args) body ...)
476 #'(define-macro macro #f (lambda args body ...)))
477 ((_ macro doc transformer)
478 (or (string? (syntax->datum #'doc))
479 (not (syntax->datum #'doc)))
480 #'(define-syntax macro
483 #((macro-type . defmacro)
484 (defmacro-args args))
487 (let ((v (syntax->datum #'args)))
488 (datum->syntax y (apply transformer v)))))))))))
490 (define-syntax defmacro
492 "Define a defmacro, with the old lispy defun syntax."
494 ((_ macro args doc body1 body ...)
495 (string? (syntax->datum #'doc))
496 #'(define-macro macro doc (lambda args body1 body ...)))
497 ((_ macro args body ...)
498 #'(define-macro macro #f (lambda args body ...))))))
506 ;;; Depends on: defmacro
509 (defmacro begin-deprecated forms
510 (if (include-deprecated-features)
516 ;;; {Trivial Functions}
519 (define (identity x) x)
520 (define (and=> value procedure) (and value (procedure value)))
521 (define call/cc call-with-current-continuation)
523 ;;; apply-to-args is functionally redundant with apply and, worse,
524 ;;; is less general than apply since it only takes two arguments.
526 ;;; On the other hand, apply-to-args is a syntacticly convenient way to
527 ;;; perform binding in many circumstances when the "let" family of
528 ;;; of forms don't cut it. E.g.:
530 ;;; (apply-to-args (return-3d-mouse-coords)
535 (define (apply-to-args args fn) (apply fn args))
537 (defmacro false-if-exception (expr)
540 ;; avoid saving backtraces inside false-if-exception
541 (with-fluids ((the-last-stack (fluid-ref the-last-stack)))
547 ;;; {General Properties}
550 ;; This is a more modern interface to properties. It will replace all
551 ;; other property-like things eventually.
553 (define (make-object-property)
554 (let ((prop (primitive-make-property #f)))
555 (make-procedure-with-setter
556 (lambda (obj) (primitive-property-ref prop obj))
557 (lambda (obj val) (primitive-property-set! prop obj val)))))
561 ;;; {Symbol Properties}
564 (define (symbol-property sym prop)
565 (let ((pair (assoc prop (symbol-pref sym))))
566 (and pair (cdr pair))))
568 (define (set-symbol-property! sym prop val)
569 (let ((pair (assoc prop (symbol-pref sym))))
572 (symbol-pset! sym (acons prop val (symbol-pref sym))))))
574 (define (symbol-property-remove! sym prop)
575 (let ((pair (assoc prop (symbol-pref sym))))
577 (symbol-pset! sym (delq! pair (symbol-pref sym))))))
584 (define (array-shape a)
585 (map (lambda (ind) (if (number? ind) (list 0 (+ -1 ind)) ind))
586 (array-dimensions a)))
593 (define (kw-arg-ref args kw)
594 (let ((rem (member kw args)))
595 (and rem (pair? (cdr rem)) (cadr rem))))
602 (define (struct-layout s)
603 (struct-ref (struct-vtable s) vtable-index-layout))
610 ;; Printing records: by default, records are printed as
612 ;; #<type-name field1: val1 field2: val2 ...>
614 ;; You can change that by giving a custom printing function to
615 ;; MAKE-RECORD-TYPE (after the list of field symbols). This function
616 ;; will be called like
618 ;; (<printer> object port)
620 ;; It should print OBJECT to PORT.
622 (define (inherit-print-state old-port new-port)
623 (if (get-print-state old-port)
624 (port-with-print-state new-port (get-print-state old-port))
627 ;; 0: type-name, 1: fields, 2: constructor
628 (define record-type-vtable
629 ;; FIXME: This should just call make-vtable, not make-vtable-vtable; but for
630 ;; that we need to expose the bare vtable-vtable to Scheme.
631 (make-vtable-vtable "prprpw" 0
633 (cond ((eq? s record-type-vtable)
634 (display "#<record-type-vtable>" p))
636 (display "#<record-type " p)
637 (display (record-type-name s) p)
640 (define (record-type? obj)
641 (and (struct? obj) (eq? record-type-vtable (struct-vtable obj))))
643 (define* (make-record-type type-name fields #:optional printer)
644 ;; Pre-generate constructors for nfields < 20.
645 (define-syntax make-constructor
647 (define *max-static-argument-count* 20)
648 (define (make-formals n)
654 (string (integer->char (+ (char->integer #\a) i)))))
658 ((_ rtd exp) (not (identifier? #'exp))
660 (make-constructor rtd n)))
664 (if (< n *max-static-argument-count*)
665 (cons (with-syntax (((formal ...) (make-formals n))
669 (make-struct rtd 0 formal ...))))
674 (if (= (length args) nfields)
675 (apply make-struct rtd 0 args)
676 (scm-error 'wrong-number-of-args
677 (format #f "make-~a" type-name)
678 "Wrong number of arguments" '() #f)))))))))
680 (define (default-record-printer s p)
682 (display (record-type-name (record-type-descriptor s)) p)
683 (let loop ((fields (record-type-fields (record-type-descriptor s)))
686 ((not (null? fields))
688 (display (car fields) p)
690 (display (struct-ref s off) p)
691 (loop (cdr fields) (+ 1 off)))))
694 (let ((rtd (make-struct record-type-vtable 0
697 (map (lambda (f) "pw") fields)))
698 (or printer default-record-printer)
700 (copy-tree fields))))
701 (struct-set! rtd (+ vtable-offset-user 2)
702 (make-constructor rtd (length fields)))
703 ;; Temporary solution: Associate a name to the record type descriptor
704 ;; so that the object system can create a wrapper class for it.
705 (set-struct-vtable-name! rtd (if (symbol? type-name)
707 (string->symbol type-name)))
710 (define (record-type-name obj)
711 (if (record-type? obj)
712 (struct-ref obj vtable-offset-user)
713 (error 'not-a-record-type obj)))
715 (define (record-type-fields obj)
716 (if (record-type? obj)
717 (struct-ref obj (+ 1 vtable-offset-user))
718 (error 'not-a-record-type obj)))
720 (define* (record-constructor rtd #:optional field-names)
721 (if (not field-names)
722 (struct-ref rtd (+ 2 vtable-offset-user))
724 `(lambda ,field-names
725 (make-struct ',rtd 0 ,@(map (lambda (f)
726 (if (memq f field-names)
729 (record-type-fields rtd)))))))
731 (define (record-predicate rtd)
732 (lambda (obj) (and (struct? obj) (eq? rtd (struct-vtable obj)))))
734 (define (%record-type-error rtd obj) ;; private helper
735 (or (eq? rtd (record-type-descriptor obj))
736 (scm-error 'wrong-type-arg "%record-type-check"
737 "Wrong type record (want `~S'): ~S"
738 (list (record-type-name rtd) obj)
741 (define (record-accessor rtd field-name)
742 (let ((pos (list-index (record-type-fields rtd) field-name)))
744 (error 'no-such-field field-name))
746 (if (eq? (struct-vtable obj) rtd)
748 (%record-type-error rtd obj)))))
750 (define (record-modifier 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)
756 (struct-set! obj pos val)
757 (%record-type-error rtd obj)))))
759 (define (record? obj)
760 (and (struct? obj) (record-type? (struct-vtable obj))))
762 (define (record-type-descriptor obj)
765 (error 'not-a-record obj)))
774 (define (->bool x) (not (not x)))
781 (define (symbol-append . args)
782 (string->symbol (apply string-append (map symbol->string args))))
784 (define (list->symbol . args)
785 (string->symbol (apply list->string args)))
787 (define (symbol . args)
788 (string->symbol (apply string args)))
795 (define (list-index l k)
801 (loop (+ n 1) (cdr l))))))
805 (if (provided? 'posix)
806 (primitive-load-path "ice-9/posix"))
808 (if (provided? 'socket)
809 (primitive-load-path "ice-9/networking"))
811 ;; For reference, Emacs file-exists-p uses stat in this same way.
813 (if (provided? 'posix)
815 (->bool (stat str #f)))
817 (let ((port (catch 'system-error (lambda () (open-file str OPEN_READ))
819 (if port (begin (close-port port) #t)
822 (define file-is-directory?
823 (if (provided? 'posix)
825 (eq? (stat:type (stat str)) 'directory))
827 (let ((port (catch 'system-error
828 (lambda () (open-file (string-append str "/.")
831 (if port (begin (close-port port) #t)
834 (define (has-suffix? str suffix)
835 (string-suffix? suffix str))
837 (define (system-error-errno args)
838 (if (eq? (car args) 'system-error)
839 (car (list-ref args 4))
847 (define (error . args)
850 (scm-error 'misc-error #f "?" #f #f)
851 (let loop ((msg "~A")
853 (if (not (null? rest))
854 (loop (string-append msg " ~S")
856 (scm-error 'misc-error #f msg args #f)))))
858 ;; bad-throw is the hook that is called upon a throw to a an unhandled
859 ;; key (unless the throw has four arguments, in which case
860 ;; it's usually interpreted as an error throw.)
861 ;; If the key has a default handler (a throw-handler-default property),
862 ;; it is applied to the throw.
864 (define (bad-throw key . args)
865 (let ((default (symbol-property key 'throw-handler-default)))
866 (or (and default (apply default key args))
867 (apply error "unhandled-exception:" key args))))
871 (define (tm:sec obj) (vector-ref obj 0))
872 (define (tm:min obj) (vector-ref obj 1))
873 (define (tm:hour obj) (vector-ref obj 2))
874 (define (tm:mday obj) (vector-ref obj 3))
875 (define (tm:mon obj) (vector-ref obj 4))
876 (define (tm:year obj) (vector-ref obj 5))
877 (define (tm:wday obj) (vector-ref obj 6))
878 (define (tm:yday obj) (vector-ref obj 7))
879 (define (tm:isdst obj) (vector-ref obj 8))
880 (define (tm:gmtoff obj) (vector-ref obj 9))
881 (define (tm:zone obj) (vector-ref obj 10))
883 (define (set-tm:sec obj val) (vector-set! obj 0 val))
884 (define (set-tm:min obj val) (vector-set! obj 1 val))
885 (define (set-tm:hour obj val) (vector-set! obj 2 val))
886 (define (set-tm:mday obj val) (vector-set! obj 3 val))
887 (define (set-tm:mon obj val) (vector-set! obj 4 val))
888 (define (set-tm:year obj val) (vector-set! obj 5 val))
889 (define (set-tm:wday obj val) (vector-set! obj 6 val))
890 (define (set-tm:yday obj val) (vector-set! obj 7 val))
891 (define (set-tm:isdst obj val) (vector-set! obj 8 val))
892 (define (set-tm:gmtoff obj val) (vector-set! obj 9 val))
893 (define (set-tm:zone obj val) (vector-set! obj 10 val))
895 (define (tms:clock obj) (vector-ref obj 0))
896 (define (tms:utime obj) (vector-ref obj 1))
897 (define (tms:stime obj) (vector-ref obj 2))
898 (define (tms:cutime obj) (vector-ref obj 3))
899 (define (tms:cstime obj) (vector-ref obj 4))
901 (define file-position ftell)
902 (define* (file-set-position port offset #:optional (whence SEEK_SET))
903 (seek port offset whence))
905 (define (move->fdes fd/port fd)
906 (cond ((integer? fd/port)
907 (dup->fdes fd/port fd)
911 (primitive-move->fdes fd/port fd)
912 (set-port-revealed! fd/port 1)
915 (define (release-port-handle port)
916 (let ((revealed (port-revealed port)))
918 (set-port-revealed! port (- revealed 1)))))
923 (fdopen (dup->fdes port/fd) mode))
924 ((port/fd mode new-fd)
925 (let ((port (fdopen (dup->fdes port/fd new-fd) mode)))
926 (set-port-revealed! port 1)
932 (dup->port port/fd "r"))
934 (dup->port port/fd "r" new-fd))))
939 (dup->port port/fd "w"))
941 (dup->port port/fd "w" new-fd))))
946 (if (integer? port/fd)
948 (dup->port port/fd (port-mode port/fd))))
950 (if (integer? port/fd)
951 (dup->fdes port/fd new-fd)
952 (dup->port port/fd (port-mode port/fd) new-fd)))))
954 (define (duplicate-port port modes)
955 (dup->port port modes))
957 (define (fdes->inport fdes)
958 (let loop ((rest-ports (fdes->ports fdes)))
959 (cond ((null? rest-ports)
960 (let ((result (fdopen fdes "r")))
961 (set-port-revealed! result 1)
963 ((input-port? (car rest-ports))
964 (set-port-revealed! (car rest-ports)
965 (+ (port-revealed (car rest-ports)) 1))
968 (loop (cdr rest-ports))))))
970 (define (fdes->outport fdes)
971 (let loop ((rest-ports (fdes->ports fdes)))
972 (cond ((null? rest-ports)
973 (let ((result (fdopen fdes "w")))
974 (set-port-revealed! result 1)
976 ((output-port? (car rest-ports))
977 (set-port-revealed! (car rest-ports)
978 (+ (port-revealed (car rest-ports)) 1))
981 (loop (cdr rest-ports))))))
983 (define (port->fdes port)
984 (set-port-revealed! port (+ (port-revealed port) 1))
987 (define (setenv name value)
989 (putenv (string-append name "=" value))
992 (define (unsetenv name)
993 "Remove the entry for NAME from the environment."
1001 ;;; Here for backward compatability
1003 (define scheme-file-suffix (lambda () ".scm"))
1005 (define (in-vicinity vicinity file)
1006 (let ((tail (let ((len (string-length vicinity)))
1009 (string-ref vicinity (- len 1))))))
1010 (string-append vicinity
1019 ;;; {Help for scm_shell}
1021 ;;; The argument-processing code used by Guile-based shells generates
1022 ;;; Scheme code based on the argument list. This page contains help
1023 ;;; functions for the code it generates.
1026 (define (command-line) (program-arguments))
1028 ;; This is mostly for the internal use of the code generated by
1029 ;; scm_compile_shell_switches.
1031 (define (turn-on-debugging)
1032 (debug-enable 'debug)
1033 (debug-enable 'backtrace)
1034 (read-enable 'positions))
1036 (define (load-user-init)
1037 (let* ((home (or (getenv "HOME")
1038 (false-if-exception (passwd:dir (getpwuid (getuid))))
1039 "/")) ;; fallback for cygwin etc.
1040 (init-file (in-vicinity home ".guile")))
1041 (if (file-exists? init-file)
1042 (primitive-load init-file))))
1046 ;;; {The interpreter stack}
1049 ;; %stacks defined in stacks.c
1050 (define (%start-stack tag thunk)
1051 (let ((prompt-tag (make-prompt-tag "start-stack")))
1055 (with-fluids ((%stacks (acons tag prompt-tag
1056 (or (fluid-ref %stacks) '()))))
1059 (%start-stack tag (lambda () (apply k args)))))))
1060 (define-syntax start-stack
1063 (%start-stack tag (lambda () exp)))))
1067 ;;; {Loading by paths}
1070 ;;; Load a Scheme source file named NAME, searching for it in the
1071 ;;; directories listed in %load-path, and applying each of the file
1072 ;;; name extensions listed in %load-extensions.
1073 (define (load-from-path name)
1074 (start-stack 'load-stack
1075 (primitive-load-path name)))
1077 (define %load-verbosely #f)
1078 (define (assert-load-verbosity v) (set! %load-verbosely v))
1080 (define (%load-announce file)
1082 (with-output-to-port (current-error-port)
1085 (display "loading ")
1090 (set! %load-hook %load-announce)
1092 (define* (load name #:optional reader)
1093 ;; Returns the .go file corresponding to `name'. Does not search load
1094 ;; paths, only the fallback path. If the .go file is missing or out of
1095 ;; date, and autocompilation is enabled, will try autocompilation, just
1096 ;; as primitive-load-path does internally. primitive-load is
1097 ;; unaffected. Returns #f if autocompilation failed or was disabled.
1099 ;; NB: Unless we need to compile the file, this function should not cause
1100 ;; (system base compile) to be loaded up. For that reason compiled-file-name
1101 ;; partially duplicates functionality from (system base compile).
1102 (define (compiled-file-name canon-path)
1103 (and %compile-fallback-path
1105 %compile-fallback-path
1106 ;; no need for '/' separator here, canon-path is absolute
1108 (cond ((or (null? %load-compiled-extensions)
1109 (string-null? (car %load-compiled-extensions)))
1110 (warn "invalid %load-compiled-extensions"
1111 %load-compiled-extensions)
1113 (else (car %load-compiled-extensions))))))
1114 (define (fresh-compiled-file-name go-path)
1117 (let* ((scmstat (stat name))
1118 (gostat (stat go-path #f)))
1119 (if (and gostat (= (stat:mtime gostat) (stat:mtime scmstat)))
1123 (format (current-error-port)
1124 ";;; note: source file ~a\n;;; newer than compiled ~a\n"
1127 (%load-should-autocompile
1128 (%warn-autocompilation-enabled)
1129 (format (current-error-port) ";;; compiling ~a\n" name)
1130 (let ((cfn ((@ (system base compile) compile-file) name
1131 #:env (current-module))))
1132 (format (current-error-port) ";;; compiled ~a\n" cfn)
1136 (format (current-error-port)
1137 ";;; WARNING: compilation of ~a failed:\n;;; key ~a, throw_args ~s\n"
1140 (with-fluids ((current-reader reader))
1141 (let ((cfn (and=> (and=> (false-if-exception (canonicalize-path name))
1143 fresh-compiled-file-name)))
1146 (start-stack 'load-stack
1147 (primitive-load name))))))
1151 ;;; {Reader Extensions}
1153 ;;; Reader code for various "#c" forms.
1156 (define read-eval? (make-fluid))
1157 (fluid-set! read-eval? #f)
1158 (read-hash-extend #\.
1160 (if (fluid-ref read-eval?)
1161 (eval (read port) (interaction-environment))
1163 "#. read expansion found and read-eval? is #f."))))
1167 ;;; {Command Line Options}
1170 (define (get-option argv kw-opts kw-args return)
1173 (return #f #f argv))
1175 ((or (not (eq? #\- (string-ref (car argv) 0)))
1176 (eq? (string-length (car argv)) 1))
1177 (return 'normal-arg (car argv) (cdr argv)))
1179 ((eq? #\- (string-ref (car argv) 1))
1180 (let* ((kw-arg-pos (or (string-index (car argv) #\=)
1181 (string-length (car argv))))
1182 (kw (symbol->keyword (substring (car argv) 2 kw-arg-pos)))
1183 (kw-opt? (member kw kw-opts))
1184 (kw-arg? (member kw kw-args))
1185 (arg (or (and (not (eq? kw-arg-pos (string-length (car argv))))
1186 (substring (car argv)
1188 (string-length (car argv))))
1190 (begin (set! argv (cdr argv)) (car argv))))))
1191 (if (or kw-opt? kw-arg?)
1192 (return kw arg (cdr argv))
1193 (return 'usage-error kw (cdr argv)))))
1196 (let* ((char (substring (car argv) 1 2))
1197 (kw (symbol->keyword char)))
1200 ((member kw kw-opts)
1201 (let* ((rest-car (substring (car argv) 2 (string-length (car argv))))
1202 (new-argv (if (= 0 (string-length rest-car))
1204 (cons (string-append "-" rest-car) (cdr argv)))))
1205 (return kw #f new-argv)))
1207 ((member kw kw-args)
1208 (let* ((rest-car (substring (car argv) 2 (string-length (car argv))))
1209 (arg (if (= 0 (string-length rest-car))
1212 (new-argv (if (= 0 (string-length rest-car))
1215 (return kw arg new-argv)))
1217 (else (return 'usage-error kw argv)))))))
1219 (define (for-next-option proc argv kw-opts kw-args)
1220 (let loop ((argv argv))
1221 (get-option argv kw-opts kw-args
1222 (lambda (opt opt-arg argv)
1223 (and opt (proc opt opt-arg argv loop))))))
1225 (define (display-usage-report kw-desc)
1228 (or (eq? (car kw) #t)
1229 (eq? (car kw) 'else)
1230 (let* ((opt-desc kw)
1231 (help (cadr opt-desc))
1232 (opts (car opt-desc))
1233 (opts-proper (if (string? (car opts)) (cdr opts) opts))
1234 (arg-name (if (string? (car opts))
1235 (string-append "<" (car opts) ">")
1237 (left-part (string-append
1238 (with-output-to-string
1240 (map (lambda (x) (display (keyword->symbol x)) (display " "))
1243 (middle-part (if (and (< (string-length left-part) 30)
1244 (< (string-length help) 40))
1245 (make-string (- 30 (string-length left-part)) #\ )
1248 (display middle-part)
1255 (define (transform-usage-lambda cases)
1256 (let* ((raw-usage (delq! 'else (map car cases)))
1257 (usage-sans-specials (map (lambda (x)
1258 (or (and (not (list? x)) x)
1259 (and (symbol? (car x)) #t)
1260 (and (boolean? (car x)) #t)
1263 (usage-desc (delq! #t usage-sans-specials))
1264 (kw-desc (map car usage-desc))
1265 (kw-opts (apply append (map (lambda (x) (and (not (string? (car x))) x)) kw-desc)))
1266 (kw-args (apply append (map (lambda (x) (and (string? (car x)) (cdr x))) kw-desc)))
1267 (transmogrified-cases (map (lambda (case)
1268 (cons (let ((opts (car case)))
1269 (if (or (boolean? opts) (eq? 'else opts))
1272 ((symbol? (car opts)) opts)
1273 ((boolean? (car opts)) opts)
1274 ((string? (caar opts)) (cdar opts))
1275 (else (car opts)))))
1278 `(let ((%display-usage (lambda () (display-usage-report ',usage-desc))))
1280 (let %next-arg ((%argv %argv))
1284 (lambda (%opt %arg %new-argv)
1286 ,@ transmogrified-cases))))))))
1291 ;;; {Low Level Modules}
1293 ;;; These are the low level data structures for modules.
1295 ;;; Every module object is of the type 'module-type', which is a record
1296 ;;; consisting of the following members:
1298 ;;; - eval-closure: the function that defines for its module the strategy that
1299 ;;; shall be followed when looking up symbols in the module.
1301 ;;; An eval-closure is a function taking two arguments: the symbol to be
1302 ;;; looked up and a boolean value telling whether a binding for the symbol
1303 ;;; should be created if it does not exist yet. If the symbol lookup
1304 ;;; succeeded (either because an existing binding was found or because a new
1305 ;;; binding was created), a variable object representing the binding is
1306 ;;; returned. Otherwise, the value #f is returned. Note that the eval
1307 ;;; closure does not take the module to be searched as an argument: During
1308 ;;; construction of the eval-closure, the eval-closure has to store the
1309 ;;; module it belongs to in its environment. This means, that any
1310 ;;; eval-closure can belong to only one module.
1312 ;;; The eval-closure of a module can be defined arbitrarily. However, three
1313 ;;; special cases of eval-closures are to be distinguished: During startup
1314 ;;; the module system is not yet activated. In this phase, no modules are
1315 ;;; defined and all bindings are automatically stored by the system in the
1316 ;;; pre-modules-obarray. Since no eval-closures exist at this time, the
1317 ;;; functions which require an eval-closure as their argument need to be
1318 ;;; passed the value #f.
1320 ;;; The other two special cases of eval-closures are the
1321 ;;; standard-eval-closure and the standard-interface-eval-closure. Both
1322 ;;; behave equally for the case that no new binding is to be created. The
1323 ;;; difference between the two comes in, when the boolean argument to the
1324 ;;; eval-closure indicates that a new binding shall be created if it is not
1327 ;;; Given that no new binding shall be created, both standard eval-closures
1328 ;;; define the following standard strategy of searching bindings in the
1329 ;;; module: First, the module's obarray is searched for the symbol. Second,
1330 ;;; if no binding for the symbol was found in the module's obarray, the
1331 ;;; module's binder procedure is exececuted. If this procedure did not
1332 ;;; return a binding for the symbol, the modules referenced in the module's
1333 ;;; uses list are recursively searched for a binding of the symbol. If the
1334 ;;; binding can not be found in these modules also, the symbol lookup has
1337 ;;; If a new binding shall be created, the standard-interface-eval-closure
1338 ;;; immediately returns indicating failure. That is, it does not even try
1339 ;;; to look up the symbol. In contrast, the standard-eval-closure would
1340 ;;; first search the obarray, and if no binding was found there, would
1341 ;;; create a new binding in the obarray, therefore not calling the binder
1342 ;;; procedure or searching the modules in the uses list.
1344 ;;; The explanation of the following members obarray, binder and uses
1345 ;;; assumes that the symbol lookup follows the strategy that is defined in
1346 ;;; the standard-eval-closure and the standard-interface-eval-closure.
1348 ;;; - obarray: a hash table that maps symbols to variable objects. In this
1349 ;;; hash table, the definitions are found that are local to the module (that
1350 ;;; is, not imported from other modules). When looking up bindings in the
1351 ;;; module, this hash table is searched first.
1353 ;;; - binder: either #f or a function taking a module and a symbol argument.
1354 ;;; If it is a function it is called after the obarray has been
1355 ;;; unsuccessfully searched for a binding. It then can provide bindings
1356 ;;; that would otherwise not be found locally in the module.
1358 ;;; - uses: a list of modules from which non-local bindings can be inherited.
1359 ;;; These modules are the third place queried for bindings after the obarray
1360 ;;; has been unsuccessfully searched and the binder function did not deliver
1361 ;;; a result either.
1363 ;;; - transformer: either #f or a function taking a scheme expression as
1364 ;;; delivered by read. If it is a function, it will be called to perform
1365 ;;; syntax transformations (e. g. makro expansion) on the given scheme
1366 ;;; expression. The output of the transformer function will then be passed
1367 ;;; to Guile's internal memoizer. This means that the output must be valid
1368 ;;; scheme code. The only exception is, that the output may make use of the
1369 ;;; syntax extensions provided to identify the modules that a binding
1372 ;;; - name: the name of the module. This is used for all kinds of printing
1373 ;;; outputs. In certain places the module name also serves as a way of
1374 ;;; identification. When adding a module to the uses list of another
1375 ;;; module, it is made sure that the new uses list will not contain two
1376 ;;; modules of the same name.
1378 ;;; - kind: classification of the kind of module. The value is (currently?)
1379 ;;; only used for printing. It has no influence on how a module is treated.
1380 ;;; Currently the following values are used when setting the module kind:
1381 ;;; 'module, 'directory, 'interface, 'custom-interface. If no explicit kind
1382 ;;; is set, it defaults to 'module.
1384 ;;; - duplicates-handlers: a list of procedures that get called to make a
1385 ;;; choice between two duplicate bindings when name clashes occur. See the
1386 ;;; `duplicate-handlers' global variable below.
1388 ;;; - observers: a list of procedures that get called when the module is
1391 ;;; - weak-observers: a weak-key hash table of procedures that get called
1392 ;;; when the module is modified. See `module-observe-weak' for details.
1394 ;;; In addition, the module may (must?) contain a binding for
1395 ;;; `%module-public-interface'. This variable should be bound to a module
1396 ;;; representing the exported interface of a module. See the
1397 ;;; `module-public-interface' and `module-export!' procedures.
1399 ;;; !!! warning: The interface to lazy binder procedures is going
1400 ;;; to be changed in an incompatible way to permit all the basic
1401 ;;; module ops to be virtualized.
1403 ;;; (make-module size use-list lazy-binding-proc) => module
1404 ;;; module-{obarray,uses,binder}[|-set!]
1405 ;;; (module? obj) => [#t|#f]
1406 ;;; (module-locally-bound? module symbol) => [#t|#f]
1407 ;;; (module-bound? module symbol) => [#t|#f]
1408 ;;; (module-symbol-locally-interned? module symbol) => [#t|#f]
1409 ;;; (module-symbol-interned? module symbol) => [#t|#f]
1410 ;;; (module-local-variable module symbol) => [#<variable ...> | #f]
1411 ;;; (module-variable module symbol) => [#<variable ...> | #f]
1412 ;;; (module-symbol-binding module symbol opt-value)
1413 ;;; => [ <obj> | opt-value | an error occurs ]
1414 ;;; (module-make-local-var! module symbol) => #<variable...>
1415 ;;; (module-add! module symbol var) => unspecified
1416 ;;; (module-remove! module symbol) => unspecified
1417 ;;; (module-for-each proc module) => unspecified
1418 ;;; (make-scm-module) => module ; a lazy copy of the symhash module
1419 ;;; (set-current-module module) => unspecified
1420 ;;; (current-module) => #<module...>
1426 ;;; {Printing Modules}
1429 ;; This is how modules are printed. You can re-define it.
1430 (define (%print-module mod port)
1432 (display (or (module-kind mod) "module") port)
1434 (display (module-name mod) port)
1436 (display (number->string (object-address mod) 16) port)
1440 ;; Locally extend the syntax to allow record accessors to be defined at
1441 ;; compile-time. Cache the rtd locally to the constructor, the getters and
1442 ;; the setters, in order to allow for redefinition of the record type; not
1443 ;; relevant in the case of modules, but perhaps if we make this public, it
1446 ((define-record-type
1448 (define (make-id scope . fragments)
1449 (datum->syntax #'scope
1450 (apply symbol-append
1452 (if (symbol? x) x (syntax->datum x)))
1455 (define (getter rtd type-name field slot)
1456 #`(define #,(make-id rtd type-name '- field)
1458 (lambda (#,type-name)
1459 (if (eq? (struct-vtable #,type-name) rtd)
1460 (struct-ref #,type-name #,slot)
1461 (%record-type-error rtd #,type-name))))))
1463 (define (setter rtd type-name field slot)
1464 #`(define #,(make-id rtd 'set- type-name '- field '!)
1466 (lambda (#,type-name val)
1467 (if (eq? (struct-vtable #,type-name) rtd)
1468 (struct-set! #,type-name #,slot val)
1469 (%record-type-error rtd #,type-name))))))
1471 (define (accessors rtd type-name fields n exp)
1472 (syntax-case fields ()
1474 (((field #:no-accessors) field* ...) (identifier? #'field)
1475 (accessors rtd type-name #'(field* ...) (1+ n)
1477 (((field #:no-setter) field* ...) (identifier? #'field)
1478 (accessors rtd type-name #'(field* ...) (1+ n)
1480 #,(getter rtd type-name #'field n))))
1481 (((field #:no-getter) field* ...) (identifier? #'field)
1482 (accessors rtd type-name #'(field* ...) (1+ n)
1484 #,(setter rtd type-name #'field n))))
1485 ((field field* ...) (identifier? #'field)
1486 (accessors rtd type-name #'(field* ...) (1+ n)
1488 #,(getter rtd type-name #'field n)
1489 #,(setter rtd type-name #'field n))))))
1491 (define (predicate rtd type-name fields exp)
1493 rtd type-name fields 0
1496 (define (#,(make-id rtd type-name '?) obj)
1497 (and (struct? obj) (eq? (struct-vtable obj) #,rtd))))))
1499 (define (field-list fields)
1500 (syntax-case fields ()
1502 (((f . opts) . rest) (identifier? #'f)
1503 (cons #'f (field-list #'rest)))
1504 ((f . rest) (identifier? #'f)
1505 (cons #'f (field-list #'rest)))))
1507 (define (constructor rtd type-name fields exp)
1508 (let ((ctor (make-id rtd type-name '-constructor))
1509 (args (field-list fields)))
1510 (predicate rtd type-name fields
1515 (make-struct rtd 0 #,@args))))
1516 (struct-set! #,rtd (+ vtable-offset-user 2)
1519 (define (type type-name printer fields)
1520 (define (make-layout)
1521 (let lp ((fields fields) (slots '()))
1522 (syntax-case fields ()
1523 (() (datum->syntax #'here
1525 (apply string-append slots))))
1526 ((_ . rest) (lp #'rest (cons "pw" slots))))))
1528 (let ((rtd (make-id type-name type-name '-type)))
1529 (constructor rtd type-name fields
1532 (make-struct record-type-vtable 0
1536 '#,(field-list fields)))
1537 (set-struct-vtable-name! #,rtd '#,type-name)))))
1540 ((_ type-name printer (field ...))
1541 (type #'type-name #'printer #'(field ...)))))))
1545 ;; A module is characterized by an obarray in which local symbols
1546 ;; are interned, a list of modules, "uses", from which non-local
1547 ;; bindings can be inherited, and an optional lazy-binder which
1548 ;; is a (CLOSURE module symbol) which, as a last resort, can provide
1549 ;; bindings that would otherwise not be found locally in the module.
1551 ;; NOTE: If you change the set of fields or their order, you also need to
1552 ;; change the constants in libguile/modules.h.
1554 ;; NOTE: The getter `module-eval-closure' is used in libguile/modules.c.
1555 ;; NOTE: The getter `module-transfomer' is defined libguile/modules.c.
1556 ;; NOTE: The getter `module-name' is defined later, due to boot reasons.
1557 ;; NOTE: The getter `module-public-interface' is used in libguile/modules.c.
1559 (define-record-type module
1560 (lambda (obj port) (%print-module obj port))
1565 (transformer #:no-getter)
1569 (import-obarray #:no-setter)
1571 (weak-observers #:no-setter)
1578 ;; make-module &opt size uses binder
1580 ;; Create a new module, perhaps with a particular size of obarray,
1581 ;; initial uses list, or binding procedure.
1586 (define (parse-arg index default)
1587 (if (> (length args) index)
1588 (list-ref args index)
1591 (define %default-import-size
1592 ;; Typical number of imported bindings actually used by a module.
1595 (if (> (length args) 3)
1596 (error "Too many args to make-module." args))
1598 (let ((size (parse-arg 0 31))
1599 (uses (parse-arg 1 '()))
1600 (binder (parse-arg 2 #f)))
1602 (if (not (integer? size))
1603 (error "Illegal size to make-module." size))
1604 (if (not (and (list? uses)
1605 (and-map module? uses)))
1606 (error "Incorrect use list." uses))
1607 (if (and binder (not (procedure? binder)))
1609 "Lazy-binder expected to be a procedure or #f." binder))
1611 (let ((module (module-constructor (make-hash-table size)
1612 uses binder #f macroexpand
1614 (make-hash-table %default-import-size)
1616 (make-weak-key-hash-table 31) #f
1617 (make-hash-table 7) #f #f)))
1619 ;; We can't pass this as an argument to module-constructor,
1620 ;; because we need it to close over a pointer to the module
1622 (set-module-eval-closure! module (standard-eval-closure module))
1629 ;;; {Observer protocol}
1632 (define (module-observe module proc)
1633 (set-module-observers! module (cons proc (module-observers module)))
1636 (define* (module-observe-weak module observer-id #:optional (proc observer-id))
1637 ;; Register PROC as an observer of MODULE under name OBSERVER-ID (which can
1638 ;; be any Scheme object). PROC is invoked and passed MODULE any time
1639 ;; MODULE is modified. PROC gets unregistered when OBSERVER-ID gets GC'd
1640 ;; (thus, it is never unregistered if OBSERVER-ID is an immediate value,
1643 ;; The two-argument version is kept for backward compatibility: when called
1644 ;; with two arguments, the observer gets unregistered when closure PROC
1645 ;; gets GC'd (making it impossible to use an anonymous lambda for PROC).
1646 (hashq-set! (module-weak-observers module) observer-id proc))
1648 (define (module-unobserve token)
1649 (let ((module (car token))
1652 (hash-remove! (module-weak-observers module) id)
1653 (set-module-observers! module (delq1! id (module-observers module)))))
1656 (define module-defer-observers #f)
1657 (define module-defer-observers-mutex (make-mutex 'recursive))
1658 (define module-defer-observers-table (make-hash-table))
1660 (define (module-modified m)
1661 (if module-defer-observers
1662 (hash-set! module-defer-observers-table m #t)
1663 (module-call-observers m)))
1665 ;;; This function can be used to delay calls to observers so that they
1666 ;;; can be called once only in the face of massive updating of modules.
1668 (define (call-with-deferred-observers thunk)
1671 (lock-mutex module-defer-observers-mutex)
1672 (set! module-defer-observers #t))
1675 (set! module-defer-observers #f)
1676 (hash-for-each (lambda (m dummy)
1677 (module-call-observers m))
1678 module-defer-observers-table)
1679 (hash-clear! module-defer-observers-table)
1680 (unlock-mutex module-defer-observers-mutex))))
1682 (define (module-call-observers m)
1683 (for-each (lambda (proc) (proc m)) (module-observers m))
1685 ;; We assume that weak observers don't (un)register themselves as they are
1686 ;; called since this would preclude proper iteration over the hash table
1688 (hash-for-each (lambda (id proc) (proc m)) (module-weak-observers m)))
1692 ;;; {Module Searching in General}
1694 ;;; We sometimes want to look for properties of a symbol
1695 ;;; just within the obarray of one module. If the property
1696 ;;; holds, then it is said to hold ``locally'' as in, ``The symbol
1697 ;;; DISPLAY is locally rebound in the module `safe-guile'.''
1700 ;;; Other times, we want to test for a symbol property in the obarray
1701 ;;; of M and, if it is not found there, try each of the modules in the
1702 ;;; uses list of M. This is the normal way of testing for some
1703 ;;; property, so we state these properties without qualification as
1704 ;;; in: ``The symbol 'fnord is interned in module M because it is
1705 ;;; interned locally in module M2 which is a member of the uses list
1709 ;; module-search fn m
1711 ;; return the first non-#f result of FN applied to M and then to
1712 ;; the modules in the uses of m, and so on recursively. If all applications
1713 ;; return #f, then so does this function.
1715 (define (module-search fn m v)
1718 (or (module-search fn (car pos) v)
1721 (loop (module-uses m))))
1724 ;;; {Is a symbol bound in a module?}
1726 ;;; Symbol S in Module M is bound if S is interned in M and if the binding
1727 ;;; of S in M has been set to some well-defined value.
1730 ;; module-locally-bound? module symbol
1732 ;; Is a symbol bound (interned and defined) locally in a given module?
1734 (define (module-locally-bound? m v)
1735 (let ((var (module-local-variable m v)))
1737 (variable-bound? var))))
1739 ;; module-bound? module symbol
1741 ;; Is a symbol bound (interned and defined) anywhere in a given module
1744 (define (module-bound? m v)
1745 (let ((var (module-variable m v)))
1747 (variable-bound? var))))
1749 ;;; {Is a symbol interned in a module?}
1751 ;;; Symbol S in Module M is interned if S occurs in
1752 ;;; of S in M has been set to some well-defined value.
1754 ;;; It is possible to intern a symbol in a module without providing
1755 ;;; an initial binding for the corresponding variable. This is done
1757 ;;; (module-add! module symbol (make-undefined-variable))
1759 ;;; In that case, the symbol is interned in the module, but not
1760 ;;; bound there. The unbound symbol shadows any binding for that
1761 ;;; symbol that might otherwise be inherited from a member of the uses list.
1764 (define (module-obarray-get-handle ob key)
1765 ((if (symbol? key) hashq-get-handle hash-get-handle) ob key))
1767 (define (module-obarray-ref ob key)
1768 ((if (symbol? key) hashq-ref hash-ref) ob key))
1770 (define (module-obarray-set! ob key val)
1771 ((if (symbol? key) hashq-set! hash-set!) ob key val))
1773 (define (module-obarray-remove! ob key)
1774 ((if (symbol? key) hashq-remove! hash-remove!) ob key))
1776 ;; module-symbol-locally-interned? module symbol
1778 ;; is a symbol interned (not neccessarily defined) locally in a given module
1779 ;; or its uses? Interned symbols shadow inherited bindings even if
1780 ;; they are not themselves bound to a defined value.
1782 (define (module-symbol-locally-interned? m v)
1783 (not (not (module-obarray-get-handle (module-obarray m) v))))
1785 ;; module-symbol-interned? module symbol
1787 ;; is a symbol interned (not neccessarily defined) anywhere in a given module
1788 ;; or its uses? Interned symbols shadow inherited bindings even if
1789 ;; they are not themselves bound to a defined value.
1791 (define (module-symbol-interned? m v)
1792 (module-search module-symbol-locally-interned? m v))
1795 ;;; {Mapping modules x symbols --> variables}
1798 ;; module-local-variable module symbol
1799 ;; return the local variable associated with a MODULE and SYMBOL.
1801 ;;; This function is very important. It is the only function that can
1802 ;;; return a variable from a module other than the mutators that store
1803 ;;; new variables in modules. Therefore, this function is the location
1804 ;;; of the "lazy binder" hack.
1806 ;;; If symbol is defined in MODULE, and if the definition binds symbol
1807 ;;; to a variable, return that variable object.
1809 ;;; If the symbols is not found at first, but the module has a lazy binder,
1810 ;;; then try the binder.
1812 ;;; If the symbol is not found at all, return #f.
1814 ;;; (This is now written in C, see `modules.c'.)
1817 ;;; {Mapping modules x symbols --> bindings}
1819 ;;; These are similar to the mapping to variables, except that the
1820 ;;; variable is dereferenced.
1823 ;; module-symbol-binding module symbol opt-value
1825 ;; return the binding of a variable specified by name within
1826 ;; a given module, signalling an error if the variable is unbound.
1827 ;; If the OPT-VALUE is passed, then instead of signalling an error,
1828 ;; return OPT-VALUE.
1830 (define (module-symbol-local-binding m v . opt-val)
1831 (let ((var (module-local-variable m v)))
1832 (if (and var (variable-bound? var))
1834 (if (not (null? opt-val))
1836 (error "Locally unbound variable." v)))))
1838 ;; module-symbol-binding module symbol opt-value
1840 ;; return the binding of a variable specified by name within
1841 ;; a given module, signalling an error if the variable is unbound.
1842 ;; If the OPT-VALUE is passed, then instead of signalling an error,
1843 ;; return OPT-VALUE.
1845 (define (module-symbol-binding m v . opt-val)
1846 (let ((var (module-variable m v)))
1847 (if (and var (variable-bound? var))
1849 (if (not (null? opt-val))
1851 (error "Unbound variable." v)))))
1856 ;;; {Adding Variables to Modules}
1859 ;; module-make-local-var! module symbol
1861 ;; ensure a variable for V in the local namespace of M.
1862 ;; If no variable was already there, then create a new and uninitialzied
1865 ;; This function is used in modules.c.
1867 (define (module-make-local-var! m v)
1868 (or (let ((b (module-obarray-ref (module-obarray m) v)))
1871 ;; Mark as modified since this function is called when
1872 ;; the standard eval closure defines a binding
1876 ;; Create a new local variable.
1877 (let ((local-var (make-undefined-variable)))
1878 (module-add! m v local-var)
1881 ;; module-ensure-local-variable! module symbol
1883 ;; Ensure that there is a local variable in MODULE for SYMBOL. If
1884 ;; there is no binding for SYMBOL, create a new uninitialized
1885 ;; variable. Return the local variable.
1887 (define (module-ensure-local-variable! module symbol)
1888 (or (module-local-variable module symbol)
1889 (let ((var (make-undefined-variable)))
1890 (module-add! module symbol var)
1893 ;; module-add! module symbol var
1895 ;; ensure a particular variable for V in the local namespace of M.
1897 (define (module-add! m v var)
1898 (if (not (variable? var))
1899 (error "Bad variable to module-add!" var))
1900 (module-obarray-set! (module-obarray m) v var)
1901 (module-modified m))
1905 ;; make sure that a symbol is undefined in the local namespace of M.
1907 (define (module-remove! m v)
1908 (module-obarray-remove! (module-obarray m) v)
1909 (module-modified m))
1911 (define (module-clear! m)
1912 (hash-clear! (module-obarray m))
1913 (module-modified m))
1915 ;; MODULE-FOR-EACH -- exported
1917 ;; Call PROC on each symbol in MODULE, with arguments of (SYMBOL VARIABLE).
1919 (define (module-for-each proc module)
1920 (hash-for-each proc (module-obarray module)))
1922 (define (module-map proc module)
1923 (hash-map->list proc (module-obarray module)))
1927 ;; Modules exist in a separate namespace from values, because you generally do
1928 ;; not want the name of a submodule, which you might not even use, to collide
1929 ;; with local variables that happen to be named the same as the submodule.
1931 (define (module-ref-submodule module name)
1932 (or (hashq-ref (module-submodules module) name)
1933 (and (module-submodule-binder module)
1934 ((module-submodule-binder module) module name))))
1936 (define (module-define-submodule! module name submodule)
1937 (hashq-set! (module-submodules module) name submodule))
1941 ;;; {Low Level Bootstrapping}
1946 ;; A root module uses the pre-modules-obarray as its obarray. This
1947 ;; special obarray accumulates all bindings that have been established
1948 ;; before the module system is fully booted.
1950 ;; (The obarray continues to be used by code that has been closed over
1951 ;; before the module system has been booted.)
1953 (define (make-root-module)
1954 (let ((m (make-module 0)))
1955 (set-module-obarray! m (%get-pre-modules-obarray))
1960 ;; The root interface is a module that uses the same obarray as the
1961 ;; root module. It does not allow new definitions, tho.
1963 (define (make-scm-module)
1964 (let ((m (make-module 0)))
1965 (set-module-obarray! m (%get-pre-modules-obarray))
1966 (set-module-eval-closure! m (standard-interface-eval-closure m))
1972 ;;; {Module-based Loading}
1975 (define (save-module-excursion thunk)
1976 (let ((inner-module (current-module))
1978 (dynamic-wind (lambda ()
1979 (set! outer-module (current-module))
1980 (set-current-module inner-module)
1981 (set! inner-module #f))
1984 (set! inner-module (current-module))
1985 (set-current-module outer-module)
1986 (set! outer-module #f)))))
1988 (define basic-load load)
1990 (define* (load-module filename #:optional reader)
1991 (save-module-excursion
1993 (let ((oldname (and (current-load-port)
1994 (port-filename (current-load-port)))))
1995 (basic-load (if (and oldname
1996 (> (string-length filename) 0)
1997 (not (char=? (string-ref filename 0) #\/))
1998 (not (string=? (dirname oldname) ".")))
1999 (string-append (dirname oldname) "/" filename)
2006 ;;; {MODULE-REF -- exported}
2009 ;; Returns the value of a variable called NAME in MODULE or any of its
2010 ;; used modules. If there is no such variable, then if the optional third
2011 ;; argument DEFAULT is present, it is returned; otherwise an error is signaled.
2013 (define (module-ref module name . rest)
2014 (let ((variable (module-variable module name)))
2015 (if (and variable (variable-bound? variable))
2016 (variable-ref variable)
2018 (error "No variable named" name 'in module)
2019 (car rest) ; default value
2022 ;; MODULE-SET! -- exported
2024 ;; Sets the variable called NAME in MODULE (or in a module that MODULE uses)
2025 ;; to VALUE; if there is no such variable, an error is signaled.
2027 (define (module-set! module name value)
2028 (let ((variable (module-variable module name)))
2030 (variable-set! variable value)
2031 (error "No variable named" name 'in module))))
2033 ;; MODULE-DEFINE! -- exported
2035 ;; Sets the variable called NAME in MODULE to VALUE; if there is no such
2036 ;; variable, it is added first.
2038 (define (module-define! module name value)
2039 (let ((variable (module-local-variable module name)))
2042 (variable-set! variable value)
2043 (module-modified module))
2044 (let ((variable (make-variable value)))
2045 (module-add! module name variable)))))
2047 ;; MODULE-DEFINED? -- exported
2049 ;; Return #t iff NAME is defined in MODULE (or in a module that MODULE
2052 (define (module-defined? module name)
2053 (let ((variable (module-variable module name)))
2054 (and variable (variable-bound? variable))))
2056 ;; MODULE-USE! module interface
2058 ;; Add INTERFACE to the list of interfaces used by MODULE.
2060 (define (module-use! module interface)
2061 (if (not (or (eq? module interface)
2062 (memq interface (module-uses module))))
2064 ;; Newly used modules must be appended rather than consed, so that
2065 ;; `module-variable' traverses the use list starting from the first
2067 (set-module-uses! module
2068 (append (filter (lambda (m)
2070 (equal? (module-name m)
2071 (module-name interface))))
2072 (module-uses module))
2074 (hash-clear! (module-import-obarray module))
2075 (module-modified module))))
2077 ;; MODULE-USE-INTERFACES! module interfaces
2079 ;; Same as MODULE-USE! but add multiple interfaces and check for duplicates
2081 (define (module-use-interfaces! module interfaces)
2082 (set-module-uses! module
2083 (append (module-uses module) interfaces))
2084 (hash-clear! (module-import-obarray module))
2085 (module-modified module))
2089 ;;; {Recursive Namespaces}
2091 ;;; A hierarchical namespace emerges if we consider some module to be
2092 ;;; root, and submodules of that module to be nested namespaces.
2094 ;;; The routines here manage variable names in hierarchical namespace.
2095 ;;; Each variable name is a list of elements, looked up in successively nested
2098 ;;; (nested-ref some-root-module '(foo bar baz))
2099 ;;; => <value of a variable named baz in the submodule bar of
2100 ;;; the submodule foo of some-root-module>
2105 ;;; ;; a-root is a module
2106 ;;; ;; name is a list of symbols
2108 ;;; nested-ref a-root name
2109 ;;; nested-set! a-root name val
2110 ;;; nested-define! a-root name val
2111 ;;; nested-remove! a-root name
2113 ;;; These functions manipulate values in namespaces. For referencing the
2114 ;;; namespaces themselves, use the following:
2116 ;;; nested-ref-module a-root name
2117 ;;; nested-define-module! a-root name mod
2119 ;;; (current-module) is a natural choice for a root so for convenience there are
2122 ;;; local-ref name == nested-ref (current-module) name
2123 ;;; local-set! name val == nested-set! (current-module) name val
2124 ;;; local-define name val == nested-define! (current-module) name val
2125 ;;; local-remove name == nested-remove! (current-module) name
2126 ;;; local-ref-module name == nested-ref-module (current-module) name
2127 ;;; local-define-module! name m == nested-define-module! (current-module) name m
2131 (define (nested-ref root names)
2134 (let loop ((cur root)
2138 (module-ref cur head #f)
2139 (let ((cur (module-ref-submodule cur head)))
2141 (loop cur (car tail) (cdr tail))))))))
2143 (define (nested-set! root names val)
2144 (let loop ((cur root)
2148 (module-set! cur head val)
2149 (let ((cur (module-ref-submodule cur head)))
2151 (error "failed to resolve module" names)
2152 (loop cur (car tail) (cdr tail)))))))
2154 (define (nested-define! root names val)
2155 (let loop ((cur root)
2159 (module-define! cur head val)
2160 (let ((cur (module-ref-submodule cur head)))
2162 (error "failed to resolve module" names)
2163 (loop cur (car tail) (cdr tail)))))))
2165 (define (nested-remove! root names)
2166 (let loop ((cur root)
2170 (module-remove! cur head)
2171 (let ((cur (module-ref-submodule cur head)))
2173 (error "failed to resolve module" names)
2174 (loop cur (car tail) (cdr tail)))))))
2177 (define (nested-ref-module root names)
2178 (let loop ((cur root)
2182 (let ((cur (module-ref-submodule cur (car names))))
2184 (loop cur (cdr names)))))))
2186 (define (nested-define-module! root names module)
2188 (error "can't redefine root module" root module)
2189 (let loop ((cur root)
2193 (module-define-submodule! cur head module)
2194 (let ((cur (or (module-ref-submodule cur head)
2195 (let ((m (make-module 31)))
2196 (set-module-kind! m 'directory)
2197 (set-module-name! m (append (module-name cur)
2199 (module-define-submodule! cur head m)
2201 (loop cur (car tail) (cdr tail)))))))
2204 (define (local-ref names) (nested-ref (current-module) names))
2205 (define (local-set! names val) (nested-set! (current-module) names val))
2206 (define (local-define names val) (nested-define! (current-module) names val))
2207 (define (local-remove names) (nested-remove! (current-module) names))
2208 (define (local-ref-module names) (nested-ref-module (current-module) names))
2209 (define (local-define-module names mod) (nested-define-module! (current-module) names mod))
2215 ;;; {The (guile) module}
2217 ;;; The standard module, which has the core Guile bindings. Also called the
2218 ;;; "root module", as it is imported by many other modules, but it is not
2219 ;;; necessarily the root of anything; and indeed, the module named '() might be
2220 ;;; better thought of as a root.
2223 (define (set-system-module! m s)
2224 (set-procedure-property! (module-eval-closure m) 'system-module s))
2225 (define the-root-module (make-root-module))
2226 (define the-scm-module (make-scm-module))
2227 (set-module-public-interface! the-root-module the-scm-module)
2228 (set-module-name! the-root-module '(guile))
2229 (set-module-name! the-scm-module '(guile))
2230 (set-module-kind! the-scm-module 'interface)
2231 (set-system-module! the-root-module #t)
2232 (set-system-module! the-scm-module #t)
2237 ;; Now that we have a root module, even though modules aren't fully booted,
2238 ;; expand the definition of resolve-module.
2240 (define (resolve-module name . args)
2241 (if (equal? name '(guile))
2243 (error "unexpected module to resolve during module boot" name)))
2245 ;; Cheat. These bindings are needed by modules.c, but we don't want
2246 ;; to move their real definition here because that would be unnatural.
2248 (define process-define-module #f)
2249 (define process-use-modules #f)
2250 (define module-export! #f)
2251 (define default-duplicate-binding-procedures #f)
2253 ;; This boots the module system. All bindings needed by modules.c
2254 ;; must have been defined by now.
2256 (set-current-module the-root-module)
2261 ;; Now that modules are booted, give module-name its final definition.
2264 (let ((accessor (record-accessor module-type 'name)))
2267 (let ((name (list (gensym))))
2268 ;; Name MOD and bind it in the module root so that it's visible to
2269 ;; `resolve-module'. This is important as `psyntax' stores module
2270 ;; names and relies on being able to `resolve-module' them.
2271 (set-module-name! mod name)
2272 (nested-define-module! (resolve-module '() #f) name mod)
2275 (define (make-modules-in module name)
2276 (or (nested-ref-module module name)
2277 (let ((m (make-module 31)))
2278 (set-module-kind! m 'directory)
2279 (set-module-name! m (append (module-name module) name))
2280 (nested-define-module! module name m)
2283 (define (beautify-user-module! module)
2284 (let ((interface (module-public-interface module)))
2285 (if (or (not interface)
2286 (eq? interface module))
2287 (let ((interface (make-module 31)))
2288 (set-module-name! interface (module-name module))
2289 (set-module-version! interface (module-version module))
2290 (set-module-kind! interface 'interface)
2291 (set-module-public-interface! module interface))))
2292 (if (and (not (memq the-scm-module (module-uses module)))
2293 (not (eq? module the-root-module)))
2294 ;; Import the default set of bindings (from the SCM module) in MODULE.
2295 (module-use! module the-scm-module)))
2297 (define (version-matches? version-ref target)
2298 (define (any pred lst)
2299 (and (not (null? lst)) (or (pred (car lst)) (any pred (cdr lst)))))
2300 (define (every pred lst)
2301 (or (null? lst) (and (pred (car lst)) (every pred (cdr lst)))))
2302 (define (sub-versions-match? v-refs t)
2303 (define (sub-version-matches? v-ref t)
2304 (define (curried-sub-version-matches? v)
2305 (sub-version-matches? v t))
2306 (cond ((number? v-ref) (eqv? v-ref t))
2308 (let ((cv (car v-ref)))
2309 (cond ((eq? cv '>=) (>= t (cadr v-ref)))
2310 ((eq? cv '<=) (<= t (cadr v-ref)))
2312 (every curried-sub-version-matches? (cdr v-ref)))
2314 (any curried-sub-version-matches? (cdr v-ref)))
2315 ((eq? cv 'not) (not (sub-version-matches? (cadr v-ref) t)))
2316 (else (error "Incompatible sub-version reference" cv)))))
2317 (else (error "Incompatible sub-version reference" v-ref))))
2319 (and (not (null? t))
2320 (sub-version-matches? (car v-refs) (car t))
2321 (sub-versions-match? (cdr v-refs) (cdr t)))))
2322 (define (curried-version-matches? v)
2323 (version-matches? v target))
2324 (or (null? version-ref)
2325 (let ((cv (car version-ref)))
2326 (cond ((eq? cv 'and) (every curried-version-matches? (cdr version-ref)))
2327 ((eq? cv 'or) (any curried-version-matches? (cdr version-ref)))
2328 ((eq? cv 'not) (not (version-matches? (cadr version-ref) target)))
2329 (else (sub-versions-match? version-ref target))))))
2331 (define (find-versioned-module dir-hint name version-ref roots)
2332 (define (subdir-pair-less pair1 pair2)
2333 (define (numlist-less lst1 lst2)
2335 (and (not (null? lst1))
2336 (cond ((> (car lst1) (car lst2)) #t)
2337 ((< (car lst1) (car lst2)) #f)
2338 (else (numlist-less (cdr lst1) (cdr lst2)))))))
2339 (numlist-less (car pair1) (car pair2)))
2340 (define (match-version-and-file pair)
2341 (and (version-matches? version-ref (car pair))
2343 (filter (lambda (file)
2344 (let ((s (false-if-exception (stat file))))
2345 (and s (eq? (stat:type s) 'regular))))
2347 (string-append (cdr pair) "/" name ext))
2348 %load-extensions))))
2349 (and (not (null? filenames))
2350 (cons (car pair) (car filenames))))))
2352 (define (match-version-recursive root-pairs leaf-pairs)
2353 (define (filter-subdirs root-pairs ret)
2354 (define (filter-subdir root-pair dstrm subdir-pairs)
2355 (let ((entry (readdir dstrm)))
2356 (if (eof-object? entry)
2358 (let* ((subdir (string-append (cdr root-pair) "/" entry))
2359 (num (string->number entry))
2360 (num (and num (append (car root-pair) (list num)))))
2361 (if (and num (eq? (stat:type (stat subdir)) 'directory))
2363 root-pair dstrm (cons (cons num subdir) subdir-pairs))
2364 (filter-subdir root-pair dstrm subdir-pairs))))))
2366 (or (and (null? root-pairs) ret)
2367 (let* ((rp (car root-pairs))
2368 (dstrm (false-if-exception (opendir (cdr rp)))))
2370 (let ((subdir-pairs (filter-subdir rp dstrm '())))
2372 (filter-subdirs (cdr root-pairs)
2373 (or (and (null? subdir-pairs) ret)
2374 (append ret subdir-pairs))))
2375 (filter-subdirs (cdr root-pairs) ret)))))
2377 (or (and (null? root-pairs) leaf-pairs)
2378 (let ((matching-subdir-pairs (filter-subdirs root-pairs '())))
2379 (match-version-recursive
2380 matching-subdir-pairs
2381 (append leaf-pairs (filter pair? (map match-version-and-file
2382 matching-subdir-pairs)))))))
2383 (define (make-root-pair root)
2384 (cons '() (string-append root "/" dir-hint)))
2386 (let* ((root-pairs (map make-root-pair roots))
2387 (matches (if (null? version-ref)
2388 (filter pair? (map match-version-and-file root-pairs))
2390 (matches (append matches (match-version-recursive root-pairs '()))))
2391 (and (null? matches) (error "No matching modules found."))
2392 (cdar (sort matches subdir-pair-less))))
2394 (define (make-fresh-user-module)
2395 (let ((m (make-module)))
2396 (beautify-user-module! m)
2399 ;; NOTE: This binding is used in libguile/modules.c.
2401 (define resolve-module
2402 (let ((root (make-module)))
2403 (set-module-name! root '())
2404 ;; Define the-root-module as '(guile).
2405 (module-define-submodule! root 'guile the-root-module)
2407 (lambda* (name #:optional (autoload #t) (version #f))
2408 (let ((already (nested-ref-module root name)))
2411 (or (not autoload) (module-public-interface already)))
2412 ;; A hit, a palpable hit.
2414 (not (version-matches? version (module-version already))))
2415 (error "incompatible module version already loaded" name))
2418 ;; Try to autoload the module, and recurse.
2419 (try-load-module name version)
2420 (resolve-module name #f))
2422 ;; No module found (or if one was, it had no public interface), and
2423 ;; we're not autoloading. Here's the weird semantics: we ensure
2424 ;; there's an empty module.
2425 (or already (make-modules-in root name))))))))
2428 (define (try-load-module name version)
2429 (try-module-autoload name version))
2431 (define (purify-module! module)
2432 "Removes bindings in MODULE which are inherited from the (guile) module."
2433 (let ((use-list (module-uses module)))
2434 (if (and (pair? use-list)
2435 (eq? (car (last-pair use-list)) the-scm-module))
2436 (set-module-uses! module (reverse (cdr (reverse use-list)))))))
2438 ;; Return a module that is an interface to the module designated by
2441 ;; `resolve-interface' takes four keyword arguments:
2443 ;; #:select SELECTION
2445 ;; SELECTION is a list of binding-specs to be imported; A binding-spec
2446 ;; is either a symbol or a pair of symbols (ORIG . SEEN), where ORIG
2447 ;; is the name in the used module and SEEN is the name in the using
2448 ;; module. Note that SEEN is also passed through RENAMER, below. The
2449 ;; default is to select all bindings. If you specify no selection but
2450 ;; a renamer, only the bindings that already exist in the used module
2451 ;; are made available in the interface. Bindings that are added later
2452 ;; are not picked up.
2456 ;; BINDINGS is a list of bindings which should not be imported.
2460 ;; PREFIX is a symbol that will be appended to each exported name.
2461 ;; The default is to not perform any renaming.
2463 ;; #:renamer RENAMER
2465 ;; RENAMER is a procedure that takes a symbol and returns its new
2466 ;; name. The default is not perform any renaming.
2468 ;; Signal "no code for module" error if module name is not resolvable
2469 ;; or its public interface is not available. Signal "no binding"
2470 ;; error if selected binding does not exist in the used module.
2472 (define* (resolve-interface name #:key
2477 (symbol-prefix-proc prefix)
2480 (let* ((module (resolve-module name #t version))
2481 (public-i (and module (module-public-interface module))))
2482 (and (or (not module) (not public-i))
2483 (error "no code for module" name))
2484 (if (and (not select) (null? hide) (eq? renamer identity))
2486 (let ((selection (or select (module-map (lambda (sym var) sym)
2488 (custom-i (make-module 31)))
2489 (set-module-kind! custom-i 'custom-interface)
2490 (set-module-name! custom-i name)
2491 ;; XXX - should use a lazy binder so that changes to the
2492 ;; used module are picked up automatically.
2493 (for-each (lambda (bspec)
2494 (let* ((direct? (symbol? bspec))
2495 (orig (if direct? bspec (car bspec)))
2496 (seen (if direct? bspec (cdr bspec)))
2497 (var (or (module-local-variable public-i orig)
2498 (module-local-variable module orig)
2500 ;; fixme: format manually for now
2502 #f "no binding `~A' in module ~A"
2504 (if (memq orig hide)
2505 (set! hide (delq! orig hide))
2506 (module-add! custom-i
2510 ;; Check that we are not hiding bindings which don't exist
2511 (for-each (lambda (binding)
2512 (if (not (module-local-variable public-i binding))
2515 #f "no binding `~A' to hide in module ~A"
2520 (define (symbol-prefix-proc prefix)
2522 (symbol-append prefix symbol)))
2524 ;; This function is called from "modules.c". If you change it, be
2525 ;; sure to update "modules.c" as well.
2527 (define (process-define-module args)
2528 (let* ((module-id (car args))
2529 (module (resolve-module module-id #f))
2531 (unrecognized (lambda (arg)
2532 (error "unrecognized define-module argument" arg))))
2533 (beautify-user-module! module)
2534 (let loop ((kws kws)
2535 (reversed-interfaces '())
2542 (call-with-deferred-observers
2544 (module-use-interfaces! module (reverse reversed-interfaces))
2545 (module-export! module exports)
2546 (module-replace! module replacements)
2547 (module-re-export! module re-exports)
2548 (if (not (null? autoloads))
2549 (apply module-autoload! module autoloads))))
2551 ((#:use-module #:use-syntax)
2552 (or (pair? (cdr kws))
2555 ((equal? (caadr kws) '(ice-9 syncase))
2556 (issue-deprecation-warning
2557 "(ice-9 syncase) is deprecated. Support for syntax-case is now in Guile core.")
2565 (let* ((interface-args (cadr kws))
2566 (interface (apply resolve-interface interface-args)))
2567 (and (eq? (car kws) #:use-syntax)
2568 (or (symbol? (caar interface-args))
2569 (error "invalid module name for use-syntax"
2570 (car interface-args)))
2571 (set-module-transformer!
2573 (module-ref interface
2574 (car (last-pair (car interface-args)))
2577 (cons interface reversed-interfaces)
2583 (or (and (pair? (cdr kws)) (pair? (cddr kws)))
2590 (let ((name (cadr kws))
2591 (bindings (caddr kws)))
2592 (cons* name bindings autoloads))))
2594 (set-system-module! module #t)
2595 (loop (cdr kws) reversed-interfaces exports re-exports
2596 replacements autoloads))
2598 (purify-module! module)
2599 (loop (cdr kws) reversed-interfaces exports re-exports
2600 replacements autoloads))
2602 (or (pair? (cdr kws))
2604 (let ((version (cadr kws)))
2605 (set-module-version! module version)
2606 (set-module-version! (module-public-interface module) version))
2607 (loop (cddr kws) reversed-interfaces exports re-exports
2608 replacements autoloads))
2610 (if (not (pair? (cdr kws)))
2612 (set-module-duplicates-handlers!
2614 (lookup-duplicates-handlers (cadr kws)))
2615 (loop (cddr kws) reversed-interfaces exports re-exports
2616 replacements autoloads))
2617 ((#:export #:export-syntax)
2618 (or (pair? (cdr kws))
2622 (append (cadr kws) exports)
2626 ((#:re-export #:re-export-syntax)
2627 (or (pair? (cdr kws))
2632 (append (cadr kws) re-exports)
2635 ((#:replace #:replace-syntax)
2636 (or (pair? (cdr kws))
2642 (append (cadr kws) replacements)
2645 (unrecognized kws)))))
2646 (run-hook module-defined-hook module)
2649 ;; `module-defined-hook' is a hook that is run whenever a new module
2650 ;; is defined. Its members are called with one argument, the new
2652 (define module-defined-hook (make-hook 1))
2659 (define (make-autoload-interface module name bindings)
2660 (let ((b (lambda (a sym definep)
2661 (and (memq sym bindings)
2662 (let ((i (module-public-interface (resolve-module name))))
2664 (error "missing interface for module" name))
2665 (let ((autoload (memq a (module-uses module))))
2666 ;; Replace autoload-interface with actual interface if
2667 ;; that has not happened yet.
2668 (if (pair? autoload)
2669 (set-car! autoload i)))
2670 (module-local-variable i sym))))))
2671 (module-constructor (make-hash-table 0) '() b #f #f name 'autoload #f
2672 (make-hash-table 0) '() (make-weak-value-hash-table 31) #f
2673 (make-hash-table 0) #f #f)))
2675 (define (module-autoload! module . args)
2676 "Have @var{module} automatically load the module named @var{name} when one
2677 of the symbols listed in @var{bindings} is looked up. @var{args} should be a
2678 list of module-name/binding-list pairs, e.g., as in @code{(module-autoload!
2679 module '(ice-9 q) '(make-q q-length))}."
2680 (let loop ((args args))
2684 (error "invalid name+binding autoload list" args))
2686 (let ((name (car args))
2687 (bindings (cadr args)))
2688 (module-use! module (make-autoload-interface module
2690 (loop (cddr args)))))))
2695 ;;; {Autoloading modules}
2698 (define autoloads-in-progress '())
2700 ;; This function is called from "modules.c". If you change it, be
2701 ;; sure to update "modules.c" as well.
2703 (define* (try-module-autoload module-name #:optional version)
2704 (let* ((reverse-name (reverse module-name))
2705 (name (symbol->string (car reverse-name)))
2706 (dir-hint-module-name (reverse (cdr reverse-name)))
2707 (dir-hint (apply string-append
2709 (string-append (symbol->string elt) "/"))
2710 dir-hint-module-name))))
2711 (resolve-module dir-hint-module-name #f)
2712 (and (not (autoload-done-or-in-progress? dir-hint name))
2715 (lambda () (autoload-in-progress! dir-hint name))
2717 (with-fluids ((current-reader #f))
2718 (save-module-excursion
2721 (load (find-versioned-module
2722 dir-hint name version %load-path))
2723 (primitive-load-path (in-vicinity dir-hint name) #f))
2725 (lambda () (set-autoloaded! dir-hint name didit)))
2730 ;;; {Dynamic linking of modules}
2733 (define autoloads-done '((guile . guile)))
2735 (define (autoload-done-or-in-progress? p m)
2736 (let ((n (cons p m)))
2737 (->bool (or (member n autoloads-done)
2738 (member n autoloads-in-progress)))))
2740 (define (autoload-done! p m)
2741 (let ((n (cons p m)))
2742 (set! autoloads-in-progress
2743 (delete! n autoloads-in-progress))
2744 (or (member n autoloads-done)
2745 (set! autoloads-done (cons n autoloads-done)))))
2747 (define (autoload-in-progress! p m)
2748 (let ((n (cons p m)))
2749 (set! autoloads-done
2750 (delete! n autoloads-done))
2751 (set! autoloads-in-progress (cons n autoloads-in-progress))))
2753 (define (set-autoloaded! p m done?)
2755 (autoload-done! p m)
2756 (let ((n (cons p m)))
2757 (set! autoloads-done (delete! n autoloads-done))
2758 (set! autoloads-in-progress (delete! n autoloads-in-progress)))))
2762 ;;; {Run-time options}
2765 (defmacro define-option-interface (option-group)
2766 (let* ((option-name 'car)
2767 (option-value 'cadr)
2768 (option-documentation 'caddr)
2770 ;; Below follow the macros defining the run-time option interfaces.
2772 (make-options (lambda (interface)
2774 (cond ((null? args) (,interface))
2776 (,interface (car args)) (,interface))
2779 (display (,option-name option))
2780 (if (< (string-length
2781 (symbol->string (,option-name option)))
2785 (display (,option-value option))
2787 (display (,option-documentation option))
2789 (,interface #t)))))))
2791 (make-enable (lambda (interface)
2793 (,interface (append flags (,interface)))
2796 (make-disable (lambda (interface)
2798 (let ((options (,interface)))
2799 (for-each (lambda (flag)
2800 (set! options (delq! flag options)))
2802 (,interface options)
2804 (let* ((interface (car option-group))
2805 (options/enable/disable (cadr option-group)))
2807 (define ,(car options/enable/disable)
2808 ,(make-options interface))
2809 (define ,(cadr options/enable/disable)
2810 ,(make-enable interface))
2811 (define ,(caddr options/enable/disable)
2812 ,(make-disable interface))
2813 (defmacro ,(caaddr option-group) (opt val)
2814 `(,',(car options/enable/disable)
2815 (append (,',(car options/enable/disable))
2816 (list ',opt ,val))))))))
2818 (define-option-interface
2819 (eval-options-interface
2820 (eval-options eval-enable eval-disable)
2823 (define-option-interface
2824 (debug-options-interface
2825 (debug-options debug-enable debug-disable)
2828 (define-option-interface
2829 (evaluator-traps-interface
2830 (traps trap-enable trap-disable)
2833 (define-option-interface
2834 (read-options-interface
2835 (read-options read-enable read-disable)
2838 (define-option-interface
2839 (print-options-interface
2840 (print-options print-enable print-disable)
2848 (define (repl read evaler print)
2849 (let loop ((source (read (current-input-port))))
2850 (print (evaler source))
2851 (loop (read (current-input-port)))))
2853 ;; A provisional repl that acts like the SCM repl:
2855 (define scm-repl-silent #f)
2856 (define (assert-repl-silence v) (set! scm-repl-silent v))
2858 (define *unspecified* (if #f #f))
2859 (define (unspecified? v) (eq? v *unspecified*))
2861 (define scm-repl-print-unspecified #f)
2862 (define (assert-repl-print-unspecified v) (set! scm-repl-print-unspecified v))
2864 (define scm-repl-verbose #f)
2865 (define (assert-repl-verbosity v) (set! scm-repl-verbose v))
2867 (define scm-repl-prompt "guile> ")
2869 (define (set-repl-prompt! v) (set! scm-repl-prompt v))
2871 (define (default-pre-unwind-handler key . args)
2872 ;; Narrow by two more frames: this one, and the throw handler.
2874 (apply throw key args))
2877 (define (pre-unwind-handler-dispatch key . args)
2878 (apply default-pre-unwind-handler key args)))
2880 (define abort-hook (make-hook))
2882 ;; these definitions are used if running a script.
2883 ;; otherwise redefined in error-catching-loop.
2884 (define (set-batch-mode?! arg) #t)
2885 (define (batch-mode?) #t)
2887 (define (error-catching-loop thunk)
2890 (define (loop first)
2895 (call-with-unblocked-asyncs
2901 ;; This line is needed because mark
2902 ;; doesn't do closures quite right.
2903 ;; Unreferenced locals should be
2906 (let loop ((v (thunk)))
2910 (lambda (key . args)
2917 (apply throw 'switch-repl args))
2920 ;; This is one of the closures that require
2921 ;; (set! first #f) above
2924 (run-hook abort-hook)
2925 (force-output (current-output-port))
2926 (display "ABORT: " (current-error-port))
2927 (write args (current-error-port))
2928 (newline (current-error-port))
2932 (not has-shown-debugger-hint?)
2933 (not (memq 'backtrace
2934 (debug-options-interface)))
2935 (stack? (fluid-ref the-last-stack)))
2937 (newline (current-error-port))
2939 "Type \"(backtrace)\" to get more information or \"(debug)\" to enter the debugger.\n"
2940 (current-error-port))
2941 (set! has-shown-debugger-hint? #t)))
2942 (force-output (current-error-port)))
2944 (primitive-exit 1)))
2945 (set! stack-saved? #f)))
2948 ;; This is the other cons-leak closure...
2950 (cond ((= (length args) 4)
2951 (apply handle-system-error key args))
2953 (apply bad-throw key args)))))))
2955 default-pre-unwind-handler)))
2957 (if next (loop next) status)))
2958 (set! set-batch-mode?! (lambda (arg)
2960 (set! interactive #f)
2963 (error "sorry, not implemented")))))
2964 (set! batch-mode? (lambda () (not interactive)))
2965 (call-with-blocked-asyncs
2966 (lambda () (loop (lambda () #t))))))
2968 ;;(define the-last-stack (make-fluid)) Defined by scm_init_backtrace ()
2969 (define before-signal-stack (make-fluid))
2970 ;; FIXME: stack-saved? is broken in the presence of threads.
2971 (define stack-saved? #f)
2973 (define (save-stack . narrowing)
2974 (if (not stack-saved?)
2976 (let ((stacks (fluid-ref %stacks)))
2977 (fluid-set! the-last-stack
2978 ;; (make-stack obj inner outer inner outer ...)
2980 ;; In this case, cut away the make-stack frame, the
2981 ;; save-stack frame, and then narrow as specified by the
2982 ;; user, delimited by the nearest start-stack invocation,
2984 (apply make-stack #t
2986 (if (pair? stacks) (cdar stacks) 0)
2988 (set! stack-saved? #t))))
2990 (define before-error-hook (make-hook))
2991 (define after-error-hook (make-hook))
2992 (define before-backtrace-hook (make-hook))
2993 (define after-backtrace-hook (make-hook))
2995 (define has-shown-debugger-hint? #f)
2997 (define (handle-system-error key . args)
2998 (let ((cep (current-error-port)))
2999 (cond ((not (stack? (fluid-ref the-last-stack))))
3000 ((memq 'backtrace (debug-options-interface))
3001 (let ((highlights (if (or (eq? key 'wrong-type-arg)
3002 (eq? key 'out-of-range))
3005 (run-hook before-backtrace-hook)
3007 (display "Backtrace:\n")
3008 (display-backtrace (fluid-ref the-last-stack) cep
3011 (run-hook after-backtrace-hook))))
3012 (run-hook before-error-hook)
3013 (apply display-error (fluid-ref the-last-stack) cep args)
3014 (run-hook after-error-hook)
3016 (throw 'abort key)))
3018 (define (quit . args)
3019 (apply throw 'quit args))
3023 ;;(define has-shown-backtrace-hint? #f) Defined by scm_init_backtrace ()
3025 ;; Replaced by C code:
3026 ;;(define (backtrace)
3027 ;; (if (fluid-ref the-last-stack)
3030 ;; (display-backtrace (fluid-ref the-last-stack) (current-output-port))
3032 ;; (if (and (not has-shown-backtrace-hint?)
3033 ;; (not (memq 'backtrace (debug-options-interface))))
3036 ;;"Type \"(debug-enable 'backtrace)\" if you would like a backtrace
3037 ;;automatically if an error occurs in the future.\n")
3038 ;; (set! has-shown-backtrace-hint? #t))))
3039 ;; (display "No backtrace available.\n")))
3041 (define (error-catching-repl r e p)
3042 (error-catching-loop
3044 (call-with-values (lambda () (e (r)))
3045 (lambda the-values (for-each p the-values))))))
3047 (define (gc-run-time)
3048 (cdr (assq 'gc-time-taken (gc-stats))))
3050 (define before-read-hook (make-hook))
3051 (define after-read-hook (make-hook))
3052 (define before-eval-hook (make-hook 1))
3053 (define after-eval-hook (make-hook 1))
3054 (define before-print-hook (make-hook 1))
3055 (define after-print-hook (make-hook 1))
3057 ;;; The default repl-reader function. We may override this if we've
3058 ;;; the readline library.
3060 (lambda* (prompt #:optional (reader (fluid-ref current-reader)))
3061 (if (not (char-ready?))
3062 (display (if (string? prompt) prompt (prompt))))
3064 (run-hook before-read-hook)
3065 ((or reader read) (current-input-port))))
3067 (define (scm-style-repl)
3072 (repl-report-start-timing (lambda ()
3073 (set! start-gc-rt (gc-run-time))
3074 (set! start-rt (get-internal-run-time))))
3075 (repl-report (lambda ()
3077 (display (inexact->exact
3078 (* 1000 (/ (- (get-internal-run-time) start-rt)
3079 internal-time-units-per-second))))
3081 (display (inexact->exact
3082 (* 1000 (/ (- (gc-run-time) start-gc-rt)
3083 internal-time-units-per-second))))
3084 (display " msec in gc)\n")))
3086 (consume-trailing-whitespace
3088 (let ((ch (peek-char)))
3091 ((or (char=? ch #\space) (char=? ch #\tab))
3093 (consume-trailing-whitespace))
3094 ((char=? ch #\newline)
3098 (let ((prompt (cond ((string? scm-repl-prompt)
3100 ((thunk? scm-repl-prompt)
3102 (scm-repl-prompt "> ")
3104 (repl-reader prompt))))
3106 ;; As described in R4RS, the READ procedure updates the
3107 ;; port to point to the first character past the end of
3108 ;; the external representation of the object. This
3109 ;; means that it doesn't consume the newline typically
3110 ;; found after an expression. This means that, when
3111 ;; debugging Guile with GDB, GDB gets the newline, which
3112 ;; it often interprets as a "continue" command, making
3113 ;; breakpoints kind of useless. So, consume any
3114 ;; trailing newline here, as well as any whitespace
3116 ;; But not if EOF, for control-D.
3117 (if (not (eof-object? val))
3118 (consume-trailing-whitespace))
3119 (run-hook after-read-hook)
3120 (if (eof-object? val)
3122 (repl-report-start-timing)
3123 (if scm-repl-verbose
3126 (display ";;; EOF -- quitting")
3131 (-eval (lambda (sourc)
3132 (repl-report-start-timing)
3133 (run-hook before-eval-hook sourc)
3134 (let ((val (start-stack 'repl-stack
3135 ;; If you change this procedure
3136 ;; (primitive-eval), please also
3137 ;; modify the repl-stack case in
3138 ;; save-stack so that stack cutting
3139 ;; continues to work.
3140 (primitive-eval sourc))))
3141 (run-hook after-eval-hook sourc)
3145 (-print (let ((maybe-print (lambda (result)
3146 (if (or scm-repl-print-unspecified
3147 (not (unspecified? result)))
3152 (if (not scm-repl-silent)
3154 (run-hook before-print-hook result)
3155 (maybe-print result)
3156 (run-hook after-print-hook result)
3157 (if scm-repl-verbose
3161 (-quit (lambda (args)
3162 (if scm-repl-verbose
3164 (display ";;; QUIT executed, repl exitting")
3169 (let ((status (error-catching-repl -read
3177 ;;; {IOTA functions: generating lists of numbers}
3181 (let loop ((count (1- n)) (result '()))
3182 (if (< count 0) result
3183 (loop (1- count) (cons count result)))))
3189 ;;; Similar to `begin' but returns a list of the results of all constituent
3190 ;;; forms instead of the result of the last form.
3191 ;;; (The definition relies on the current left-to-right
3192 ;;; order of evaluation of operands in applications.)
3195 (defmacro collect forms
3202 ;;; with `continue' and `break'.
3205 ;; The inner `do' loop avoids re-establishing a catch every iteration,
3206 ;; that's only necessary if continue is actually used. A new key is
3207 ;; generated every time, so break and continue apply to their originating
3208 ;; `while' even when recursing.
3210 ;; FIXME: This macro is unintentionally unhygienic with respect to let,
3211 ;; make-symbol, do, throw, catch, lambda, and not.
3213 (define-macro (while cond . body)
3214 (let ((keyvar (make-symbol "while-keyvar")))
3215 `(let ((,keyvar (make-symbol "while-key")))
3219 (let ((break (lambda () (throw ,keyvar #t)))
3220 (continue (lambda () (throw ,keyvar #f))))
3231 ;;; {Module System Macros}
3234 ;; Return a list of expressions that evaluate to the appropriate
3235 ;; arguments for resolve-interface according to SPEC.
3239 (if (memq 'prefix (read-options))
3240 (error "boot-9 must be compiled with #:kw, not :kw")))
3242 (define (keyword-like-symbol->keyword sym)
3243 (symbol->keyword (string->symbol (substring (symbol->string sym) 1))))
3245 ;; FIXME: we really need to clean up the guts of the module system.
3246 ;; We can compile to something better than process-define-module.
3247 (define-syntax define-module
3249 (define (keyword-like? stx)
3250 (let ((dat (syntax->datum stx)))
3252 (eqv? (string-ref (symbol->string dat) 0) #\:))))
3253 (define (->keyword sym)
3254 (symbol->keyword (string->symbol (substring (symbol->string sym) 1))))
3256 (define (quotify-iface args)
3257 (let loop ((in args) (out '()))
3260 ;; The user wanted #:foo, but wrote :foo. Fix it.
3261 ((sym . in) (keyword-like? #'sym)
3262 (loop #`(#,(->keyword (syntax->datum #'sym)) . in) out))
3263 ((kw . in) (not (keyword? (syntax->datum #'kw)))
3264 (syntax-violation 'define-module "expected keyword arg" x #'kw))
3265 ((#:renamer renamer . in)
3266 (loop #'in (cons* #'renamer #:renamer out)))
3268 (loop #'in (cons* #''val #'kw out))))))
3270 (define (quotify args)
3271 ;; Just quote everything except #:use-module and #:use-syntax. We
3272 ;; need to know about all arguments regardless since we want to turn
3273 ;; symbols that look like keywords into real keywords, and the
3274 ;; keyword args in a define-module form are not regular
3275 ;; (i.e. no-backtrace doesn't take a value).
3276 (let loop ((in args) (out '()))
3279 ;; The user wanted #:foo, but wrote :foo. Fix it.
3280 ((sym . in) (keyword-like? #'sym)
3281 (loop #`(#,(->keyword (syntax->datum #'sym)) . in) out))
3282 ((kw . in) (not (keyword? (syntax->datum #'kw)))
3283 (syntax-violation 'define-module "expected keyword arg" x #'kw))
3284 ((#:no-backtrace . in)
3285 (loop #'in (cons #:no-backtrace out)))
3287 (loop #'in (cons #:pure out)))
3289 (syntax-violation 'define-module "keyword arg without value" x #'kw))
3290 ((use-module (name name* ...) . in)
3291 (and (memq (syntax->datum #'use-module) '(#:use-module #:use-syntax))
3292 (and-map symbol? (syntax->datum #'(name name* ...))))
3294 (cons* #''((name name* ...))
3297 ((use-module ((name name* ...) arg ...) . in)
3298 (and (memq (syntax->datum #'use-module) '(#:use-module #:use-syntax))
3299 (and-map symbol? (syntax->datum #'(name name* ...))))
3301 (cons* #`(list '(name name* ...) #,@(quotify-iface #'(arg ...)))
3304 ((#:autoload name bindings . in)
3305 (loop #'in (cons* #''bindings #''name #:autoload out)))
3307 (loop #'in (cons* #''val #'kw out))))))
3310 ((_ (name name* ...) arg ...)
3311 (with-syntax (((quoted-arg ...) (quotify #'(arg ...))))
3312 #'(eval-when (eval load compile expand)
3313 (let ((m (process-define-module
3314 (list '(name name* ...) quoted-arg ...))))
3315 (set-current-module m)
3318 ;; The guts of the use-modules macro. Add the interfaces of the named
3319 ;; modules to the use-list of the current module, in order.
3321 ;; This function is called by "modules.c". If you change it, be sure
3322 ;; to change scm_c_use_module as well.
3324 (define (process-use-modules module-interface-args)
3325 (let ((interfaces (map (lambda (mif-args)
3326 (or (apply resolve-interface mif-args)
3327 (error "no such module" mif-args)))
3328 module-interface-args)))
3329 (call-with-deferred-observers
3331 (module-use-interfaces! (current-module) interfaces)))))
3333 (define-syntax use-modules
3335 (define (keyword-like? stx)
3336 (let ((dat (syntax->datum stx)))
3338 (eqv? (string-ref (symbol->string dat) 0) #\:))))
3339 (define (->keyword sym)
3340 (symbol->keyword (string->symbol (substring (symbol->string sym) 1))))
3342 (define (quotify-iface args)
3343 (let loop ((in args) (out '()))
3346 ;; The user wanted #:foo, but wrote :foo. Fix it.
3347 ((sym . in) (keyword-like? #'sym)
3348 (loop #`(#,(->keyword (syntax->datum #'sym)) . in) out))
3349 ((kw . in) (not (keyword? (syntax->datum #'kw)))
3350 (syntax-violation 'define-module "expected keyword arg" x #'kw))
3351 ((#:renamer renamer . in)
3352 (loop #'in (cons* #'renamer #:renamer out)))
3354 (loop #'in (cons* #''val #'kw out))))))
3356 (define (quotify specs)
3357 (let lp ((in specs) (out '()))
3360 (((name name* ...) . in)
3361 (and-map symbol? (syntax->datum #'(name name* ...)))
3362 (lp #'in (cons #''((name name* ...)) out)))
3363 ((((name name* ...) arg ...) . in)
3364 (and-map symbol? (syntax->datum #'(name name* ...)))
3365 (with-syntax (((quoted-arg ...) (quotify-iface #'(arg ...))))
3366 (lp #'in (cons #`(list '(name name* ...) quoted-arg ...)
3371 (with-syntax (((quoted-args ...) (quotify #'(spec ...))))
3372 #'(eval-when (eval load compile expand)
3373 (process-use-modules (list quoted-args ...))
3376 (define-syntax use-syntax
3380 (eval-when (eval load compile expand)
3381 (issue-deprecation-warning
3382 "`use-syntax' is deprecated. Please contact guile-devel for more info."))
3383 (use-modules spec ...)))))
3385 (include-from-path "ice-9/r6rs-libraries")
3387 (define-syntax define-private
3392 (define-syntax define-public
3394 ((_ (name . args) . body)
3395 (define-public name (lambda args . body)))
3401 (define-syntax defmacro-public
3403 ((_ name args . body)
3405 (defmacro name args . body)
3406 (export-syntax name)))))
3408 ;; And now for the most important macro.
3411 ((_ formals body ...)
3412 (lambda formals body ...))))
3415 ;; Export a local variable
3417 ;; This function is called from "modules.c". If you change it, be
3418 ;; sure to update "modules.c" as well.
3420 (define (module-export! m names)
3421 (let ((public-i (module-public-interface m)))
3422 (for-each (lambda (name)
3423 (let* ((internal-name (if (pair? name) (car name) name))
3424 (external-name (if (pair? name) (cdr name) name))
3425 (var (module-ensure-local-variable! m internal-name)))
3426 (module-add! public-i external-name var)))
3429 (define (module-replace! m names)
3430 (let ((public-i (module-public-interface m)))
3431 (for-each (lambda (name)
3432 (let* ((internal-name (if (pair? name) (car name) name))
3433 (external-name (if (pair? name) (cdr name) name))
3434 (var (module-ensure-local-variable! m internal-name)))
3435 (set-object-property! var 'replace #t)
3436 (module-add! public-i external-name var)))
3439 ;; Export all local variables from a module
3441 (define (module-export-all! mod)
3442 (define (fresh-interface!)
3443 (let ((iface (make-module)))
3444 (set-module-name! iface (module-name mod))
3445 ;; for guile 2: (set-module-version! iface (module-version mod))
3446 (set-module-kind! iface 'interface)
3447 (set-module-public-interface! mod iface)
3449 (let ((iface (or (module-public-interface mod)
3450 (fresh-interface!))))
3451 (set-module-obarray! iface (module-obarray mod))))
3453 ;; Re-export a imported variable
3455 (define (module-re-export! m names)
3456 (let ((public-i (module-public-interface m)))
3457 (for-each (lambda (name)
3458 (let* ((internal-name (if (pair? name) (car name) name))
3459 (external-name (if (pair? name) (cdr name) name))
3460 (var (module-variable m internal-name)))
3462 (error "Undefined variable:" internal-name))
3463 ((eq? var (module-local-variable m internal-name))
3464 (error "re-exporting local variable:" internal-name))
3466 (module-add! public-i external-name var)))))
3469 (define-syntax export
3472 (eval-when (eval load compile expand)
3473 (call-with-deferred-observers
3475 (module-export! (current-module) '(name ...))))))))
3477 (define-syntax re-export
3480 (eval-when (eval load compile expand)
3481 (call-with-deferred-observers
3483 (module-re-export! (current-module) '(name ...))))))))
3485 (define-syntax export-syntax
3488 (export name ...))))
3490 (define-syntax re-export-syntax
3493 (re-export name ...))))
3495 (define load load-module)
3502 (define make-mutable-parameter
3503 (let ((make (lambda (fluid converter)
3507 (fluid-set! fluid (converter (car args))))))))
3508 (lambda (init . converter)
3509 (let ((fluid (make-fluid))
3510 (converter (if (null? converter)
3513 (fluid-set! fluid (converter init))
3514 (make fluid converter)))))
3518 ;;; {Handling of duplicate imported bindings}
3521 ;; Duplicate handlers take the following arguments:
3523 ;; module importing module
3524 ;; name conflicting name
3525 ;; int1 old interface where name occurs
3526 ;; val1 value of binding in old interface
3527 ;; int2 new interface where name occurs
3528 ;; val2 value of binding in new interface
3529 ;; var previous resolution or #f
3530 ;; val value of previous resolution
3532 ;; A duplicate handler can take three alternative actions:
3534 ;; 1. return #f => leave responsibility to next handler
3535 ;; 2. exit with an error
3536 ;; 3. return a variable resolving the conflict
3539 (define duplicate-handlers
3540 (let ((m (make-module 7)))
3542 (define (check module name int1 val1 int2 val2 var val)
3543 (scm-error 'misc-error
3545 "~A: `~A' imported from both ~A and ~A"
3546 (list (module-name module)
3552 (define (warn module name int1 val1 int2 val2 var val)
3553 (format (current-error-port)
3554 "WARNING: ~A: `~A' imported from both ~A and ~A\n"
3555 (module-name module)
3561 (define (replace module name int1 val1 int2 val2 var val)
3562 (let ((old (or (and var (object-property var 'replace) var)
3563 (module-variable int1 name)))
3564 (new (module-variable int2 name)))
3565 (if (object-property old 'replace)
3566 (and (or (eq? old new)
3567 (not (object-property new 'replace)))
3569 (and (object-property new 'replace)
3572 (define (warn-override-core module name int1 val1 int2 val2 var val)
3573 (and (eq? int1 the-scm-module)
3575 (format (current-error-port)
3576 "WARNING: ~A: imported module ~A overrides core binding `~A'\n"
3577 (module-name module)
3580 (module-local-variable int2 name))))
3582 (define (first module name int1 val1 int2 val2 var val)
3583 (or var (module-local-variable int1 name)))
3585 (define (last module name int1 val1 int2 val2 var val)
3586 (module-local-variable int2 name))
3588 (define (noop module name int1 val1 int2 val2 var val)
3591 (set-module-name! m 'duplicate-handlers)
3592 (set-module-kind! m 'interface)
3593 (module-define! m 'check check)
3594 (module-define! m 'warn warn)
3595 (module-define! m 'replace replace)
3596 (module-define! m 'warn-override-core warn-override-core)
3597 (module-define! m 'first first)
3598 (module-define! m 'last last)
3599 (module-define! m 'merge-generics noop)
3600 (module-define! m 'merge-accessors noop)
3603 (define (lookup-duplicates-handlers handler-names)
3605 (map (lambda (handler-name)
3606 (or (module-symbol-local-binding
3607 duplicate-handlers handler-name #f)
3608 (error "invalid duplicate handler name:"
3610 (if (list? handler-names)
3612 (list handler-names)))))
3614 (define default-duplicate-binding-procedures
3615 (make-mutable-parameter #f))
3617 (define default-duplicate-binding-handler
3618 (make-mutable-parameter '(replace warn-override-core warn last)
3619 (lambda (handler-names)
3620 (default-duplicate-binding-procedures
3621 (lookup-duplicates-handlers handler-names))
3626 ;;; {`cond-expand' for SRFI-0 support.}
3628 ;;; This syntactic form expands into different commands or
3629 ;;; definitions, depending on the features provided by the Scheme
3635 ;;; --> (cond-expand <cond-expand-clause>+)
3636 ;;; | (cond-expand <cond-expand-clause>* (else <command-or-definition>))
3637 ;;; <cond-expand-clause>
3638 ;;; --> (<feature-requirement> <command-or-definition>*)
3639 ;;; <feature-requirement>
3640 ;;; --> <feature-identifier>
3641 ;;; | (and <feature-requirement>*)
3642 ;;; | (or <feature-requirement>*)
3643 ;;; | (not <feature-requirement>)
3644 ;;; <feature-identifier>
3645 ;;; --> <a symbol which is the name or alias of a SRFI>
3647 ;;; Additionally, this implementation provides the
3648 ;;; <feature-identifier>s `guile' and `r5rs', so that programs can
3649 ;;; determine the implementation type and the supported standard.
3651 ;;; Currently, the following feature identifiers are supported:
3653 ;;; guile r5rs srfi-0 srfi-4 srfi-6 srfi-13 srfi-14 srfi-55 srfi-61
3655 ;;; Remember to update the features list when adding more SRFIs.
3658 (define %cond-expand-features
3659 ;; Adjust the above comment when changing this.
3663 srfi-0 ;; cond-expand itself
3664 srfi-4 ;; homogenous numeric vectors
3665 srfi-6 ;; open-input-string etc, in the guile core
3666 srfi-13 ;; string library
3667 srfi-14 ;; character sets
3668 srfi-55 ;; require-extension
3669 srfi-61 ;; general cond clause
3672 ;; This table maps module public interfaces to the list of features.
3674 (define %cond-expand-table (make-hash-table 31))
3676 ;; Add one or more features to the `cond-expand' feature list of the
3679 (define (cond-expand-provide module features)
3680 (let ((mod (module-public-interface module)))
3682 (hashq-set! %cond-expand-table mod
3683 (append (hashq-ref %cond-expand-table mod '())
3686 (define-macro (cond-expand . clauses)
3687 (let ((syntax-error (lambda (cl)
3688 (error "invalid clause in `cond-expand'" cl))))
3694 (or (memq clause %cond-expand-features)
3695 (let lp ((uses (module-uses (current-module))))
3698 (hashq-ref %cond-expand-table
3704 ((eq? 'and (car clause))
3705 (let lp ((l (cdr clause)))
3709 (and (test-clause (car l)) (lp (cdr l))))
3711 (syntax-error clause)))))
3712 ((eq? 'or (car clause))
3713 (let lp ((l (cdr clause)))
3717 (or (test-clause (car l)) (lp (cdr l))))
3719 (syntax-error clause)))))
3720 ((eq? 'not (car clause))
3721 (cond ((not (pair? (cdr clause)))
3722 (syntax-error clause))
3723 ((pair? (cddr clause))
3724 ((syntax-error clause))))
3725 (not (test-clause (cadr clause))))
3727 (syntax-error clause))))
3729 (syntax-error clause))))))
3730 (let lp ((c clauses))
3733 (error "Unfulfilled `cond-expand'"))
3736 ((not (pair? (car c)))
3737 (syntax-error (car c)))
3738 ((test-clause (caar c))
3739 `(begin ,@(cdar c)))
3740 ((eq? (caar c) 'else)
3743 `(begin ,@(cdar c)))
3747 ;; This procedure gets called from the startup code with a list of
3748 ;; numbers, which are the numbers of the SRFIs to be loaded on startup.
3750 (define (use-srfis srfis)
3751 (process-use-modules
3753 (list (list 'srfi (string->symbol
3754 (string-append "srfi-" (number->string num))))))
3759 ;;; srfi-55: require-extension
3762 (define-macro (require-extension extension-spec)
3763 ;; This macro only handles the srfi extension, which, at present, is
3764 ;; the only one defined by the standard.
3765 (if (not (pair? extension-spec))
3766 (scm-error 'wrong-type-arg "require-extension"
3767 "Not an extension: ~S" (list extension-spec) #f))
3768 (let ((extension (car extension-spec))
3769 (extension-args (cdr extension-spec)))
3772 (let ((use-list '()))
3775 (if (not (integer? i))
3776 (scm-error 'wrong-type-arg "require-extension"
3777 "Invalid srfi name: ~S" (list i) #f))
3778 (let ((srfi-sym (string->symbol
3779 (string-append "srfi-" (number->string i)))))
3780 (if (not (memq srfi-sym %cond-expand-features))
3781 (set! use-list (cons `(use-modules (srfi ,srfi-sym))
3784 (if (pair? use-list)
3785 ;; i.e. (begin (use-modules x) (use-modules y) (use-modules z))
3786 `(begin ,@(reverse! use-list)))))
3789 'wrong-type-arg "require-extension"
3790 "Not a recognized extension type: ~S" (list extension) #f)))))
3794 ;;; {Load emacs interface support if emacs option is given.}
3797 (define (named-module-use! user usee)
3798 (module-use! (resolve-module user) (resolve-interface usee)))
3800 (define (load-emacs-interface)
3801 (and (provided? 'debug-extensions)
3802 (debug-enable 'backtrace))
3803 (named-module-use! '(guile-user) '(ice-9 emacs)))
3807 (define using-readline?
3808 (let ((using-readline? (make-fluid)))
3809 (make-procedure-with-setter
3810 (lambda () (fluid-ref using-readline?))
3811 (lambda (v) (fluid-set! using-readline? v)))))
3814 (let ((guile-user-module (resolve-module '(guile-user))))
3816 ;; Load emacs interface support if emacs option is given.
3817 (if (and (module-defined? guile-user-module 'use-emacs-interface)
3818 (module-ref guile-user-module 'use-emacs-interface))
3819 (load-emacs-interface))
3821 ;; Use some convenient modules (in reverse order)
3823 (set-current-module guile-user-module)
3824 (process-use-modules
3829 (if (provided? 'regex)
3832 (if (provided? 'threads)
3833 '(((ice-9 threads)))
3835 ;; load debugger on demand
3836 (module-autoload! guile-user-module '(system vm debug) '(debug))
3838 ;; Note: SIGFPE, SIGSEGV and SIGBUS are actually "query-only" (see
3839 ;; scmsigs.c scm_sigaction_for_thread), so the handlers setup here have
3841 (let ((old-handlers #f)
3842 (start-repl (module-ref (resolve-interface '(system repl repl))
3844 (signals (if (provided? 'posix)
3845 `((,SIGINT . "User interrupt")
3846 (,SIGFPE . "Arithmetic error")
3848 . "Bad memory access (Segmentation violation)"))
3850 ;; no SIGBUS on mingw
3851 (if (defined? 'SIGBUS)
3852 (set! signals (acons SIGBUS "Bad memory access (bus error)"
3859 (let ((make-handler (lambda (msg)
3861 ;; Make a backup copy of the stack
3862 (fluid-set! before-signal-stack
3863 (fluid-ref the-last-stack))
3871 (map (lambda (sig-msg)
3872 (sigaction (car sig-msg)
3873 (make-handler (cdr sig-msg))))
3876 ;; the protected thunk.
3878 (let ((status (start-repl 'scheme)))
3879 (run-hook exit-hook)
3884 (map (lambda (sig-msg old-handler)
3885 (if (not (car old-handler))
3886 ;; restore original C handler.
3887 (sigaction (car sig-msg) #f)
3888 ;; restore Scheme handler, SIG_IGN or SIG_DFL.
3889 (sigaction (car sig-msg)
3891 (cdr old-handler))))
3892 signals old-handlers))))))
3894 ;;; This hook is run at the very end of an interactive session.
3896 (define exit-hook (make-hook))
3900 ;;; {Deprecated stuff}
3904 (module-use! the-scm-module (resolve-interface '(ice-9 deprecated))))
3908 ;;; Place the user in the guile-user module.
3911 ;;; FIXME: annotate ?
3912 ;; (define (syncase exp)
3913 ;; (with-fluids ((expansion-eval-closure
3914 ;; (module-eval-closure (current-module))))
3915 ;; (deannotate/source-properties (macroexpand (annotate exp)))))
3918 (module-use! the-scm-module (resolve-interface '(srfi srfi-4)))
3920 (define-module (guile-user)
3921 #:autoload (system base compile) (compile))
3923 ;; Remain in the `(guile)' module at compilation-time so that the
3924 ;; `-Wunused-toplevel' warning works as expected.
3925 (eval-when (compile) (set-current-module the-root-module))
3927 ;;; boot-9.scm ends here