1 ;;; -*- mode: scheme; coding: utf-8; -*-
3 ;;;; Copyright (C) 1995,1996,1997,1998,1999,2000,2001,2002,2003,2004,2005,2006,2007,2008,2009,2010
4 ;;;; Free Software Foundation, Inc.
6 ;;;; This library is free software; you can redistribute it and/or
7 ;;;; modify it under the terms of the GNU Lesser General Public
8 ;;;; License as published by the Free Software Foundation; either
9 ;;;; version 3 of the License, or (at your option) any later version.
11 ;;;; This library is distributed in the hope that it will be useful,
12 ;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
13 ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 ;;;; Lesser General Public License for more details.
16 ;;;; You should have received a copy of the GNU Lesser General Public
17 ;;;; License along with this library; if not, write to the Free Software
18 ;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
25 ;;; This file is the first thing loaded into Guile. It adds many mundane
26 ;;; definitions and a few that are interesting.
28 ;;; The module system (hence the hierarchical namespace) are defined in this
36 ;; Before compiling, make sure any symbols are resolved in the (guile)
37 ;; module, the primary location of those symbols, rather than in
38 ;; (guile-user), the default module that we compile in.
41 (set-current-module (resolve-module '(guile))))
48 ;; Define delimited continuation operators, and implement catch and throw in
51 (define make-prompt-tag
52 (lambda* (#:optional (stem "prompt"))
55 (define default-prompt-tag
56 ;; not sure if we should expose this to the user as a fluid
57 (let ((%default-prompt-tag (make-prompt-tag)))
59 %default-prompt-tag)))
61 (define (call-with-prompt tag thunk handler)
62 (@prompt tag (thunk) handler))
63 (define (abort-to-prompt tag . args)
67 ;; Define catch and with-throw-handler, using some common helper routines and a
68 ;; shared fluid. Hide the helpers in a lexical contour.
71 ;; Ideally we'd like to be able to give these default values for all threads,
72 ;; even threads not created by Guile; but alack, that does not currently seem
73 ;; possible. So wrap the getters in thunks.
74 (define %running-exception-handlers (make-fluid))
75 (define %exception-handler (make-fluid))
77 (define (running-exception-handlers)
78 (or (fluid-ref %running-exception-handlers)
80 (fluid-set! %running-exception-handlers '())
82 (define (exception-handler)
83 (or (fluid-ref %exception-handler)
85 (fluid-set! %exception-handler default-exception-handler)
86 default-exception-handler)))
88 (define (default-exception-handler k . args)
92 ((not (pair? args)) 0)
93 ((integer? (car args)) (car args))
97 (format (current-error-port) "guile: uncaught throw to ~a: ~a\n" k args)
100 (define (default-throw-handler prompt-tag catch-k)
101 (let ((prev (exception-handler)))
102 (lambda (thrown-k . args)
103 (if (or (eq? thrown-k catch-k) (eqv? catch-k #t))
104 (apply abort-to-prompt prompt-tag thrown-k args)
105 (apply prev thrown-k args)))))
107 (define (custom-throw-handler prompt-tag catch-k pre)
108 (let ((prev (exception-handler)))
109 (lambda (thrown-k . args)
110 (if (or (eq? thrown-k catch-k) (eqv? catch-k #t))
111 (let ((running (running-exception-handlers)))
112 (with-fluids ((%running-exception-handlers (cons pre running)))
113 (if (not (memq pre running))
114 (apply pre thrown-k args))
117 (apply abort-to-prompt prompt-tag thrown-k args)
118 (apply prev thrown-k args))))
119 (apply prev thrown-k args)))))
122 (lambda* (k thunk handler #:optional pre-unwind-handler)
123 "Invoke @var{thunk} in the dynamic context of @var{handler} for
124 exceptions matching @var{key}. If thunk throws to the symbol
125 @var{key}, then @var{handler} is invoked this way:
127 (handler key args ...)
130 @var{key} is a symbol or @code{#t}.
132 @var{thunk} takes no arguments. If @var{thunk} returns
133 normally, that is the return value of @code{catch}.
135 Handler is invoked outside the scope of its own @code{catch}.
136 If @var{handler} again throws to the same key, a new handler
137 from further up the call chain is invoked.
139 If the key is @code{#t}, then a throw to @emph{any} symbol will
140 match this call to @code{catch}.
142 If a @var{pre-unwind-handler} is given and @var{thunk} throws
143 an exception that matches @var{key}, Guile calls the
144 @var{pre-unwind-handler} before unwinding the dynamic state and
145 invoking the main @var{handler}. @var{pre-unwind-handler} should
146 be a procedure with the same signature as @var{handler}, that
147 is @code{(lambda (key . args))}. It is typically used to save
148 the stack at the point where the exception occurred, but can also
149 query other parts of the dynamic state at that point, such as
152 A @var{pre-unwind-handler} can exit either normally or non-locally.
153 If it exits normally, Guile unwinds the stack and dynamic context
154 and then calls the normal (third argument) handler. If it exits
155 non-locally, that exit determines the continuation."
156 (if (not (or (symbol? k) (eqv? k #t)))
157 (scm-error "catch" 'wrong-type-arg
158 "Wrong type argument in position ~a: ~a"
159 (list 1 k) (list k)))
160 (let ((tag (make-prompt-tag "catch")))
166 (if pre-unwind-handler
167 (custom-throw-handler tag k pre-unwind-handler)
168 (default-throw-handler tag k))))
170 (lambda (cont k . args)
171 (apply handler k args))))))
173 (define! 'with-throw-handler
174 (lambda (k thunk pre-unwind-handler)
175 "Add @var{handler} to the dynamic context as a throw handler
176 for key @var{key}, then invoke @var{thunk}."
177 (if (not (or (symbol? k) (eqv? k #t)))
178 (scm-error "with-throw-handler" 'wrong-type-arg
179 "Wrong type argument in position ~a: ~a"
180 (list 1 k) (list k)))
181 (with-fluids ((%exception-handler
182 (custom-throw-handler #f k pre-unwind-handler)))
187 "Invoke the catch form matching @var{key}, passing @var{args} to the
190 @var{key} is a symbol. It will match catches of the same symbol or of @code{#t}.
192 If there is no handler at all, Guile prints an error and then exits."
193 (if (not (symbol? key))
194 ((exception-handler) 'wrong-type-arg "throw"
195 "Wrong type argument in position ~a: ~a" (list 1 key) (list key))
196 (apply (exception-handler) key args)))))
201 ;;; {R4RS compliance}
204 (primitive-load-path "ice-9/r4rs")
208 ;;; {Simple Debugging Tools}
211 ;; peek takes any number of arguments, writes them to the
212 ;; current ouput port, and returns the last argument.
213 ;; It is handy to wrap around an expression to look at
214 ;; a value each time is evaluated, e.g.:
216 ;; (+ 10 (troublesome-fn))
217 ;; => (+ 10 (pk 'troublesome-fn-returned (troublesome-fn)))
220 (define (peek . stuff)
225 (car (last-pair stuff)))
230 (define (warn . stuff)
231 (with-output-to-port (current-error-port)
234 (display ";;; WARNING ")
237 (car (last-pair stuff)))))
244 (define (provide sym)
245 (if (not (memq sym *features*))
246 (set! *features* (cons sym *features*))))
248 ;; Return #t iff FEATURE is available to this Guile interpreter. In SLIB,
249 ;; provided? also checks to see if the module is available. We should do that
252 (define (provided? feature)
253 (and (memq feature *features*) #t))
257 ;;; {and-map and or-map}
259 ;;; (and-map fn lst) is like (and (fn (car lst)) (fn (cadr lst)) (fn...) ...)
260 ;;; (or-map fn lst) is like (or (fn (car lst)) (fn (cadr lst)) (fn...) ...)
265 ;; Apply f to successive elements of l until exhaustion or f returns #f.
266 ;; If returning early, return #f. Otherwise, return the last value returned
267 ;; by f. If f has never been called because l is empty, return #t.
269 (define (and-map f lst)
270 (let loop ((result #t)
275 (loop (f (car l)) (cdr l))))))
279 ;; Apply f to successive elements of l until exhaustion or while f returns #f.
280 ;; If returning early, return the return value of f.
282 (define (or-map f lst)
283 (let loop ((result #f)
287 (loop (f (car l)) (cdr l))))))
291 ;; let format alias simple-format until the more complete version is loaded
293 (define format simple-format)
295 ;; this is scheme wrapping the C code so the final pred call is a tail call,
298 (lambda* (char_pred s #:optional (start 0) (end (string-length s)))
299 (if (and (procedure? char_pred)
301 (<= end (string-length s))) ;; let c-code handle range error
302 (or (string-any-c-code char_pred s start (1- end))
303 (char_pred (string-ref s (1- end))))
304 (string-any-c-code char_pred s start end))))
306 ;; this is scheme wrapping the C code so the final pred call is a tail call,
309 (lambda* (char_pred s #:optional (start 0) (end (string-length s)))
310 (if (and (procedure? char_pred)
312 (<= end (string-length s))) ;; let c-code handle range error
313 (and (string-every-c-code char_pred s start (1- end))
314 (char_pred (string-ref s (1- end))))
315 (string-every-c-code char_pred s start end))))
317 ;; A variant of string-fill! that we keep for compatability
319 (define (substring-fill! str start end fill)
320 (string-fill! str fill start end))
324 ;; Define a minimal stub of the module API for psyntax, before modules
326 (define (module-name x)
328 (define (module-define! module sym val)
329 (let ((v (hashq-ref (%get-pre-modules-obarray) sym)))
331 (variable-set! v val)
332 (hashq-set! (%get-pre-modules-obarray) sym
333 (make-variable val)))))
334 (define (module-ref module sym)
335 (let ((v (module-variable module sym)))
336 (if v (variable-ref v) (error "badness!" (pk module) (pk sym)))))
337 (define (resolve-module . args)
340 ;; API provided by psyntax
341 (define syntax-violation #f)
342 (define datum->syntax #f)
343 (define syntax->datum #f)
344 (define syntax-source #f)
345 (define identifier? #f)
346 (define generate-temporaries #f)
347 (define bound-identifier=? #f)
348 (define free-identifier=? #f)
350 ;; $sc-dispatch is an implementation detail of psyntax. It is used by
351 ;; expanded macros, to dispatch an input against a set of patterns.
352 (define $sc-dispatch #f)
355 (primitive-load-path "ice-9/psyntax-pp")
356 ;; The binding for `macroexpand' has now been overridden, making psyntax the
363 ((_ x y ...) (if x (and y ...) #f))))
369 ((_ x y ...) (let ((t x)) (if t t (or y ...))))))
371 ;; The "maybe-more" bits are something of a hack, so that we can support
372 ;; SRFI-61. Rewrites into a standalone syntax-case macro would be
375 (syntax-rules (=> else)
376 ((_ "maybe-more" test consequent)
377 (if test consequent))
379 ((_ "maybe-more" test consequent clause ...)
380 (if test consequent (cond clause ...)))
382 ((_ (else else1 else2 ...))
383 (begin else1 else2 ...))
385 ((_ (test => receiver) more-clause ...)
387 (cond "maybe-more" t (receiver t) more-clause ...)))
389 ((_ (generator guard => receiver) more-clause ...)
390 (call-with-values (lambda () generator)
393 (apply guard t) (apply receiver t) more-clause ...))))
395 ((_ (test => receiver ...) more-clause ...)
396 (syntax-violation 'cond "wrong number of receiver expressions"
397 '(test => receiver ...)))
398 ((_ (generator guard => receiver ...) more-clause ...)
399 (syntax-violation 'cond "wrong number of receiver expressions"
400 '(generator guard => receiver ...)))
402 ((_ (test) more-clause ...)
404 (cond "maybe-more" t t more-clause ...)))
406 ((_ (test body1 body2 ...) more-clause ...)
408 test (begin body1 body2 ...) more-clause ...))))
414 (let ((atom-key (key ...)))
415 (case atom-key clauses ...)))
417 (else result1 result2 ...))
418 (begin result1 result2 ...))
420 ((atoms ...) result1 result2 ...))
421 (if (memv key '(atoms ...))
422 (begin result1 result2 ...)))
424 ((atoms ...) result1 result2 ...)
426 (if (memv key '(atoms ...))
427 (begin result1 result2 ...)
428 (case key clause clauses ...)))))
432 ((do ((var init step ...) ...)
445 (loop (do "step" var step ...)
455 ((_ exp) (make-promise (lambda () exp)))))
457 (include-from-path "ice-9/quasisyntax")
459 (define-syntax current-source-location
463 (with-syntax ((s (datum->syntax x (syntax-source x))))
472 (define-syntax define-macro
476 ((_ (macro . args) doc body1 body ...)
477 (string? (syntax->datum #'doc))
478 #'(define-macro macro doc (lambda args body1 body ...)))
479 ((_ (macro . args) body ...)
480 #'(define-macro macro #f (lambda args body ...)))
481 ((_ macro doc transformer)
482 (or (string? (syntax->datum #'doc))
483 (not (syntax->datum #'doc)))
484 #'(define-syntax macro
487 #((macro-type . defmacro)
488 (defmacro-args args))
491 (let ((v (syntax->datum #'args)))
492 (datum->syntax y (apply transformer v)))))))))))
494 (define-syntax defmacro
496 "Define a defmacro, with the old lispy defun syntax."
498 ((_ macro args doc body1 body ...)
499 (string? (syntax->datum #'doc))
500 #'(define-macro macro doc (lambda args body1 body ...)))
501 ((_ macro args body ...)
502 #'(define-macro macro #f (lambda args body ...))))))
510 ;;; Depends on: defmacro
513 (defmacro begin-deprecated forms
514 (if (include-deprecated-features)
520 ;;; {Trivial Functions}
523 (define (identity x) x)
524 (define (and=> value procedure) (and value (procedure value)))
525 (define call/cc call-with-current-continuation)
527 (defmacro false-if-exception (expr)
530 ;; avoid saving backtraces inside false-if-exception
531 (with-fluids ((the-last-stack (fluid-ref the-last-stack)))
537 ;;; {General Properties}
540 ;; Properties are a lispy way to associate random info with random objects.
541 ;; Traditionally properties are implemented as an alist or a plist actually
542 ;; pertaining to the object in question.
544 ;; These "object properties" have the advantage that they can be associated with
545 ;; any object, even if the object has no plist. Object properties are good when
546 ;; you are extending pre-existing objects in unexpected ways. They also present
547 ;; a pleasing, uniform procedure-with-setter interface. But if you have a data
548 ;; type that always has properties, it's often still best to store those
549 ;; properties within the object itself.
551 (define (make-object-property)
552 (let ((prop (primitive-make-property #f)))
553 (make-procedure-with-setter
554 (lambda (obj) (primitive-property-ref prop obj))
555 (lambda (obj val) (primitive-property-set! prop obj val)))))
559 ;;; {Symbol Properties}
562 ;;; Symbol properties are something you see in old Lisp code. In most current
563 ;;; Guile code, symbols are not used as a data structure -- they are used as
564 ;;; keys into other data structures.
566 (define (symbol-property sym prop)
567 (let ((pair (assoc prop (symbol-pref sym))))
568 (and pair (cdr pair))))
570 (define (set-symbol-property! sym prop val)
571 (let ((pair (assoc prop (symbol-pref sym))))
574 (symbol-pset! sym (acons prop val (symbol-pref sym))))))
576 (define (symbol-property-remove! sym prop)
577 (let ((pair (assoc prop (symbol-pref sym))))
579 (symbol-pset! sym (delq! pair (symbol-pref sym))))))
586 (define (array-shape a)
587 (map (lambda (ind) (if (number? ind) (list 0 (+ -1 ind)) ind))
588 (array-dimensions a)))
595 ;;; It's much better if you can use lambda* / define*, of course.
597 (define (kw-arg-ref args kw)
598 (let ((rem (member kw args)))
599 (and rem (pair? (cdr rem)) (cadr rem))))
606 (define (struct-layout s)
607 (struct-ref (struct-vtable s) vtable-index-layout))
614 ;; Printing records: by default, records are printed as
616 ;; #<type-name field1: val1 field2: val2 ...>
618 ;; You can change that by giving a custom printing function to
619 ;; MAKE-RECORD-TYPE (after the list of field symbols). This function
620 ;; will be called like
622 ;; (<printer> object port)
624 ;; It should print OBJECT to PORT.
626 (define (inherit-print-state old-port new-port)
627 (if (get-print-state old-port)
628 (port-with-print-state new-port (get-print-state old-port))
631 ;; 0: type-name, 1: fields, 2: constructor
632 (define record-type-vtable
633 ;; FIXME: This should just call make-vtable, not make-vtable-vtable; but for
634 ;; that we need to expose the bare vtable-vtable to Scheme.
635 (make-vtable-vtable "prprpw" 0
637 (cond ((eq? s record-type-vtable)
638 (display "#<record-type-vtable>" p))
640 (display "#<record-type " p)
641 (display (record-type-name s) p)
644 (define (record-type? obj)
645 (and (struct? obj) (eq? record-type-vtable (struct-vtable obj))))
647 (define* (make-record-type type-name fields #:optional printer)
648 ;; Pre-generate constructors for nfields < 20.
649 (define-syntax make-constructor
651 (define *max-static-argument-count* 20)
652 (define (make-formals n)
658 (string (integer->char (+ (char->integer #\a) i)))))
662 ((_ rtd exp) (not (identifier? #'exp))
664 (make-constructor rtd n)))
668 (if (< n *max-static-argument-count*)
669 (cons (with-syntax (((formal ...) (make-formals n))
673 (make-struct rtd 0 formal ...))))
678 (if (= (length args) nfields)
679 (apply make-struct rtd 0 args)
680 (scm-error 'wrong-number-of-args
681 (format #f "make-~a" type-name)
682 "Wrong number of arguments" '() #f)))))))))
684 (define (default-record-printer s p)
686 (display (record-type-name (record-type-descriptor s)) p)
687 (let loop ((fields (record-type-fields (record-type-descriptor s)))
690 ((not (null? fields))
692 (display (car fields) p)
694 (display (struct-ref s off) p)
695 (loop (cdr fields) (+ 1 off)))))
698 (let ((rtd (make-struct record-type-vtable 0
701 (map (lambda (f) "pw") fields)))
702 (or printer default-record-printer)
704 (copy-tree fields))))
705 (struct-set! rtd (+ vtable-offset-user 2)
706 (make-constructor rtd (length fields)))
707 ;; Temporary solution: Associate a name to the record type descriptor
708 ;; so that the object system can create a wrapper class for it.
709 (set-struct-vtable-name! rtd (if (symbol? type-name)
711 (string->symbol type-name)))
714 (define (record-type-name obj)
715 (if (record-type? obj)
716 (struct-ref obj vtable-offset-user)
717 (error 'not-a-record-type obj)))
719 (define (record-type-fields obj)
720 (if (record-type? obj)
721 (struct-ref obj (+ 1 vtable-offset-user))
722 (error 'not-a-record-type obj)))
724 (define* (record-constructor rtd #:optional field-names)
725 (if (not field-names)
726 (struct-ref rtd (+ 2 vtable-offset-user))
728 `(lambda ,field-names
729 (make-struct ',rtd 0 ,@(map (lambda (f)
730 (if (memq f field-names)
733 (record-type-fields rtd)))))))
735 (define (record-predicate rtd)
736 (lambda (obj) (and (struct? obj) (eq? rtd (struct-vtable obj)))))
738 (define (%record-type-error rtd obj) ;; private helper
739 (or (eq? rtd (record-type-descriptor obj))
740 (scm-error 'wrong-type-arg "%record-type-check"
741 "Wrong type record (want `~S'): ~S"
742 (list (record-type-name rtd) obj)
745 (define (record-accessor rtd field-name)
746 (let ((pos (list-index (record-type-fields rtd) field-name)))
748 (error 'no-such-field field-name))
750 (if (eq? (struct-vtable obj) rtd)
752 (%record-type-error rtd obj)))))
754 (define (record-modifier rtd field-name)
755 (let ((pos (list-index (record-type-fields rtd) field-name)))
757 (error 'no-such-field field-name))
759 (if (eq? (struct-vtable obj) rtd)
760 (struct-set! obj pos val)
761 (%record-type-error rtd obj)))))
763 (define (record? obj)
764 (and (struct? obj) (record-type? (struct-vtable obj))))
766 (define (record-type-descriptor obj)
769 (error 'not-a-record obj)))
778 (define (->bool x) (not (not x)))
785 (define (symbol-append . args)
786 (string->symbol (apply string-append (map symbol->string args))))
788 (define (list->symbol . args)
789 (string->symbol (apply list->string args)))
791 (define (symbol . args)
792 (string->symbol (apply string args)))
799 (define (list-index l k)
805 (loop (+ n 1) (cdr l))))))
809 (if (provided? 'posix)
810 (primitive-load-path "ice-9/posix"))
812 (if (provided? 'socket)
813 (primitive-load-path "ice-9/networking"))
815 ;; For reference, Emacs file-exists-p uses stat in this same way.
817 (if (provided? 'posix)
819 (->bool (stat str #f)))
821 (let ((port (catch 'system-error (lambda () (open-file str OPEN_READ))
823 (if port (begin (close-port port) #t)
826 (define file-is-directory?
827 (if (provided? 'posix)
829 (eq? (stat:type (stat str)) 'directory))
831 (let ((port (catch 'system-error
832 (lambda () (open-file (string-append str "/.")
835 (if port (begin (close-port port) #t)
838 (define (system-error-errno args)
839 (if (eq? (car args) 'system-error)
840 (car (list-ref args 4))
852 (scm-error 'misc-error #f "?" #f #f))
855 (let ((msg (string-join (cons "~A" (make-list (length args) "~S")))))
856 (scm-error 'misc-error #f msg (cons message args) #f)))))
860 ;;; {Time Structures}
863 (define (tm:sec obj) (vector-ref obj 0))
864 (define (tm:min obj) (vector-ref obj 1))
865 (define (tm:hour obj) (vector-ref obj 2))
866 (define (tm:mday obj) (vector-ref obj 3))
867 (define (tm:mon obj) (vector-ref obj 4))
868 (define (tm:year obj) (vector-ref obj 5))
869 (define (tm:wday obj) (vector-ref obj 6))
870 (define (tm:yday obj) (vector-ref obj 7))
871 (define (tm:isdst obj) (vector-ref obj 8))
872 (define (tm:gmtoff obj) (vector-ref obj 9))
873 (define (tm:zone obj) (vector-ref obj 10))
875 (define (set-tm:sec obj val) (vector-set! obj 0 val))
876 (define (set-tm:min obj val) (vector-set! obj 1 val))
877 (define (set-tm:hour obj val) (vector-set! obj 2 val))
878 (define (set-tm:mday obj val) (vector-set! obj 3 val))
879 (define (set-tm:mon obj val) (vector-set! obj 4 val))
880 (define (set-tm:year obj val) (vector-set! obj 5 val))
881 (define (set-tm:wday obj val) (vector-set! obj 6 val))
882 (define (set-tm:yday obj val) (vector-set! obj 7 val))
883 (define (set-tm:isdst obj val) (vector-set! obj 8 val))
884 (define (set-tm:gmtoff obj val) (vector-set! obj 9 val))
885 (define (set-tm:zone obj val) (vector-set! obj 10 val))
887 (define (tms:clock obj) (vector-ref obj 0))
888 (define (tms:utime obj) (vector-ref obj 1))
889 (define (tms:stime obj) (vector-ref obj 2))
890 (define (tms:cutime obj) (vector-ref obj 3))
891 (define (tms:cstime obj) (vector-ref obj 4))
895 ;;; {File Descriptors and Ports}
898 (define file-position ftell)
899 (define* (file-set-position port offset #:optional (whence SEEK_SET))
900 (seek port offset whence))
902 (define (move->fdes fd/port fd)
903 (cond ((integer? fd/port)
904 (dup->fdes fd/port fd)
908 (primitive-move->fdes fd/port fd)
909 (set-port-revealed! fd/port 1)
912 (define (release-port-handle port)
913 (let ((revealed (port-revealed port)))
915 (set-port-revealed! port (- revealed 1)))))
920 (fdopen (dup->fdes port/fd) mode))
921 ((port/fd mode new-fd)
922 (let ((port (fdopen (dup->fdes port/fd new-fd) mode)))
923 (set-port-revealed! port 1)
929 (dup->port port/fd "r"))
931 (dup->port port/fd "r" new-fd))))
936 (dup->port port/fd "w"))
938 (dup->port port/fd "w" new-fd))))
943 (if (integer? port/fd)
945 (dup->port port/fd (port-mode port/fd))))
947 (if (integer? port/fd)
948 (dup->fdes port/fd new-fd)
949 (dup->port port/fd (port-mode port/fd) new-fd)))))
951 (define (duplicate-port port modes)
952 (dup->port port modes))
954 (define (fdes->inport fdes)
955 (let loop ((rest-ports (fdes->ports fdes)))
956 (cond ((null? rest-ports)
957 (let ((result (fdopen fdes "r")))
958 (set-port-revealed! result 1)
960 ((input-port? (car rest-ports))
961 (set-port-revealed! (car rest-ports)
962 (+ (port-revealed (car rest-ports)) 1))
965 (loop (cdr rest-ports))))))
967 (define (fdes->outport fdes)
968 (let loop ((rest-ports (fdes->ports fdes)))
969 (cond ((null? rest-ports)
970 (let ((result (fdopen fdes "w")))
971 (set-port-revealed! result 1)
973 ((output-port? (car rest-ports))
974 (set-port-revealed! (car rest-ports)
975 (+ (port-revealed (car rest-ports)) 1))
978 (loop (cdr rest-ports))))))
980 (define (port->fdes port)
981 (set-port-revealed! port (+ (port-revealed port) 1))
984 (define (setenv name value)
986 (putenv (string-append name "=" value))
989 (define (unsetenv name)
990 "Remove the entry for NAME from the environment."
998 (define (in-vicinity vicinity file)
999 (let ((tail (let ((len (string-length vicinity)))
1002 (string-ref vicinity (- len 1))))))
1003 (string-append vicinity
1012 ;;; {Help for scm_shell}
1014 ;;; The argument-processing code used by Guile-based shells generates
1015 ;;; Scheme code based on the argument list. This page contains help
1016 ;;; functions for the code it generates.
1019 (define (command-line) (program-arguments))
1021 ;; This is mostly for the internal use of the code generated by
1022 ;; scm_compile_shell_switches.
1024 (define (turn-on-debugging)
1025 (debug-enable 'debug)
1026 (debug-enable 'backtrace)
1027 (read-enable 'positions))
1029 (define (load-user-init)
1030 (let* ((home (or (getenv "HOME")
1031 (false-if-exception (passwd:dir (getpwuid (getuid))))
1032 "/")) ;; fallback for cygwin etc.
1033 (init-file (in-vicinity home ".guile")))
1034 (if (file-exists? init-file)
1035 (primitive-load init-file))))
1039 ;;; {The interpreter stack}
1042 ;; %stacks defined in stacks.c
1043 (define (%start-stack tag thunk)
1044 (let ((prompt-tag (make-prompt-tag "start-stack")))
1048 (with-fluids ((%stacks (acons tag prompt-tag
1049 (or (fluid-ref %stacks) '()))))
1052 (%start-stack tag (lambda () (apply k args)))))))
1053 (define-syntax start-stack
1056 (%start-stack tag (lambda () exp)))))
1060 ;;; {Loading by paths}
1063 ;;; Load a Scheme source file named NAME, searching for it in the
1064 ;;; directories listed in %load-path, and applying each of the file
1065 ;;; name extensions listed in %load-extensions.
1066 (define (load-from-path name)
1067 (start-stack 'load-stack
1068 (primitive-load-path name)))
1070 (define %load-verbosely #f)
1071 (define (assert-load-verbosity v) (set! %load-verbosely v))
1073 (define (%load-announce file)
1075 (with-output-to-port (current-error-port)
1078 (display "loading ")
1083 (set! %load-hook %load-announce)
1085 (define* (load name #:optional reader)
1086 ;; Returns the .go file corresponding to `name'. Does not search load
1087 ;; paths, only the fallback path. If the .go file is missing or out of
1088 ;; date, and autocompilation is enabled, will try autocompilation, just
1089 ;; as primitive-load-path does internally. primitive-load is
1090 ;; unaffected. Returns #f if autocompilation failed or was disabled.
1092 ;; NB: Unless we need to compile the file, this function should not cause
1093 ;; (system base compile) to be loaded up. For that reason compiled-file-name
1094 ;; partially duplicates functionality from (system base compile).
1095 (define (compiled-file-name canon-path)
1096 (and %compile-fallback-path
1098 %compile-fallback-path
1099 ;; no need for '/' separator here, canon-path is absolute
1101 (cond ((or (null? %load-compiled-extensions)
1102 (string-null? (car %load-compiled-extensions)))
1103 (warn "invalid %load-compiled-extensions"
1104 %load-compiled-extensions)
1106 (else (car %load-compiled-extensions))))))
1107 (define (fresh-compiled-file-name go-path)
1110 (let* ((scmstat (stat name))
1111 (gostat (stat go-path #f)))
1112 (if (and gostat (= (stat:mtime gostat) (stat:mtime scmstat)))
1116 (format (current-error-port)
1117 ";;; note: source file ~a\n;;; newer than compiled ~a\n"
1120 (%load-should-autocompile
1121 (%warn-autocompilation-enabled)
1122 (format (current-error-port) ";;; compiling ~a\n" name)
1123 ;; This use of @ is (ironically?) boot-safe, as modules have
1124 ;; not been booted yet, so the resolve-module call in psyntax
1125 ;; doesn't try to load a module, and compile-file will be
1126 ;; treated as a function, not a macro.
1127 (let ((cfn ((@ (system base compile) compile-file) name
1128 #:env (current-module))))
1129 (format (current-error-port) ";;; compiled ~a\n" cfn)
1133 (format (current-error-port)
1134 ";;; WARNING: compilation of ~a failed:\n;;; key ~a, throw_args ~s\n"
1137 (with-fluids ((current-reader reader))
1138 (let ((cfn (and=> (and=> (false-if-exception (canonicalize-path name))
1140 fresh-compiled-file-name)))
1143 (start-stack 'load-stack
1144 (primitive-load name))))))
1148 ;;; {Reader Extensions}
1150 ;;; Reader code for various "#c" forms.
1153 (define read-eval? (make-fluid))
1154 (fluid-set! read-eval? #f)
1155 (read-hash-extend #\.
1157 (if (fluid-ref read-eval?)
1158 (eval (read port) (interaction-environment))
1160 "#. read expansion found and read-eval? is #f."))))
1164 ;;; {Low Level Modules}
1166 ;;; These are the low level data structures for modules.
1168 ;;; Every module object is of the type 'module-type', which is a record
1169 ;;; consisting of the following members:
1171 ;;; - eval-closure: the function that defines for its module the strategy that
1172 ;;; shall be followed when looking up symbols in the module.
1174 ;;; An eval-closure is a function taking two arguments: the symbol to be
1175 ;;; looked up and a boolean value telling whether a binding for the symbol
1176 ;;; should be created if it does not exist yet. If the symbol lookup
1177 ;;; succeeded (either because an existing binding was found or because a new
1178 ;;; binding was created), a variable object representing the binding is
1179 ;;; returned. Otherwise, the value #f is returned. Note that the eval
1180 ;;; closure does not take the module to be searched as an argument: During
1181 ;;; construction of the eval-closure, the eval-closure has to store the
1182 ;;; module it belongs to in its environment. This means, that any
1183 ;;; eval-closure can belong to only one module.
1185 ;;; The eval-closure of a module can be defined arbitrarily. However, three
1186 ;;; special cases of eval-closures are to be distinguished: During startup
1187 ;;; the module system is not yet activated. In this phase, no modules are
1188 ;;; defined and all bindings are automatically stored by the system in the
1189 ;;; pre-modules-obarray. Since no eval-closures exist at this time, the
1190 ;;; functions which require an eval-closure as their argument need to be
1191 ;;; passed the value #f.
1193 ;;; The other two special cases of eval-closures are the
1194 ;;; standard-eval-closure and the standard-interface-eval-closure. Both
1195 ;;; behave equally for the case that no new binding is to be created. The
1196 ;;; difference between the two comes in, when the boolean argument to the
1197 ;;; eval-closure indicates that a new binding shall be created if it is not
1200 ;;; Given that no new binding shall be created, both standard eval-closures
1201 ;;; define the following standard strategy of searching bindings in the
1202 ;;; module: First, the module's obarray is searched for the symbol. Second,
1203 ;;; if no binding for the symbol was found in the module's obarray, the
1204 ;;; module's binder procedure is exececuted. If this procedure did not
1205 ;;; return a binding for the symbol, the modules referenced in the module's
1206 ;;; uses list are recursively searched for a binding of the symbol. If the
1207 ;;; binding can not be found in these modules also, the symbol lookup has
1210 ;;; If a new binding shall be created, the standard-interface-eval-closure
1211 ;;; immediately returns indicating failure. That is, it does not even try
1212 ;;; to look up the symbol. In contrast, the standard-eval-closure would
1213 ;;; first search the obarray, and if no binding was found there, would
1214 ;;; create a new binding in the obarray, therefore not calling the binder
1215 ;;; procedure or searching the modules in the uses list.
1217 ;;; The explanation of the following members obarray, binder and uses
1218 ;;; assumes that the symbol lookup follows the strategy that is defined in
1219 ;;; the standard-eval-closure and the standard-interface-eval-closure.
1221 ;;; - obarray: a hash table that maps symbols to variable objects. In this
1222 ;;; hash table, the definitions are found that are local to the module (that
1223 ;;; is, not imported from other modules). When looking up bindings in the
1224 ;;; module, this hash table is searched first.
1226 ;;; - binder: either #f or a function taking a module and a symbol argument.
1227 ;;; If it is a function it is called after the obarray has been
1228 ;;; unsuccessfully searched for a binding. It then can provide bindings
1229 ;;; that would otherwise not be found locally in the module.
1231 ;;; - uses: a list of modules from which non-local bindings can be inherited.
1232 ;;; These modules are the third place queried for bindings after the obarray
1233 ;;; has been unsuccessfully searched and the binder function did not deliver
1234 ;;; a result either.
1236 ;;; - transformer: either #f or a function taking a scheme expression as
1237 ;;; delivered by read. If it is a function, it will be called to perform
1238 ;;; syntax transformations (e. g. makro expansion) on the given scheme
1239 ;;; expression. The output of the transformer function will then be passed
1240 ;;; to Guile's internal memoizer. This means that the output must be valid
1241 ;;; scheme code. The only exception is, that the output may make use of the
1242 ;;; syntax extensions provided to identify the modules that a binding
1245 ;;; - name: the name of the module. This is used for all kinds of printing
1246 ;;; outputs. In certain places the module name also serves as a way of
1247 ;;; identification. When adding a module to the uses list of another
1248 ;;; module, it is made sure that the new uses list will not contain two
1249 ;;; modules of the same name.
1251 ;;; - kind: classification of the kind of module. The value is (currently?)
1252 ;;; only used for printing. It has no influence on how a module is treated.
1253 ;;; Currently the following values are used when setting the module kind:
1254 ;;; 'module, 'directory, 'interface, 'custom-interface. If no explicit kind
1255 ;;; is set, it defaults to 'module.
1257 ;;; - duplicates-handlers: a list of procedures that get called to make a
1258 ;;; choice between two duplicate bindings when name clashes occur. See the
1259 ;;; `duplicate-handlers' global variable below.
1261 ;;; - observers: a list of procedures that get called when the module is
1264 ;;; - weak-observers: a weak-key hash table of procedures that get called
1265 ;;; when the module is modified. See `module-observe-weak' for details.
1267 ;;; In addition, the module may (must?) contain a binding for
1268 ;;; `%module-public-interface'. This variable should be bound to a module
1269 ;;; representing the exported interface of a module. See the
1270 ;;; `module-public-interface' and `module-export!' procedures.
1272 ;;; !!! warning: The interface to lazy binder procedures is going
1273 ;;; to be changed in an incompatible way to permit all the basic
1274 ;;; module ops to be virtualized.
1276 ;;; (make-module size use-list lazy-binding-proc) => module
1277 ;;; module-{obarray,uses,binder}[|-set!]
1278 ;;; (module? obj) => [#t|#f]
1279 ;;; (module-locally-bound? module symbol) => [#t|#f]
1280 ;;; (module-bound? module symbol) => [#t|#f]
1281 ;;; (module-symbol-locally-interned? module symbol) => [#t|#f]
1282 ;;; (module-symbol-interned? module symbol) => [#t|#f]
1283 ;;; (module-local-variable module symbol) => [#<variable ...> | #f]
1284 ;;; (module-variable module symbol) => [#<variable ...> | #f]
1285 ;;; (module-symbol-binding module symbol opt-value)
1286 ;;; => [ <obj> | opt-value | an error occurs ]
1287 ;;; (module-make-local-var! module symbol) => #<variable...>
1288 ;;; (module-add! module symbol var) => unspecified
1289 ;;; (module-remove! module symbol) => unspecified
1290 ;;; (module-for-each proc module) => unspecified
1291 ;;; (make-scm-module) => module ; a lazy copy of the symhash module
1292 ;;; (set-current-module module) => unspecified
1293 ;;; (current-module) => #<module...>
1299 ;;; {Printing Modules}
1302 ;; This is how modules are printed. You can re-define it.
1303 (define (%print-module mod port)
1305 (display (or (module-kind mod) "module") port)
1307 (display (module-name mod) port)
1309 (display (number->string (object-address mod) 16) port)
1313 ;; Locally extend the syntax to allow record accessors to be defined at
1314 ;; compile-time. Cache the rtd locally to the constructor, the getters and
1315 ;; the setters, in order to allow for redefinition of the record type; not
1316 ;; relevant in the case of modules, but perhaps if we make this public, it
1319 ((define-record-type
1321 (define (make-id scope . fragments)
1322 (datum->syntax #'scope
1323 (apply symbol-append
1325 (if (symbol? x) x (syntax->datum x)))
1328 (define (getter rtd type-name field slot)
1329 #`(define #,(make-id rtd type-name '- field)
1331 (lambda (#,type-name)
1332 (if (eq? (struct-vtable #,type-name) rtd)
1333 (struct-ref #,type-name #,slot)
1334 (%record-type-error rtd #,type-name))))))
1336 (define (setter rtd type-name field slot)
1337 #`(define #,(make-id rtd 'set- type-name '- field '!)
1339 (lambda (#,type-name val)
1340 (if (eq? (struct-vtable #,type-name) rtd)
1341 (struct-set! #,type-name #,slot val)
1342 (%record-type-error rtd #,type-name))))))
1344 (define (accessors rtd type-name fields n exp)
1345 (syntax-case fields ()
1347 (((field #:no-accessors) field* ...) (identifier? #'field)
1348 (accessors rtd type-name #'(field* ...) (1+ n)
1350 (((field #:no-setter) field* ...) (identifier? #'field)
1351 (accessors rtd type-name #'(field* ...) (1+ n)
1353 #,(getter rtd type-name #'field n))))
1354 (((field #:no-getter) field* ...) (identifier? #'field)
1355 (accessors rtd type-name #'(field* ...) (1+ n)
1357 #,(setter rtd type-name #'field n))))
1358 ((field field* ...) (identifier? #'field)
1359 (accessors rtd type-name #'(field* ...) (1+ n)
1361 #,(getter rtd type-name #'field n)
1362 #,(setter rtd type-name #'field n))))))
1364 (define (predicate rtd type-name fields exp)
1366 rtd type-name fields 0
1369 (define (#,(make-id rtd type-name '?) obj)
1370 (and (struct? obj) (eq? (struct-vtable obj) #,rtd))))))
1372 (define (field-list fields)
1373 (syntax-case fields ()
1375 (((f . opts) . rest) (identifier? #'f)
1376 (cons #'f (field-list #'rest)))
1377 ((f . rest) (identifier? #'f)
1378 (cons #'f (field-list #'rest)))))
1380 (define (constructor rtd type-name fields exp)
1381 (let ((ctor (make-id rtd type-name '-constructor))
1382 (args (field-list fields)))
1383 (predicate rtd type-name fields
1388 (make-struct rtd 0 #,@args))))
1389 (struct-set! #,rtd (+ vtable-offset-user 2)
1392 (define (type type-name printer fields)
1393 (define (make-layout)
1394 (let lp ((fields fields) (slots '()))
1395 (syntax-case fields ()
1396 (() (datum->syntax #'here
1398 (apply string-append slots))))
1399 ((_ . rest) (lp #'rest (cons "pw" slots))))))
1401 (let ((rtd (make-id type-name type-name '-type)))
1402 (constructor rtd type-name fields
1405 (make-struct record-type-vtable 0
1409 '#,(field-list fields)))
1410 (set-struct-vtable-name! #,rtd '#,type-name)))))
1413 ((_ type-name printer (field ...))
1414 (type #'type-name #'printer #'(field ...)))))))
1418 ;; A module is characterized by an obarray in which local symbols
1419 ;; are interned, a list of modules, "uses", from which non-local
1420 ;; bindings can be inherited, and an optional lazy-binder which
1421 ;; is a (CLOSURE module symbol) which, as a last resort, can provide
1422 ;; bindings that would otherwise not be found locally in the module.
1424 ;; NOTE: If you change the set of fields or their order, you also need to
1425 ;; change the constants in libguile/modules.h.
1427 ;; NOTE: The getter `module-eval-closure' is used in libguile/modules.c.
1428 ;; NOTE: The getter `module-transfomer' is defined libguile/modules.c.
1429 ;; NOTE: The getter `module-name' is defined later, due to boot reasons.
1430 ;; NOTE: The getter `module-public-interface' is used in libguile/modules.c.
1432 (define-record-type module
1433 (lambda (obj port) (%print-module obj port))
1438 (transformer #:no-getter)
1442 (import-obarray #:no-setter)
1444 (weak-observers #:no-setter)
1452 ;; make-module &opt size uses binder
1454 ;; Create a new module, perhaps with a particular size of obarray,
1455 ;; initial uses list, or binding procedure.
1460 (define (parse-arg index default)
1461 (if (> (length args) index)
1462 (list-ref args index)
1465 (define %default-import-size
1466 ;; Typical number of imported bindings actually used by a module.
1469 (if (> (length args) 3)
1470 (error "Too many args to make-module." args))
1472 (let ((size (parse-arg 0 31))
1473 (uses (parse-arg 1 '()))
1474 (binder (parse-arg 2 #f)))
1476 (if (not (integer? size))
1477 (error "Illegal size to make-module." size))
1478 (if (not (and (list? uses)
1479 (and-map module? uses)))
1480 (error "Incorrect use list." uses))
1481 (if (and binder (not (procedure? binder)))
1483 "Lazy-binder expected to be a procedure or #f." binder))
1485 (let ((module (module-constructor (make-hash-table size)
1486 uses binder #f macroexpand
1488 (make-hash-table %default-import-size)
1490 (make-weak-key-hash-table 31) #f
1491 (make-hash-table 7) #f #f #f)))
1493 ;; We can't pass this as an argument to module-constructor,
1494 ;; because we need it to close over a pointer to the module
1496 (set-module-eval-closure! module (standard-eval-closure module))
1503 ;;; {Observer protocol}
1506 (define (module-observe module proc)
1507 (set-module-observers! module (cons proc (module-observers module)))
1510 (define* (module-observe-weak module observer-id #:optional (proc observer-id))
1511 ;; Register PROC as an observer of MODULE under name OBSERVER-ID (which can
1512 ;; be any Scheme object). PROC is invoked and passed MODULE any time
1513 ;; MODULE is modified. PROC gets unregistered when OBSERVER-ID gets GC'd
1514 ;; (thus, it is never unregistered if OBSERVER-ID is an immediate value,
1517 ;; The two-argument version is kept for backward compatibility: when called
1518 ;; with two arguments, the observer gets unregistered when closure PROC
1519 ;; gets GC'd (making it impossible to use an anonymous lambda for PROC).
1520 (hashq-set! (module-weak-observers module) observer-id proc))
1522 (define (module-unobserve token)
1523 (let ((module (car token))
1526 (hash-remove! (module-weak-observers module) id)
1527 (set-module-observers! module (delq1! id (module-observers module)))))
1530 (define module-defer-observers #f)
1531 (define module-defer-observers-mutex (make-mutex 'recursive))
1532 (define module-defer-observers-table (make-hash-table))
1534 (define (module-modified m)
1535 (if module-defer-observers
1536 (hash-set! module-defer-observers-table m #t)
1537 (module-call-observers m)))
1539 ;;; This function can be used to delay calls to observers so that they
1540 ;;; can be called once only in the face of massive updating of modules.
1542 (define (call-with-deferred-observers thunk)
1545 (lock-mutex module-defer-observers-mutex)
1546 (set! module-defer-observers #t))
1549 (set! module-defer-observers #f)
1550 (hash-for-each (lambda (m dummy)
1551 (module-call-observers m))
1552 module-defer-observers-table)
1553 (hash-clear! module-defer-observers-table)
1554 (unlock-mutex module-defer-observers-mutex))))
1556 (define (module-call-observers m)
1557 (for-each (lambda (proc) (proc m)) (module-observers m))
1559 ;; We assume that weak observers don't (un)register themselves as they are
1560 ;; called since this would preclude proper iteration over the hash table
1562 (hash-for-each (lambda (id proc) (proc m)) (module-weak-observers m)))
1566 ;;; {Module Searching in General}
1568 ;;; We sometimes want to look for properties of a symbol
1569 ;;; just within the obarray of one module. If the property
1570 ;;; holds, then it is said to hold ``locally'' as in, ``The symbol
1571 ;;; DISPLAY is locally rebound in the module `safe-guile'.''
1574 ;;; Other times, we want to test for a symbol property in the obarray
1575 ;;; of M and, if it is not found there, try each of the modules in the
1576 ;;; uses list of M. This is the normal way of testing for some
1577 ;;; property, so we state these properties without qualification as
1578 ;;; in: ``The symbol 'fnord is interned in module M because it is
1579 ;;; interned locally in module M2 which is a member of the uses list
1583 ;; module-search fn m
1585 ;; return the first non-#f result of FN applied to M and then to
1586 ;; the modules in the uses of m, and so on recursively. If all applications
1587 ;; return #f, then so does this function.
1589 (define (module-search fn m v)
1592 (or (module-search fn (car pos) v)
1595 (loop (module-uses m))))
1598 ;;; {Is a symbol bound in a module?}
1600 ;;; Symbol S in Module M is bound if S is interned in M and if the binding
1601 ;;; of S in M has been set to some well-defined value.
1604 ;; module-locally-bound? module symbol
1606 ;; Is a symbol bound (interned and defined) locally in a given module?
1608 (define (module-locally-bound? m v)
1609 (let ((var (module-local-variable m v)))
1611 (variable-bound? var))))
1613 ;; module-bound? module symbol
1615 ;; Is a symbol bound (interned and defined) anywhere in a given module
1618 (define (module-bound? m v)
1619 (let ((var (module-variable m v)))
1621 (variable-bound? var))))
1623 ;;; {Is a symbol interned in a module?}
1625 ;;; Symbol S in Module M is interned if S occurs in
1626 ;;; of S in M has been set to some well-defined value.
1628 ;;; It is possible to intern a symbol in a module without providing
1629 ;;; an initial binding for the corresponding variable. This is done
1631 ;;; (module-add! module symbol (make-undefined-variable))
1633 ;;; In that case, the symbol is interned in the module, but not
1634 ;;; bound there. The unbound symbol shadows any binding for that
1635 ;;; symbol that might otherwise be inherited from a member of the uses list.
1638 (define (module-obarray-get-handle ob key)
1639 ((if (symbol? key) hashq-get-handle hash-get-handle) ob key))
1641 (define (module-obarray-ref ob key)
1642 ((if (symbol? key) hashq-ref hash-ref) ob key))
1644 (define (module-obarray-set! ob key val)
1645 ((if (symbol? key) hashq-set! hash-set!) ob key val))
1647 (define (module-obarray-remove! ob key)
1648 ((if (symbol? key) hashq-remove! hash-remove!) ob key))
1650 ;; module-symbol-locally-interned? module symbol
1652 ;; is a symbol interned (not neccessarily defined) locally in a given module
1653 ;; or its uses? Interned symbols shadow inherited bindings even if
1654 ;; they are not themselves bound to a defined value.
1656 (define (module-symbol-locally-interned? m v)
1657 (not (not (module-obarray-get-handle (module-obarray m) v))))
1659 ;; module-symbol-interned? module symbol
1661 ;; is a symbol interned (not neccessarily defined) anywhere in a given module
1662 ;; or its uses? Interned symbols shadow inherited bindings even if
1663 ;; they are not themselves bound to a defined value.
1665 (define (module-symbol-interned? m v)
1666 (module-search module-symbol-locally-interned? m v))
1669 ;;; {Mapping modules x symbols --> variables}
1672 ;; module-local-variable module symbol
1673 ;; return the local variable associated with a MODULE and SYMBOL.
1675 ;;; This function is very important. It is the only function that can
1676 ;;; return a variable from a module other than the mutators that store
1677 ;;; new variables in modules. Therefore, this function is the location
1678 ;;; of the "lazy binder" hack.
1680 ;;; If symbol is defined in MODULE, and if the definition binds symbol
1681 ;;; to a variable, return that variable object.
1683 ;;; If the symbols is not found at first, but the module has a lazy binder,
1684 ;;; then try the binder.
1686 ;;; If the symbol is not found at all, return #f.
1688 ;;; (This is now written in C, see `modules.c'.)
1691 ;;; {Mapping modules x symbols --> bindings}
1693 ;;; These are similar to the mapping to variables, except that the
1694 ;;; variable is dereferenced.
1697 ;; module-symbol-binding module symbol opt-value
1699 ;; return the binding of a variable specified by name within
1700 ;; a given module, signalling an error if the variable is unbound.
1701 ;; If the OPT-VALUE is passed, then instead of signalling an error,
1702 ;; return OPT-VALUE.
1704 (define (module-symbol-local-binding m v . opt-val)
1705 (let ((var (module-local-variable m v)))
1706 (if (and var (variable-bound? var))
1708 (if (not (null? opt-val))
1710 (error "Locally unbound variable." v)))))
1712 ;; module-symbol-binding module symbol opt-value
1714 ;; return the binding of a variable specified by name within
1715 ;; a given module, signalling an error if the variable is unbound.
1716 ;; If the OPT-VALUE is passed, then instead of signalling an error,
1717 ;; return OPT-VALUE.
1719 (define (module-symbol-binding m v . opt-val)
1720 (let ((var (module-variable m v)))
1721 (if (and var (variable-bound? var))
1723 (if (not (null? opt-val))
1725 (error "Unbound variable." v)))))
1730 ;;; {Adding Variables to Modules}
1733 ;; module-make-local-var! module symbol
1735 ;; ensure a variable for V in the local namespace of M.
1736 ;; If no variable was already there, then create a new and uninitialzied
1739 ;; This function is used in modules.c.
1741 (define (module-make-local-var! m v)
1742 (or (let ((b (module-obarray-ref (module-obarray m) v)))
1745 ;; Mark as modified since this function is called when
1746 ;; the standard eval closure defines a binding
1750 ;; Create a new local variable.
1751 (let ((local-var (make-undefined-variable)))
1752 (module-add! m v local-var)
1755 ;; module-ensure-local-variable! module symbol
1757 ;; Ensure that there is a local variable in MODULE for SYMBOL. If
1758 ;; there is no binding for SYMBOL, create a new uninitialized
1759 ;; variable. Return the local variable.
1761 (define (module-ensure-local-variable! module symbol)
1762 (or (module-local-variable module symbol)
1763 (let ((var (make-undefined-variable)))
1764 (module-add! module symbol var)
1767 ;; module-add! module symbol var
1769 ;; ensure a particular variable for V in the local namespace of M.
1771 (define (module-add! m v var)
1772 (if (not (variable? var))
1773 (error "Bad variable to module-add!" var))
1774 (module-obarray-set! (module-obarray m) v var)
1775 (module-modified m))
1779 ;; make sure that a symbol is undefined in the local namespace of M.
1781 (define (module-remove! m v)
1782 (module-obarray-remove! (module-obarray m) v)
1783 (module-modified m))
1785 (define (module-clear! m)
1786 (hash-clear! (module-obarray m))
1787 (module-modified m))
1789 ;; MODULE-FOR-EACH -- exported
1791 ;; Call PROC on each symbol in MODULE, with arguments of (SYMBOL VARIABLE).
1793 (define (module-for-each proc module)
1794 (hash-for-each proc (module-obarray module)))
1796 (define (module-map proc module)
1797 (hash-map->list proc (module-obarray module)))
1801 ;; Modules exist in a separate namespace from values, because you generally do
1802 ;; not want the name of a submodule, which you might not even use, to collide
1803 ;; with local variables that happen to be named the same as the submodule.
1805 (define (module-ref-submodule module name)
1806 (or (hashq-ref (module-submodules module) name)
1807 (and (module-submodule-binder module)
1808 ((module-submodule-binder module) module name))))
1810 (define (module-define-submodule! module name submodule)
1811 (hashq-set! (module-submodules module) name submodule))
1815 ;;; {Low Level Bootstrapping}
1820 ;; A root module uses the pre-modules-obarray as its obarray. This
1821 ;; special obarray accumulates all bindings that have been established
1822 ;; before the module system is fully booted.
1824 ;; (The obarray continues to be used by code that has been closed over
1825 ;; before the module system has been booted.)
1827 (define (make-root-module)
1828 (let ((m (make-module 0)))
1829 (set-module-obarray! m (%get-pre-modules-obarray))
1834 ;; The root interface is a module that uses the same obarray as the
1835 ;; root module. It does not allow new definitions, tho.
1837 (define (make-scm-module)
1838 (let ((m (make-module 0)))
1839 (set-module-obarray! m (%get-pre-modules-obarray))
1840 (set-module-eval-closure! m (standard-interface-eval-closure m))
1846 ;;; {Module-based Loading}
1849 (define (save-module-excursion thunk)
1850 (let ((inner-module (current-module))
1852 (dynamic-wind (lambda ()
1853 (set! outer-module (current-module))
1854 (set-current-module inner-module)
1855 (set! inner-module #f))
1858 (set! inner-module (current-module))
1859 (set-current-module outer-module)
1860 (set! outer-module #f)))))
1862 (define basic-load load)
1864 (define* (load-module filename #:optional reader)
1865 (save-module-excursion
1867 (let ((oldname (and (current-load-port)
1868 (port-filename (current-load-port)))))
1869 (basic-load (if (and oldname
1870 (> (string-length filename) 0)
1871 (not (char=? (string-ref filename 0) #\/))
1872 (not (string=? (dirname oldname) ".")))
1873 (string-append (dirname oldname) "/" filename)
1880 ;;; {MODULE-REF -- exported}
1883 ;; Returns the value of a variable called NAME in MODULE or any of its
1884 ;; used modules. If there is no such variable, then if the optional third
1885 ;; argument DEFAULT is present, it is returned; otherwise an error is signaled.
1887 (define (module-ref module name . rest)
1888 (let ((variable (module-variable module name)))
1889 (if (and variable (variable-bound? variable))
1890 (variable-ref variable)
1892 (error "No variable named" name 'in module)
1893 (car rest) ; default value
1896 ;; MODULE-SET! -- exported
1898 ;; Sets the variable called NAME in MODULE (or in a module that MODULE uses)
1899 ;; to VALUE; if there is no such variable, an error is signaled.
1901 (define (module-set! module name value)
1902 (let ((variable (module-variable module name)))
1904 (variable-set! variable value)
1905 (error "No variable named" name 'in module))))
1907 ;; MODULE-DEFINE! -- exported
1909 ;; Sets the variable called NAME in MODULE to VALUE; if there is no such
1910 ;; variable, it is added first.
1912 (define (module-define! module name value)
1913 (let ((variable (module-local-variable module name)))
1916 (variable-set! variable value)
1917 (module-modified module))
1918 (let ((variable (make-variable value)))
1919 (module-add! module name variable)))))
1921 ;; MODULE-DEFINED? -- exported
1923 ;; Return #t iff NAME is defined in MODULE (or in a module that MODULE
1926 (define (module-defined? module name)
1927 (let ((variable (module-variable module name)))
1928 (and variable (variable-bound? variable))))
1930 ;; MODULE-USE! module interface
1932 ;; Add INTERFACE to the list of interfaces used by MODULE.
1934 (define (module-use! module interface)
1935 (if (not (or (eq? module interface)
1936 (memq interface (module-uses module))))
1938 ;; Newly used modules must be appended rather than consed, so that
1939 ;; `module-variable' traverses the use list starting from the first
1941 (set-module-uses! module
1942 (append (filter (lambda (m)
1944 (equal? (module-name m)
1945 (module-name interface))))
1946 (module-uses module))
1948 (hash-clear! (module-import-obarray module))
1949 (module-modified module))))
1951 ;; MODULE-USE-INTERFACES! module interfaces
1953 ;; Same as MODULE-USE! but add multiple interfaces and check for duplicates
1955 (define (module-use-interfaces! module interfaces)
1956 (set-module-uses! module
1957 (append (module-uses module) interfaces))
1958 (hash-clear! (module-import-obarray module))
1959 (module-modified module))
1963 ;;; {Recursive Namespaces}
1965 ;;; A hierarchical namespace emerges if we consider some module to be
1966 ;;; root, and submodules of that module to be nested namespaces.
1968 ;;; The routines here manage variable names in hierarchical namespace.
1969 ;;; Each variable name is a list of elements, looked up in successively nested
1972 ;;; (nested-ref some-root-module '(foo bar baz))
1973 ;;; => <value of a variable named baz in the submodule bar of
1974 ;;; the submodule foo of some-root-module>
1979 ;;; ;; a-root is a module
1980 ;;; ;; name is a list of symbols
1982 ;;; nested-ref a-root name
1983 ;;; nested-set! a-root name val
1984 ;;; nested-define! a-root name val
1985 ;;; nested-remove! a-root name
1987 ;;; These functions manipulate values in namespaces. For referencing the
1988 ;;; namespaces themselves, use the following:
1990 ;;; nested-ref-module a-root name
1991 ;;; nested-define-module! a-root name mod
1993 ;;; (current-module) is a natural choice for a root so for convenience there are
1996 ;;; local-ref name == nested-ref (current-module) name
1997 ;;; local-set! name val == nested-set! (current-module) name val
1998 ;;; local-define name val == nested-define! (current-module) name val
1999 ;;; local-remove name == nested-remove! (current-module) name
2000 ;;; local-ref-module name == nested-ref-module (current-module) name
2001 ;;; local-define-module! name m == nested-define-module! (current-module) name m
2005 (define (nested-ref root names)
2008 (let loop ((cur root)
2012 (module-ref cur head #f)
2013 (let ((cur (module-ref-submodule cur head)))
2015 (loop cur (car tail) (cdr tail))))))))
2017 (define (nested-set! root names val)
2018 (let loop ((cur root)
2022 (module-set! cur head val)
2023 (let ((cur (module-ref-submodule cur head)))
2025 (error "failed to resolve module" names)
2026 (loop cur (car tail) (cdr tail)))))))
2028 (define (nested-define! root names val)
2029 (let loop ((cur root)
2033 (module-define! cur head val)
2034 (let ((cur (module-ref-submodule cur head)))
2036 (error "failed to resolve module" names)
2037 (loop cur (car tail) (cdr tail)))))))
2039 (define (nested-remove! root names)
2040 (let loop ((cur root)
2044 (module-remove! cur head)
2045 (let ((cur (module-ref-submodule cur head)))
2047 (error "failed to resolve module" names)
2048 (loop cur (car tail) (cdr tail)))))))
2051 (define (nested-ref-module root names)
2052 (let loop ((cur root)
2056 (let ((cur (module-ref-submodule cur (car names))))
2058 (loop cur (cdr names)))))))
2060 (define (nested-define-module! root names module)
2062 (error "can't redefine root module" root module)
2063 (let loop ((cur root)
2067 (module-define-submodule! cur head module)
2068 (let ((cur (or (module-ref-submodule cur head)
2069 (let ((m (make-module 31)))
2070 (set-module-kind! m 'directory)
2071 (set-module-name! m (append (module-name cur)
2073 (module-define-submodule! cur head m)
2075 (loop cur (car tail) (cdr tail)))))))
2078 (define (local-ref names) (nested-ref (current-module) names))
2079 (define (local-set! names val) (nested-set! (current-module) names val))
2080 (define (local-define names val) (nested-define! (current-module) names val))
2081 (define (local-remove names) (nested-remove! (current-module) names))
2082 (define (local-ref-module names) (nested-ref-module (current-module) names))
2083 (define (local-define-module names mod) (nested-define-module! (current-module) names mod))
2089 ;;; {The (guile) module}
2091 ;;; The standard module, which has the core Guile bindings. Also called the
2092 ;;; "root module", as it is imported by many other modules, but it is not
2093 ;;; necessarily the root of anything; and indeed, the module named '() might be
2094 ;;; better thought of as a root.
2097 (define (set-system-module! m s)
2098 (set-procedure-property! (module-eval-closure m) 'system-module s))
2099 (define the-root-module (make-root-module))
2100 (define the-scm-module (make-scm-module))
2101 (set-module-public-interface! the-root-module the-scm-module)
2102 (set-module-name! the-root-module '(guile))
2103 (set-module-name! the-scm-module '(guile))
2104 (set-module-kind! the-scm-module 'interface)
2105 (set-system-module! the-root-module #t)
2106 (set-system-module! the-scm-module #t)
2111 ;; Now that we have a root module, even though modules aren't fully booted,
2112 ;; expand the definition of resolve-module.
2114 (define (resolve-module name . args)
2115 (if (equal? name '(guile))
2117 (error "unexpected module to resolve during module boot" name)))
2119 ;; Cheat. These bindings are needed by modules.c, but we don't want
2120 ;; to move their real definition here because that would be unnatural.
2122 (define process-define-module #f)
2123 (define process-use-modules #f)
2124 (define module-export! #f)
2125 (define default-duplicate-binding-procedures #f)
2127 ;; This boots the module system. All bindings needed by modules.c
2128 ;; must have been defined by now.
2130 (set-current-module the-root-module)
2135 ;; Now that modules are booted, give module-name its final definition.
2138 (let ((accessor (record-accessor module-type 'name)))
2141 (let ((name (list (gensym))))
2142 ;; Name MOD and bind it in the module root so that it's visible to
2143 ;; `resolve-module'. This is important as `psyntax' stores module
2144 ;; names and relies on being able to `resolve-module' them.
2145 (set-module-name! mod name)
2146 (nested-define-module! (resolve-module '() #f) name mod)
2149 (define (make-modules-in module name)
2150 (or (nested-ref-module module name)
2151 (let ((m (make-module 31)))
2152 (set-module-kind! m 'directory)
2153 (set-module-name! m (append (module-name module) name))
2154 (nested-define-module! module name m)
2157 (define (beautify-user-module! module)
2158 (let ((interface (module-public-interface module)))
2159 (if (or (not interface)
2160 (eq? interface module))
2161 (let ((interface (make-module 31)))
2162 (set-module-name! interface (module-name module))
2163 (set-module-version! interface (module-version module))
2164 (set-module-kind! interface 'interface)
2165 (set-module-public-interface! module interface))))
2166 (if (and (not (memq the-scm-module (module-uses module)))
2167 (not (eq? module the-root-module)))
2168 ;; Import the default set of bindings (from the SCM module) in MODULE.
2169 (module-use! module the-scm-module)))
2171 (define (version-matches? version-ref target)
2172 (define (sub-versions-match? v-refs t)
2173 (define (sub-version-matches? v-ref t)
2174 (let ((matches? (lambda (v) (sub-version-matches? v t))))
2176 ((number? v-ref) (eqv? v-ref t))
2179 ((>=) (>= t (cadr v-ref)))
2180 ((<=) (<= t (cadr v-ref)))
2181 ((and) (and-map matches? (cdr v-ref)))
2182 ((or) (or-map matches? (cdr v-ref)))
2183 ((not) (not (matches? (cadr v-ref))))
2184 (else (error "Invalid sub-version reference" v-ref))))
2185 (else (error "Invalid sub-version reference" v-ref)))))
2187 (and (not (null? t))
2188 (sub-version-matches? (car v-refs) (car t))
2189 (sub-versions-match? (cdr v-refs) (cdr t)))))
2191 (let ((matches? (lambda (v) (version-matches? v target))))
2192 (or (null? version-ref)
2193 (case (car version-ref)
2194 ((and) (and-map matches? (cdr version-ref)))
2195 ((or) (or-map matches? (cdr version-ref)))
2196 ((not) (not (matches? (cadr version-ref))))
2197 (else (sub-versions-match? version-ref target))))))
2199 (define (find-versioned-module dir-hint name version-ref roots)
2200 (define (subdir-pair-less pair1 pair2)
2201 (define (numlist-less lst1 lst2)
2203 (and (not (null? lst1))
2204 (cond ((> (car lst1) (car lst2)) #t)
2205 ((< (car lst1) (car lst2)) #f)
2206 (else (numlist-less (cdr lst1) (cdr lst2)))))))
2207 (not (numlist-less (car pair2) (car pair1))))
2208 (define (match-version-and-file pair)
2209 (and (version-matches? version-ref (car pair))
2211 (filter (lambda (file)
2212 (let ((s (false-if-exception (stat file))))
2213 (and s (eq? (stat:type s) 'regular))))
2215 (string-append (cdr pair) name ext))
2216 %load-extensions))))
2217 (and (not (null? filenames))
2218 (cons (car pair) (car filenames))))))
2220 (define (match-version-recursive root-pairs leaf-pairs)
2221 (define (filter-subdirs root-pairs ret)
2222 (define (filter-subdir root-pair dstrm subdir-pairs)
2223 (let ((entry (readdir dstrm)))
2224 (if (eof-object? entry)
2226 (let* ((subdir (string-append (cdr root-pair) entry))
2227 (num (string->number entry))
2228 (num (and num (exact? num) (append (car root-pair)
2230 (if (and num (eq? (stat:type (stat subdir)) 'directory))
2232 root-pair dstrm (cons (cons num (string-append subdir "/"))
2234 (filter-subdir root-pair dstrm subdir-pairs))))))
2236 (or (and (null? root-pairs) ret)
2237 (let* ((rp (car root-pairs))
2238 (dstrm (false-if-exception (opendir (cdr rp)))))
2240 (let ((subdir-pairs (filter-subdir rp dstrm '())))
2242 (filter-subdirs (cdr root-pairs)
2243 (or (and (null? subdir-pairs) ret)
2244 (append ret subdir-pairs))))
2245 (filter-subdirs (cdr root-pairs) ret)))))
2247 (or (and (null? root-pairs) leaf-pairs)
2248 (let ((matching-subdir-pairs (filter-subdirs root-pairs '())))
2249 (match-version-recursive
2250 matching-subdir-pairs
2251 (append leaf-pairs (filter pair? (map match-version-and-file
2252 matching-subdir-pairs)))))))
2253 (define (make-root-pair root)
2254 (cons '() (string-append root "/" dir-hint)))
2256 (let* ((root-pairs (map make-root-pair roots))
2257 (matches (if (null? version-ref)
2258 (filter pair? (map match-version-and-file root-pairs))
2260 (matches (append matches (match-version-recursive root-pairs '()))))
2261 (and (null? matches) (error "No matching modules found."))
2262 (cdar (sort matches subdir-pair-less))))
2264 (define (make-fresh-user-module)
2265 (let ((m (make-module)))
2266 (beautify-user-module! m)
2269 ;; NOTE: This binding is used in libguile/modules.c.
2271 (define resolve-module
2272 (let ((root (make-module)))
2273 (set-module-name! root '())
2274 ;; Define the-root-module as '(guile).
2275 (module-define-submodule! root 'guile the-root-module)
2277 (lambda* (name #:optional (autoload #t) (version #f) #:key (ensure #t))
2278 (let ((already (nested-ref-module root name)))
2281 (or (not autoload) (module-public-interface already)))
2282 ;; A hit, a palpable hit.
2284 (not (version-matches? version (module-version already))))
2285 (error "incompatible module version already loaded" name))
2288 ;; Try to autoload the module, and recurse.
2289 (try-load-module name version)
2290 (resolve-module name #f #:ensure ensure))
2292 ;; No module found (or if one was, it had no public interface), and
2293 ;; we're not autoloading. Make an empty module if #:ensure is true.
2296 (make-modules-in root name)))))))))
2299 (define (try-load-module name version)
2300 (try-module-autoload name version))
2302 (define (purify-module! module)
2303 "Removes bindings in MODULE which are inherited from the (guile) module."
2304 (let ((use-list (module-uses module)))
2305 (if (and (pair? use-list)
2306 (eq? (car (last-pair use-list)) the-scm-module))
2307 (set-module-uses! module (reverse (cdr (reverse use-list)))))))
2309 ;; Return a module that is an interface to the module designated by
2312 ;; `resolve-interface' takes four keyword arguments:
2314 ;; #:select SELECTION
2316 ;; SELECTION is a list of binding-specs to be imported; A binding-spec
2317 ;; is either a symbol or a pair of symbols (ORIG . SEEN), where ORIG
2318 ;; is the name in the used module and SEEN is the name in the using
2319 ;; module. Note that SEEN is also passed through RENAMER, below. The
2320 ;; default is to select all bindings. If you specify no selection but
2321 ;; a renamer, only the bindings that already exist in the used module
2322 ;; are made available in the interface. Bindings that are added later
2323 ;; are not picked up.
2327 ;; BINDINGS is a list of bindings which should not be imported.
2331 ;; PREFIX is a symbol that will be appended to each exported name.
2332 ;; The default is to not perform any renaming.
2334 ;; #:renamer RENAMER
2336 ;; RENAMER is a procedure that takes a symbol and returns its new
2337 ;; name. The default is not perform any renaming.
2339 ;; Signal "no code for module" error if module name is not resolvable
2340 ;; or its public interface is not available. Signal "no binding"
2341 ;; error if selected binding does not exist in the used module.
2343 (define* (resolve-interface name #:key
2348 (symbol-prefix-proc prefix)
2351 (let* ((module (resolve-module name #t version #:ensure #f))
2352 (public-i (and module (module-public-interface module))))
2353 (and (or (not module) (not public-i))
2354 (error "no code for module" name))
2355 (if (and (not select) (null? hide) (eq? renamer identity))
2357 (let ((selection (or select (module-map (lambda (sym var) sym)
2359 (custom-i (make-module 31)))
2360 (set-module-kind! custom-i 'custom-interface)
2361 (set-module-name! custom-i name)
2362 ;; XXX - should use a lazy binder so that changes to the
2363 ;; used module are picked up automatically.
2364 (for-each (lambda (bspec)
2365 (let* ((direct? (symbol? bspec))
2366 (orig (if direct? bspec (car bspec)))
2367 (seen (if direct? bspec (cdr bspec)))
2368 (var (or (module-local-variable public-i orig)
2369 (module-local-variable module orig)
2371 ;; fixme: format manually for now
2373 #f "no binding `~A' in module ~A"
2375 (if (memq orig hide)
2376 (set! hide (delq! orig hide))
2377 (module-add! custom-i
2381 ;; Check that we are not hiding bindings which don't exist
2382 (for-each (lambda (binding)
2383 (if (not (module-local-variable public-i binding))
2386 #f "no binding `~A' to hide in module ~A"
2391 (define (symbol-prefix-proc prefix)
2393 (symbol-append prefix symbol)))
2395 ;; This function is called from "modules.c". If you change it, be
2396 ;; sure to update "modules.c" as well.
2398 (define (process-define-module args)
2399 (let* ((module-id (car args))
2400 (module (resolve-module module-id #f))
2402 (unrecognized (lambda (arg)
2403 (error "unrecognized define-module argument" arg))))
2404 (beautify-user-module! module)
2405 (let loop ((kws kws)
2406 (reversed-interfaces '())
2413 (call-with-deferred-observers
2415 (module-use-interfaces! module (reverse reversed-interfaces))
2416 (module-export! module exports)
2417 (module-replace! module replacements)
2418 (module-re-export! module re-exports)
2419 (if (not (null? autoloads))
2420 (apply module-autoload! module autoloads))))
2422 ((#:use-module #:use-syntax)
2423 (or (pair? (cdr kws))
2426 ((equal? (caadr kws) '(ice-9 syncase))
2427 (issue-deprecation-warning
2428 "(ice-9 syncase) is deprecated. Support for syntax-case is now in Guile core.")
2436 (let* ((interface-args (cadr kws))
2437 (interface (apply resolve-interface interface-args)))
2438 (and (eq? (car kws) #:use-syntax)
2439 (or (symbol? (caar interface-args))
2440 (error "invalid module name for use-syntax"
2441 (car interface-args)))
2442 (set-module-transformer!
2444 (module-ref interface
2445 (car (last-pair (car interface-args)))
2448 (cons interface reversed-interfaces)
2454 (or (and (pair? (cdr kws)) (pair? (cddr kws)))
2461 (let ((name (cadr kws))
2462 (bindings (caddr kws)))
2463 (cons* name bindings autoloads))))
2465 (set-system-module! module #t)
2466 (loop (cdr kws) reversed-interfaces exports re-exports
2467 replacements autoloads))
2469 (purify-module! module)
2470 (loop (cdr kws) reversed-interfaces exports re-exports
2471 replacements autoloads))
2473 (or (pair? (cdr kws))
2475 (let ((version (cadr kws)))
2476 (set-module-version! module version)
2477 (set-module-version! (module-public-interface module) version))
2478 (loop (cddr kws) reversed-interfaces exports re-exports
2479 replacements autoloads))
2481 (if (not (pair? (cdr kws)))
2483 (set-module-duplicates-handlers!
2485 (lookup-duplicates-handlers (cadr kws)))
2486 (loop (cddr kws) reversed-interfaces exports re-exports
2487 replacements autoloads))
2488 ((#:export #:export-syntax)
2489 (or (pair? (cdr kws))
2493 (append (cadr kws) exports)
2497 ((#:re-export #:re-export-syntax)
2498 (or (pair? (cdr kws))
2503 (append (cadr kws) re-exports)
2506 ((#:replace #:replace-syntax)
2507 (or (pair? (cdr kws))
2513 (append (cadr kws) replacements)
2516 (or (pair? (cdr kws))
2518 (set-module-filename! module (cadr kws))
2526 (unrecognized kws)))))
2527 (run-hook module-defined-hook module)
2530 ;; `module-defined-hook' is a hook that is run whenever a new module
2531 ;; is defined. Its members are called with one argument, the new
2533 (define module-defined-hook (make-hook 1))
2540 (define (make-autoload-interface module name bindings)
2541 (let ((b (lambda (a sym definep)
2542 (and (memq sym bindings)
2543 (let ((i (module-public-interface (resolve-module name))))
2545 (error "missing interface for module" name))
2546 (let ((autoload (memq a (module-uses module))))
2547 ;; Replace autoload-interface with actual interface if
2548 ;; that has not happened yet.
2549 (if (pair? autoload)
2550 (set-car! autoload i)))
2551 (module-local-variable i sym))))))
2552 (module-constructor (make-hash-table 0) '() b #f #f name 'autoload #f
2553 (make-hash-table 0) '() (make-weak-value-hash-table 31) #f
2554 (make-hash-table 0) #f #f #f)))
2556 (define (module-autoload! module . args)
2557 "Have @var{module} automatically load the module named @var{name} when one
2558 of the symbols listed in @var{bindings} is looked up. @var{args} should be a
2559 list of module-name/binding-list pairs, e.g., as in @code{(module-autoload!
2560 module '(ice-9 q) '(make-q q-length))}."
2561 (let loop ((args args))
2565 (error "invalid name+binding autoload list" args))
2567 (let ((name (car args))
2568 (bindings (cadr args)))
2569 (module-use! module (make-autoload-interface module
2571 (loop (cddr args)))))))
2576 ;;; {Autoloading modules}
2579 (define autoloads-in-progress '())
2581 ;; This function is called from "modules.c". If you change it, be
2582 ;; sure to update "modules.c" as well.
2584 (define* (try-module-autoload module-name #:optional version)
2585 (let* ((reverse-name (reverse module-name))
2586 (name (symbol->string (car reverse-name)))
2587 (dir-hint-module-name (reverse (cdr reverse-name)))
2588 (dir-hint (apply string-append
2590 (string-append (symbol->string elt) "/"))
2591 dir-hint-module-name))))
2592 (resolve-module dir-hint-module-name #f)
2593 (and (not (autoload-done-or-in-progress? dir-hint name))
2596 (lambda () (autoload-in-progress! dir-hint name))
2598 (with-fluids ((current-reader #f))
2599 (save-module-excursion
2602 (load (find-versioned-module
2603 dir-hint name version %load-path))
2604 (primitive-load-path (in-vicinity dir-hint name) #f))
2606 (lambda () (set-autoloaded! dir-hint name didit)))
2611 ;;; {Dynamic linking of modules}
2614 (define autoloads-done '((guile . guile)))
2616 (define (autoload-done-or-in-progress? p m)
2617 (let ((n (cons p m)))
2618 (->bool (or (member n autoloads-done)
2619 (member n autoloads-in-progress)))))
2621 (define (autoload-done! p m)
2622 (let ((n (cons p m)))
2623 (set! autoloads-in-progress
2624 (delete! n autoloads-in-progress))
2625 (or (member n autoloads-done)
2626 (set! autoloads-done (cons n autoloads-done)))))
2628 (define (autoload-in-progress! p m)
2629 (let ((n (cons p m)))
2630 (set! autoloads-done
2631 (delete! n autoloads-done))
2632 (set! autoloads-in-progress (cons n autoloads-in-progress))))
2634 (define (set-autoloaded! p m done?)
2636 (autoload-done! p m)
2637 (let ((n (cons p m)))
2638 (set! autoloads-done (delete! n autoloads-done))
2639 (set! autoloads-in-progress (delete! n autoloads-in-progress)))))
2643 ;;; {Run-time options}
2646 (defmacro define-option-interface (option-group)
2647 (let* ((option-name 'car)
2648 (option-value 'cadr)
2649 (option-documentation 'caddr)
2651 ;; Below follow the macros defining the run-time option interfaces.
2653 (make-options (lambda (interface)
2655 (cond ((null? args) (,interface))
2657 (,interface (car args)) (,interface))
2660 (display (,option-name option))
2661 (if (< (string-length
2662 (symbol->string (,option-name option)))
2666 (display (,option-value option))
2668 (display (,option-documentation option))
2670 (,interface #t)))))))
2672 (make-enable (lambda (interface)
2674 (,interface (append flags (,interface)))
2677 (make-disable (lambda (interface)
2679 (let ((options (,interface)))
2680 (for-each (lambda (flag)
2681 (set! options (delq! flag options)))
2683 (,interface options)
2685 (let* ((interface (car option-group))
2686 (options/enable/disable (cadr option-group)))
2688 (define ,(car options/enable/disable)
2689 ,(make-options interface))
2690 (define ,(cadr options/enable/disable)
2691 ,(make-enable interface))
2692 (define ,(caddr options/enable/disable)
2693 ,(make-disable interface))
2694 (defmacro ,(caaddr option-group) (opt val)
2695 `(,',(car options/enable/disable)
2696 (append (,',(car options/enable/disable))
2697 (list ',opt ,val))))))))
2699 (define-option-interface
2700 (eval-options-interface
2701 (eval-options eval-enable eval-disable)
2704 (define-option-interface
2705 (debug-options-interface
2706 (debug-options debug-enable debug-disable)
2709 (define-option-interface
2710 (evaluator-traps-interface
2711 (traps trap-enable trap-disable)
2714 (define-option-interface
2715 (read-options-interface
2716 (read-options read-enable read-disable)
2719 (define-option-interface
2720 (print-options-interface
2721 (print-options print-enable print-disable)
2729 (define (repl read evaler print)
2730 (let loop ((source (read (current-input-port))))
2731 (print (evaler source))
2732 (loop (read (current-input-port)))))
2734 ;; A provisional repl that acts like the SCM repl:
2736 (define scm-repl-silent #f)
2737 (define (assert-repl-silence v) (set! scm-repl-silent v))
2739 (define *unspecified* (if #f #f))
2740 (define (unspecified? v) (eq? v *unspecified*))
2742 (define scm-repl-print-unspecified #f)
2743 (define (assert-repl-print-unspecified v) (set! scm-repl-print-unspecified v))
2745 (define scm-repl-verbose #f)
2746 (define (assert-repl-verbosity v) (set! scm-repl-verbose v))
2748 (define scm-repl-prompt "guile> ")
2750 (define (set-repl-prompt! v) (set! scm-repl-prompt v))
2752 (define (default-pre-unwind-handler key . args)
2753 ;; Narrow by two more frames: this one, and the throw handler.
2755 (apply throw key args))
2758 (define (pre-unwind-handler-dispatch key . args)
2759 (apply default-pre-unwind-handler key args)))
2761 (define abort-hook (make-hook))
2763 ;; these definitions are used if running a script.
2764 ;; otherwise redefined in error-catching-loop.
2765 (define (set-batch-mode?! arg) #t)
2766 (define (batch-mode?) #t)
2768 ;;(define the-last-stack (make-fluid)) Defined by scm_init_backtrace ()
2769 (define before-signal-stack (make-fluid))
2770 ;; FIXME: stack-saved? is broken in the presence of threads.
2771 (define stack-saved? #f)
2773 (define (save-stack . narrowing)
2774 (if (not stack-saved?)
2776 (let ((stacks (fluid-ref %stacks)))
2777 (fluid-set! the-last-stack
2778 ;; (make-stack obj inner outer inner outer ...)
2780 ;; In this case, cut away the make-stack frame, the
2781 ;; save-stack frame, and then narrow as specified by the
2782 ;; user, delimited by the nearest start-stack invocation,
2784 (apply make-stack #t
2786 (if (pair? stacks) (cdar stacks) 0)
2788 (set! stack-saved? #t))))
2790 (define before-error-hook (make-hook))
2791 (define after-error-hook (make-hook))
2792 (define before-backtrace-hook (make-hook))
2793 (define after-backtrace-hook (make-hook))
2795 (define has-shown-debugger-hint? #f)
2797 (define (handle-system-error key . args)
2798 (let ((cep (current-error-port)))
2799 (cond ((not (stack? (fluid-ref the-last-stack))))
2800 ((memq 'backtrace (debug-options-interface))
2801 (let ((highlights (if (or (eq? key 'wrong-type-arg)
2802 (eq? key 'out-of-range))
2805 (run-hook before-backtrace-hook)
2807 (display "Backtrace:\n")
2808 (display-backtrace (fluid-ref the-last-stack) cep
2811 (run-hook after-backtrace-hook))))
2812 (run-hook before-error-hook)
2813 (apply display-error (fluid-ref the-last-stack) cep args)
2814 (run-hook after-error-hook)
2816 (throw 'abort key)))
2818 (define (quit . args)
2819 (apply throw 'quit args))
2823 (define (gc-run-time)
2824 (cdr (assq 'gc-time-taken (gc-stats))))
2826 (define before-read-hook (make-hook))
2827 (define after-read-hook (make-hook))
2828 (define before-eval-hook (make-hook 1))
2829 (define after-eval-hook (make-hook 1))
2830 (define before-print-hook (make-hook 1))
2831 (define after-print-hook (make-hook 1))
2833 ;;; The default repl-reader function. We may override this if we've
2834 ;;; the readline library.
2836 (lambda* (prompt #:optional (reader (fluid-ref current-reader)))
2837 (if (not (char-ready?))
2838 (display (if (string? prompt) prompt (prompt))))
2840 (run-hook before-read-hook)
2841 ((or reader read) (current-input-port))))
2846 ;;; {IOTA functions: generating lists of numbers}
2850 (let loop ((count (1- n)) (result '()))
2851 (if (< count 0) result
2852 (loop (1- count) (cons count result)))))
2858 ;;; Similar to `begin' but returns a list of the results of all constituent
2859 ;;; forms instead of the result of the last form.
2860 ;;; (The definition relies on the current left-to-right
2861 ;;; order of evaluation of operands in applications.)
2864 (defmacro collect forms
2871 ;;; with `continue' and `break'.
2874 ;; The inner `do' loop avoids re-establishing a catch every iteration,
2875 ;; that's only necessary if continue is actually used. A new key is
2876 ;; generated every time, so break and continue apply to their originating
2877 ;; `while' even when recursing.
2879 ;; FIXME: This macro is unintentionally unhygienic with respect to let,
2880 ;; make-symbol, do, throw, catch, lambda, and not.
2882 (define-macro (while cond . body)
2883 (let ((keyvar (make-symbol "while-keyvar")))
2884 `(let ((,keyvar (make-symbol "while-key")))
2888 (let ((break (lambda () (throw ,keyvar #t)))
2889 (continue (lambda () (throw ,keyvar #f))))
2900 ;;; {Module System Macros}
2903 ;; Return a list of expressions that evaluate to the appropriate
2904 ;; arguments for resolve-interface according to SPEC.
2908 (if (memq 'prefix (read-options))
2909 (error "boot-9 must be compiled with #:kw, not :kw")))
2911 (define (keyword-like-symbol->keyword sym)
2912 (symbol->keyword (string->symbol (substring (symbol->string sym) 1))))
2914 ;; FIXME: we really need to clean up the guts of the module system.
2915 ;; We can compile to something better than process-define-module.
2916 (define-syntax define-module
2918 (define (keyword-like? stx)
2919 (let ((dat (syntax->datum stx)))
2921 (eqv? (string-ref (symbol->string dat) 0) #\:))))
2922 (define (->keyword sym)
2923 (symbol->keyword (string->symbol (substring (symbol->string sym) 1))))
2925 (define (quotify-iface args)
2926 (let loop ((in args) (out '()))
2929 ;; The user wanted #:foo, but wrote :foo. Fix it.
2930 ((sym . in) (keyword-like? #'sym)
2931 (loop #`(#,(->keyword (syntax->datum #'sym)) . in) out))
2932 ((kw . in) (not (keyword? (syntax->datum #'kw)))
2933 (syntax-violation 'define-module "expected keyword arg" x #'kw))
2934 ((#:renamer renamer . in)
2935 (loop #'in (cons* #'renamer #:renamer out)))
2937 (loop #'in (cons* #''val #'kw out))))))
2939 (define (quotify args)
2940 ;; Just quote everything except #:use-module and #:use-syntax. We
2941 ;; need to know about all arguments regardless since we want to turn
2942 ;; symbols that look like keywords into real keywords, and the
2943 ;; keyword args in a define-module form are not regular
2944 ;; (i.e. no-backtrace doesn't take a value).
2945 (let loop ((in args) (out '()))
2948 ;; The user wanted #:foo, but wrote :foo. Fix it.
2949 ((sym . in) (keyword-like? #'sym)
2950 (loop #`(#,(->keyword (syntax->datum #'sym)) . in) out))
2951 ((kw . in) (not (keyword? (syntax->datum #'kw)))
2952 (syntax-violation 'define-module "expected keyword arg" x #'kw))
2953 ((#:no-backtrace . in)
2954 (loop #'in (cons #:no-backtrace out)))
2956 (loop #'in (cons #:pure out)))
2958 (syntax-violation 'define-module "keyword arg without value" x #'kw))
2959 ((use-module (name name* ...) . in)
2960 (and (memq (syntax->datum #'use-module) '(#:use-module #:use-syntax))
2961 (and-map symbol? (syntax->datum #'(name name* ...))))
2963 (cons* #''((name name* ...))
2966 ((use-module ((name name* ...) arg ...) . in)
2967 (and (memq (syntax->datum #'use-module) '(#:use-module #:use-syntax))
2968 (and-map symbol? (syntax->datum #'(name name* ...))))
2970 (cons* #`(list '(name name* ...) #,@(quotify-iface #'(arg ...)))
2973 ((#:autoload name bindings . in)
2974 (loop #'in (cons* #''bindings #''name #:autoload out)))
2976 (loop #'in (cons* #''val #'kw out))))))
2979 ((_ (name name* ...) arg ...)
2980 (with-syntax (((quoted-arg ...) (quotify #'(arg ...))))
2981 #'(eval-when (eval load compile expand)
2982 (let ((m (process-define-module
2983 (list '(name name* ...)
2984 #:filename (assq-ref
2985 (or (current-source-location) '())
2988 (set-current-module m)
2991 ;; The guts of the use-modules macro. Add the interfaces of the named
2992 ;; modules to the use-list of the current module, in order.
2994 ;; This function is called by "modules.c". If you change it, be sure
2995 ;; to change scm_c_use_module as well.
2997 (define (process-use-modules module-interface-args)
2998 (let ((interfaces (map (lambda (mif-args)
2999 (or (apply resolve-interface mif-args)
3000 (error "no such module" mif-args)))
3001 module-interface-args)))
3002 (call-with-deferred-observers
3004 (module-use-interfaces! (current-module) interfaces)))))
3006 (define-syntax use-modules
3008 (define (keyword-like? stx)
3009 (let ((dat (syntax->datum stx)))
3011 (eqv? (string-ref (symbol->string dat) 0) #\:))))
3012 (define (->keyword sym)
3013 (symbol->keyword (string->symbol (substring (symbol->string sym) 1))))
3015 (define (quotify-iface args)
3016 (let loop ((in args) (out '()))
3019 ;; The user wanted #:foo, but wrote :foo. Fix it.
3020 ((sym . in) (keyword-like? #'sym)
3021 (loop #`(#,(->keyword (syntax->datum #'sym)) . in) out))
3022 ((kw . in) (not (keyword? (syntax->datum #'kw)))
3023 (syntax-violation 'define-module "expected keyword arg" x #'kw))
3024 ((#:renamer renamer . in)
3025 (loop #'in (cons* #'renamer #:renamer out)))
3027 (loop #'in (cons* #''val #'kw out))))))
3029 (define (quotify specs)
3030 (let lp ((in specs) (out '()))
3033 (((name name* ...) . in)
3034 (and-map symbol? (syntax->datum #'(name name* ...)))
3035 (lp #'in (cons #''((name name* ...)) out)))
3036 ((((name name* ...) arg ...) . in)
3037 (and-map symbol? (syntax->datum #'(name name* ...)))
3038 (with-syntax (((quoted-arg ...) (quotify-iface #'(arg ...))))
3039 (lp #'in (cons #`(list '(name name* ...) quoted-arg ...)
3044 (with-syntax (((quoted-args ...) (quotify #'(spec ...))))
3045 #'(eval-when (eval load compile expand)
3046 (process-use-modules (list quoted-args ...))
3049 (define-syntax use-syntax
3053 (eval-when (eval load compile expand)
3054 (issue-deprecation-warning
3055 "`use-syntax' is deprecated. Please contact guile-devel for more info."))
3056 (use-modules spec ...)))))
3058 (include-from-path "ice-9/r6rs-libraries")
3060 (define-syntax define-private
3065 (define-syntax define-public
3067 ((_ (name . args) . body)
3068 (define-public name (lambda args . body)))
3074 (define-syntax defmacro-public
3076 ((_ name args . body)
3078 (defmacro name args . body)
3079 (export-syntax name)))))
3081 ;; And now for the most important macro.
3084 ((_ formals body ...)
3085 (lambda formals body ...))))
3088 ;; Export a local variable
3090 ;; This function is called from "modules.c". If you change it, be
3091 ;; sure to update "modules.c" as well.
3093 (define (module-export! m names)
3094 (let ((public-i (module-public-interface m)))
3095 (for-each (lambda (name)
3096 (let* ((internal-name (if (pair? name) (car name) name))
3097 (external-name (if (pair? name) (cdr name) name))
3098 (var (module-ensure-local-variable! m internal-name)))
3099 (module-add! public-i external-name var)))
3102 (define (module-replace! m names)
3103 (let ((public-i (module-public-interface m)))
3104 (for-each (lambda (name)
3105 (let* ((internal-name (if (pair? name) (car name) name))
3106 (external-name (if (pair? name) (cdr name) name))
3107 (var (module-ensure-local-variable! m internal-name)))
3108 (set-object-property! var 'replace #t)
3109 (module-add! public-i external-name var)))
3112 ;; Export all local variables from a module
3114 (define (module-export-all! mod)
3115 (define (fresh-interface!)
3116 (let ((iface (make-module)))
3117 (set-module-name! iface (module-name mod))
3118 ;; for guile 2: (set-module-version! iface (module-version mod))
3119 (set-module-kind! iface 'interface)
3120 (set-module-public-interface! mod iface)
3122 (let ((iface (or (module-public-interface mod)
3123 (fresh-interface!))))
3124 (set-module-obarray! iface (module-obarray mod))))
3126 ;; Re-export a imported variable
3128 (define (module-re-export! m names)
3129 (let ((public-i (module-public-interface m)))
3130 (for-each (lambda (name)
3131 (let* ((internal-name (if (pair? name) (car name) name))
3132 (external-name (if (pair? name) (cdr name) name))
3133 (var (module-variable m internal-name)))
3135 (error "Undefined variable:" internal-name))
3136 ((eq? var (module-local-variable m internal-name))
3137 (error "re-exporting local variable:" internal-name))
3139 (module-add! public-i external-name var)))))
3142 (define-syntax export
3145 (eval-when (eval load compile expand)
3146 (call-with-deferred-observers
3148 (module-export! (current-module) '(name ...))))))))
3150 (define-syntax re-export
3153 (eval-when (eval load compile expand)
3154 (call-with-deferred-observers
3156 (module-re-export! (current-module) '(name ...))))))))
3158 (define-syntax export-syntax
3161 (export name ...))))
3163 (define-syntax re-export-syntax
3166 (re-export name ...))))
3168 (define load load-module)
3175 (define make-mutable-parameter
3176 (let ((make (lambda (fluid converter)
3180 (fluid-set! fluid (converter (car args))))))))
3181 (lambda* (init #:optional (converter identity))
3182 (let ((fluid (make-fluid)))
3183 (fluid-set! fluid (converter init))
3184 (make fluid converter)))))
3188 ;;; {Handling of duplicate imported bindings}
3191 ;; Duplicate handlers take the following arguments:
3193 ;; module importing module
3194 ;; name conflicting name
3195 ;; int1 old interface where name occurs
3196 ;; val1 value of binding in old interface
3197 ;; int2 new interface where name occurs
3198 ;; val2 value of binding in new interface
3199 ;; var previous resolution or #f
3200 ;; val value of previous resolution
3202 ;; A duplicate handler can take three alternative actions:
3204 ;; 1. return #f => leave responsibility to next handler
3205 ;; 2. exit with an error
3206 ;; 3. return a variable resolving the conflict
3209 (define duplicate-handlers
3210 (let ((m (make-module 7)))
3212 (define (check module name int1 val1 int2 val2 var val)
3213 (scm-error 'misc-error
3215 "~A: `~A' imported from both ~A and ~A"
3216 (list (module-name module)
3222 (define (warn module name int1 val1 int2 val2 var val)
3223 (format (current-error-port)
3224 "WARNING: ~A: `~A' imported from both ~A and ~A\n"
3225 (module-name module)
3231 (define (replace module name int1 val1 int2 val2 var val)
3232 (let ((old (or (and var (object-property var 'replace) var)
3233 (module-variable int1 name)))
3234 (new (module-variable int2 name)))
3235 (if (object-property old 'replace)
3236 (and (or (eq? old new)
3237 (not (object-property new 'replace)))
3239 (and (object-property new 'replace)
3242 (define (warn-override-core module name int1 val1 int2 val2 var val)
3243 (and (eq? int1 the-scm-module)
3245 (format (current-error-port)
3246 "WARNING: ~A: imported module ~A overrides core binding `~A'\n"
3247 (module-name module)
3250 (module-local-variable int2 name))))
3252 (define (first module name int1 val1 int2 val2 var val)
3253 (or var (module-local-variable int1 name)))
3255 (define (last module name int1 val1 int2 val2 var val)
3256 (module-local-variable int2 name))
3258 (define (noop module name int1 val1 int2 val2 var val)
3261 (set-module-name! m 'duplicate-handlers)
3262 (set-module-kind! m 'interface)
3263 (module-define! m 'check check)
3264 (module-define! m 'warn warn)
3265 (module-define! m 'replace replace)
3266 (module-define! m 'warn-override-core warn-override-core)
3267 (module-define! m 'first first)
3268 (module-define! m 'last last)
3269 (module-define! m 'merge-generics noop)
3270 (module-define! m 'merge-accessors noop)
3273 (define (lookup-duplicates-handlers handler-names)
3275 (map (lambda (handler-name)
3276 (or (module-symbol-local-binding
3277 duplicate-handlers handler-name #f)
3278 (error "invalid duplicate handler name:"
3280 (if (list? handler-names)
3282 (list handler-names)))))
3284 (define default-duplicate-binding-procedures
3285 (make-mutable-parameter #f))
3287 (define default-duplicate-binding-handler
3288 (make-mutable-parameter '(replace warn-override-core warn last)
3289 (lambda (handler-names)
3290 (default-duplicate-binding-procedures
3291 (lookup-duplicates-handlers handler-names))
3296 ;;; {`cond-expand' for SRFI-0 support.}
3298 ;;; This syntactic form expands into different commands or
3299 ;;; definitions, depending on the features provided by the Scheme
3305 ;;; --> (cond-expand <cond-expand-clause>+)
3306 ;;; | (cond-expand <cond-expand-clause>* (else <command-or-definition>))
3307 ;;; <cond-expand-clause>
3308 ;;; --> (<feature-requirement> <command-or-definition>*)
3309 ;;; <feature-requirement>
3310 ;;; --> <feature-identifier>
3311 ;;; | (and <feature-requirement>*)
3312 ;;; | (or <feature-requirement>*)
3313 ;;; | (not <feature-requirement>)
3314 ;;; <feature-identifier>
3315 ;;; --> <a symbol which is the name or alias of a SRFI>
3317 ;;; Additionally, this implementation provides the
3318 ;;; <feature-identifier>s `guile' and `r5rs', so that programs can
3319 ;;; determine the implementation type and the supported standard.
3321 ;;; Currently, the following feature identifiers are supported:
3323 ;;; guile r5rs srfi-0 srfi-4 srfi-6 srfi-13 srfi-14 srfi-55 srfi-61
3325 ;;; Remember to update the features list when adding more SRFIs.
3328 (define %cond-expand-features
3329 ;; Adjust the above comment when changing this.
3333 srfi-0 ;; cond-expand itself
3334 srfi-4 ;; homogenous numeric vectors
3335 srfi-6 ;; open-input-string etc, in the guile core
3336 srfi-13 ;; string library
3337 srfi-14 ;; character sets
3338 srfi-55 ;; require-extension
3339 srfi-61 ;; general cond clause
3342 ;; This table maps module public interfaces to the list of features.
3344 (define %cond-expand-table (make-hash-table 31))
3346 ;; Add one or more features to the `cond-expand' feature list of the
3349 (define (cond-expand-provide module features)
3350 (let ((mod (module-public-interface module)))
3352 (hashq-set! %cond-expand-table mod
3353 (append (hashq-ref %cond-expand-table mod '())
3356 (define-macro (cond-expand . clauses)
3357 (let ((syntax-error (lambda (cl)
3358 (error "invalid clause in `cond-expand'" cl))))
3364 (or (memq clause %cond-expand-features)
3365 (let lp ((uses (module-uses (current-module))))
3368 (hashq-ref %cond-expand-table
3374 ((eq? 'and (car clause))
3375 (let lp ((l (cdr clause)))
3379 (and (test-clause (car l)) (lp (cdr l))))
3381 (syntax-error clause)))))
3382 ((eq? 'or (car clause))
3383 (let lp ((l (cdr clause)))
3387 (or (test-clause (car l)) (lp (cdr l))))
3389 (syntax-error clause)))))
3390 ((eq? 'not (car clause))
3391 (cond ((not (pair? (cdr clause)))
3392 (syntax-error clause))
3393 ((pair? (cddr clause))
3394 ((syntax-error clause))))
3395 (not (test-clause (cadr clause))))
3397 (syntax-error clause))))
3399 (syntax-error clause))))))
3400 (let lp ((c clauses))
3403 (error "Unfulfilled `cond-expand'"))
3406 ((not (pair? (car c)))
3407 (syntax-error (car c)))
3408 ((test-clause (caar c))
3409 `(begin ,@(cdar c)))
3410 ((eq? (caar c) 'else)
3413 `(begin ,@(cdar c)))
3417 ;; This procedure gets called from the startup code with a list of
3418 ;; numbers, which are the numbers of the SRFIs to be loaded on startup.
3420 (define (use-srfis srfis)
3421 (process-use-modules
3423 (list (list 'srfi (string->symbol
3424 (string-append "srfi-" (number->string num))))))
3429 ;;; srfi-55: require-extension
3432 (define-macro (require-extension extension-spec)
3433 ;; This macro only handles the srfi extension, which, at present, is
3434 ;; the only one defined by the standard.
3435 (if (not (pair? extension-spec))
3436 (scm-error 'wrong-type-arg "require-extension"
3437 "Not an extension: ~S" (list extension-spec) #f))
3438 (let ((extension (car extension-spec))
3439 (extension-args (cdr extension-spec)))
3442 (let ((use-list '()))
3445 (if (not (integer? i))
3446 (scm-error 'wrong-type-arg "require-extension"
3447 "Invalid srfi name: ~S" (list i) #f))
3448 (let ((srfi-sym (string->symbol
3449 (string-append "srfi-" (number->string i)))))
3450 (if (not (memq srfi-sym %cond-expand-features))
3451 (set! use-list (cons `(use-modules (srfi ,srfi-sym))
3454 (if (pair? use-list)
3455 ;; i.e. (begin (use-modules x) (use-modules y) (use-modules z))
3456 `(begin ,@(reverse! use-list)))))
3459 'wrong-type-arg "require-extension"
3460 "Not a recognized extension type: ~S" (list extension) #f)))))
3464 ;;; {Load emacs interface support if emacs option is given.}
3467 (define (named-module-use! user usee)
3468 (module-use! (resolve-module user) (resolve-interface usee)))
3470 (define (load-emacs-interface)
3471 (and (provided? 'debug-extensions)
3472 (debug-enable 'backtrace))
3473 (named-module-use! '(guile-user) '(ice-9 emacs)))
3477 (define using-readline?
3478 (let ((using-readline? (make-fluid)))
3479 (make-procedure-with-setter
3480 (lambda () (fluid-ref using-readline?))
3481 (lambda (v) (fluid-set! using-readline? v)))))
3484 (let ((guile-user-module (resolve-module '(guile-user))))
3486 ;; Load emacs interface support if emacs option is given.
3487 (if (and (module-defined? guile-user-module 'use-emacs-interface)
3488 (module-ref guile-user-module 'use-emacs-interface))
3489 (load-emacs-interface))
3491 ;; Use some convenient modules (in reverse order)
3493 (set-current-module guile-user-module)
3494 (process-use-modules
3499 (if (provided? 'regex)
3502 (if (provided? 'threads)
3503 '(((ice-9 threads)))
3505 ;; load debugger on demand
3506 (module-autoload! guile-user-module '(system vm debug) '(debug))
3508 ;; Note: SIGFPE, SIGSEGV and SIGBUS are actually "query-only" (see
3509 ;; scmsigs.c scm_sigaction_for_thread), so the handlers setup here have
3511 (let ((old-handlers #f)
3512 ;; We can't use @ here, as modules have been booted, but in Guile's
3513 ;; build the srfi-1 helper lib hasn't been built yet, which will
3514 ;; result in an error when (system repl repl) is loaded at compile
3515 ;; time (to see if it is a macro or not).
3516 (start-repl (module-ref (resolve-module '(system repl repl))
3518 (signals (if (provided? 'posix)
3519 `((,SIGINT . "User interrupt")
3520 (,SIGFPE . "Arithmetic error")
3522 . "Bad memory access (Segmentation violation)"))
3524 ;; no SIGBUS on mingw
3525 (if (defined? 'SIGBUS)
3526 (set! signals (acons SIGBUS "Bad memory access (bus error)"
3533 (let ((make-handler (lambda (msg)
3535 ;; Make a backup copy of the stack
3536 (fluid-set! before-signal-stack
3537 (fluid-ref the-last-stack))
3545 (map (lambda (sig-msg)
3546 (sigaction (car sig-msg)
3547 (make-handler (cdr sig-msg))))
3550 ;; the protected thunk.
3552 (let ((status (start-repl 'scheme)))
3553 (run-hook exit-hook)
3558 (map (lambda (sig-msg old-handler)
3559 (if (not (car old-handler))
3560 ;; restore original C handler.
3561 (sigaction (car sig-msg) #f)
3562 ;; restore Scheme handler, SIG_IGN or SIG_DFL.
3563 (sigaction (car sig-msg)
3565 (cdr old-handler))))
3566 signals old-handlers))))))
3568 ;;; This hook is run at the very end of an interactive session.
3570 (define exit-hook (make-hook))
3574 ;;; {Deprecated stuff}
3578 (module-use! the-scm-module (resolve-interface '(ice-9 deprecated))))
3582 ;;; Place the user in the guile-user module.
3586 (module-use! the-scm-module (resolve-interface '(srfi srfi-4)))
3588 (define-module (guile-user)
3589 #:autoload (system base compile) (compile))
3591 ;; Remain in the `(guile)' module at compilation-time so that the
3592 ;; `-Wunused-toplevel' warning works as expected.
3593 (eval-when (compile) (set-current-module the-root-module))
3595 ;;; boot-9.scm ends here