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))
260 (define (make-struct/no-tail vtable . args)
261 (apply make-struct vtable 0 args))
265 ;;; {and-map and or-map}
267 ;;; (and-map fn lst) is like (and (fn (car lst)) (fn (cadr lst)) (fn...) ...)
268 ;;; (or-map fn lst) is like (or (fn (car lst)) (fn (cadr lst)) (fn...) ...)
273 ;; Apply f to successive elements of l until exhaustion or f returns #f.
274 ;; If returning early, return #f. Otherwise, return the last value returned
275 ;; by f. If f has never been called because l is empty, return #t.
277 (define (and-map f lst)
278 (let loop ((result #t)
283 (loop (f (car l)) (cdr l))))))
287 ;; Apply f to successive elements of l until exhaustion or while f returns #f.
288 ;; If returning early, return the return value of f.
290 (define (or-map f lst)
291 (let loop ((result #f)
295 (loop (f (car l)) (cdr l))))))
299 ;; let format alias simple-format until the more complete version is loaded
301 (define format simple-format)
303 ;; this is scheme wrapping the C code so the final pred call is a tail call,
306 (lambda* (char_pred s #:optional (start 0) (end (string-length s)))
307 (if (and (procedure? char_pred)
309 (<= end (string-length s))) ;; let c-code handle range error
310 (or (string-any-c-code char_pred s start (1- end))
311 (char_pred (string-ref s (1- end))))
312 (string-any-c-code char_pred s start end))))
314 ;; this is scheme wrapping the C code so the final pred call is a tail call,
317 (lambda* (char_pred s #:optional (start 0) (end (string-length s)))
318 (if (and (procedure? char_pred)
320 (<= end (string-length s))) ;; let c-code handle range error
321 (and (string-every-c-code char_pred s start (1- end))
322 (char_pred (string-ref s (1- end))))
323 (string-every-c-code char_pred s start end))))
325 ;; A variant of string-fill! that we keep for compatability
327 (define (substring-fill! str start end fill)
328 (string-fill! str fill start end))
332 ;; Define a minimal stub of the module API for psyntax, before modules
334 (define (module-name x)
336 (define (module-define! module sym val)
337 (let ((v (hashq-ref (%get-pre-modules-obarray) sym)))
339 (variable-set! v val)
340 (hashq-set! (%get-pre-modules-obarray) sym
341 (make-variable val)))))
342 (define (module-ref module sym)
343 (let ((v (module-variable module sym)))
344 (if v (variable-ref v) (error "badness!" (pk module) (pk sym)))))
345 (define (resolve-module . args)
348 ;; API provided by psyntax
349 (define syntax-violation #f)
350 (define datum->syntax #f)
351 (define syntax->datum #f)
352 (define syntax-source #f)
353 (define identifier? #f)
354 (define generate-temporaries #f)
355 (define bound-identifier=? #f)
356 (define free-identifier=? #f)
358 ;; $sc-dispatch is an implementation detail of psyntax. It is used by
359 ;; expanded macros, to dispatch an input against a set of patterns.
360 (define $sc-dispatch #f)
363 (primitive-load-path "ice-9/psyntax-pp")
364 ;; The binding for `macroexpand' has now been overridden, making psyntax the
371 ((_ x y ...) (if x (and y ...) #f))))
377 ((_ x y ...) (let ((t x)) (if t t (or y ...))))))
379 ;; The "maybe-more" bits are something of a hack, so that we can support
380 ;; SRFI-61. Rewrites into a standalone syntax-case macro would be
383 (syntax-rules (=> else)
384 ((_ "maybe-more" test consequent)
385 (if test consequent))
387 ((_ "maybe-more" test consequent clause ...)
388 (if test consequent (cond clause ...)))
390 ((_ (else else1 else2 ...))
391 (begin else1 else2 ...))
393 ((_ (test => receiver) more-clause ...)
395 (cond "maybe-more" t (receiver t) more-clause ...)))
397 ((_ (generator guard => receiver) more-clause ...)
398 (call-with-values (lambda () generator)
401 (apply guard t) (apply receiver t) more-clause ...))))
403 ((_ (test => receiver ...) more-clause ...)
404 (syntax-violation 'cond "wrong number of receiver expressions"
405 '(test => receiver ...)))
406 ((_ (generator guard => receiver ...) more-clause ...)
407 (syntax-violation 'cond "wrong number of receiver expressions"
408 '(generator guard => receiver ...)))
410 ((_ (test) more-clause ...)
412 (cond "maybe-more" t t more-clause ...)))
414 ((_ (test body1 body2 ...) more-clause ...)
416 test (begin body1 body2 ...) more-clause ...))))
422 (let ((atom-key (key ...)))
423 (case atom-key clauses ...)))
425 (else result1 result2 ...))
426 (begin result1 result2 ...))
428 ((atoms ...) result1 result2 ...))
429 (if (memv key '(atoms ...))
430 (begin result1 result2 ...)))
432 ((atoms ...) result1 result2 ...)
434 (if (memv key '(atoms ...))
435 (begin result1 result2 ...)
436 (case key clause clauses ...)))))
440 ((do ((var init step ...) ...)
453 (loop (do "step" var step ...)
463 ((_ exp) (make-promise (lambda () exp)))))
465 (include-from-path "ice-9/quasisyntax")
467 (define-syntax current-source-location
471 (with-syntax ((s (datum->syntax x (syntax-source x))))
480 (define-syntax define-macro
484 ((_ (macro . args) doc body1 body ...)
485 (string? (syntax->datum #'doc))
486 #'(define-macro macro doc (lambda args body1 body ...)))
487 ((_ (macro . args) body ...)
488 #'(define-macro macro #f (lambda args body ...)))
489 ((_ macro doc transformer)
490 (or (string? (syntax->datum #'doc))
491 (not (syntax->datum #'doc)))
492 #'(define-syntax macro
495 #((macro-type . defmacro)
496 (defmacro-args args))
499 (let ((v (syntax->datum #'args)))
500 (datum->syntax y (apply transformer v)))))))))))
502 (define-syntax defmacro
504 "Define a defmacro, with the old lispy defun syntax."
506 ((_ macro args doc body1 body ...)
507 (string? (syntax->datum #'doc))
508 #'(define-macro macro doc (lambda args body1 body ...)))
509 ((_ macro args body ...)
510 #'(define-macro macro #f (lambda args body ...))))))
518 ;;; Depends on: defmacro
521 (defmacro begin-deprecated forms
522 (if (include-deprecated-features)
528 ;;; {Trivial Functions}
531 (define (identity x) x)
532 (define (and=> value procedure) (and value (procedure value)))
533 (define call/cc call-with-current-continuation)
535 (defmacro false-if-exception (expr)
538 ;; avoid saving backtraces inside false-if-exception
539 (with-fluids ((the-last-stack (fluid-ref the-last-stack)))
545 ;;; {General Properties}
548 ;; Properties are a lispy way to associate random info with random objects.
549 ;; Traditionally properties are implemented as an alist or a plist actually
550 ;; pertaining to the object in question.
552 ;; These "object properties" have the advantage that they can be associated with
553 ;; any object, even if the object has no plist. Object properties are good when
554 ;; you are extending pre-existing objects in unexpected ways. They also present
555 ;; a pleasing, uniform procedure-with-setter interface. But if you have a data
556 ;; type that always has properties, it's often still best to store those
557 ;; properties within the object itself.
559 (define (make-object-property)
560 (let ((prop (primitive-make-property #f)))
561 (make-procedure-with-setter
562 (lambda (obj) (primitive-property-ref prop obj))
563 (lambda (obj val) (primitive-property-set! prop obj val)))))
567 ;;; {Symbol Properties}
570 ;;; Symbol properties are something you see in old Lisp code. In most current
571 ;;; Guile code, symbols are not used as a data structure -- they are used as
572 ;;; keys into other data structures.
574 (define (symbol-property sym prop)
575 (let ((pair (assoc prop (symbol-pref sym))))
576 (and pair (cdr pair))))
578 (define (set-symbol-property! sym prop val)
579 (let ((pair (assoc prop (symbol-pref sym))))
582 (symbol-pset! sym (acons prop val (symbol-pref sym))))))
584 (define (symbol-property-remove! sym prop)
585 (let ((pair (assoc prop (symbol-pref sym))))
587 (symbol-pset! sym (delq! pair (symbol-pref sym))))))
594 (define (array-shape a)
595 (map (lambda (ind) (if (number? ind) (list 0 (+ -1 ind)) ind))
596 (array-dimensions a)))
603 ;;; It's much better if you can use lambda* / define*, of course.
605 (define (kw-arg-ref args kw)
606 (let ((rem (member kw args)))
607 (and rem (pair? (cdr rem)) (cadr rem))))
614 (define (struct-layout s)
615 (struct-ref (struct-vtable s) vtable-index-layout))
622 ;; Printing records: by default, records are printed as
624 ;; #<type-name field1: val1 field2: val2 ...>
626 ;; You can change that by giving a custom printing function to
627 ;; MAKE-RECORD-TYPE (after the list of field symbols). This function
628 ;; will be called like
630 ;; (<printer> object port)
632 ;; It should print OBJECT to PORT.
634 (define (inherit-print-state old-port new-port)
635 (if (get-print-state old-port)
636 (port-with-print-state new-port (get-print-state old-port))
639 ;; 0: type-name, 1: fields, 2: constructor
640 (define record-type-vtable
641 ;; FIXME: This should just call make-vtable, not make-vtable-vtable; but for
642 ;; that we need to expose the bare vtable-vtable to Scheme.
643 (make-vtable-vtable "prprpw" 0
645 (cond ((eq? s record-type-vtable)
646 (display "#<record-type-vtable>" p))
648 (display "#<record-type " p)
649 (display (record-type-name s) p)
652 (define (record-type? obj)
653 (and (struct? obj) (eq? record-type-vtable (struct-vtable obj))))
655 (define* (make-record-type type-name fields #:optional printer)
656 ;; Pre-generate constructors for nfields < 20.
657 (define-syntax make-constructor
659 (define *max-static-argument-count* 20)
660 (define (make-formals n)
666 (string (integer->char (+ (char->integer #\a) i)))))
670 ((_ rtd exp) (not (identifier? #'exp))
672 (make-constructor rtd n)))
676 (if (< n *max-static-argument-count*)
677 (cons (with-syntax (((formal ...) (make-formals n))
681 (make-struct rtd 0 formal ...))))
686 (if (= (length args) nfields)
687 (apply make-struct rtd 0 args)
688 (scm-error 'wrong-number-of-args
689 (format #f "make-~a" type-name)
690 "Wrong number of arguments" '() #f)))))))))
692 (define (default-record-printer s p)
694 (display (record-type-name (record-type-descriptor s)) p)
695 (let loop ((fields (record-type-fields (record-type-descriptor s)))
698 ((not (null? fields))
700 (display (car fields) p)
702 (display (struct-ref s off) p)
703 (loop (cdr fields) (+ 1 off)))))
706 (let ((rtd (make-struct record-type-vtable 0
709 (map (lambda (f) "pw") fields)))
710 (or printer default-record-printer)
712 (copy-tree fields))))
713 (struct-set! rtd (+ vtable-offset-user 2)
714 (make-constructor rtd (length fields)))
715 ;; Temporary solution: Associate a name to the record type descriptor
716 ;; so that the object system can create a wrapper class for it.
717 (set-struct-vtable-name! rtd (if (symbol? type-name)
719 (string->symbol type-name)))
722 (define (record-type-name obj)
723 (if (record-type? obj)
724 (struct-ref obj vtable-offset-user)
725 (error 'not-a-record-type obj)))
727 (define (record-type-fields obj)
728 (if (record-type? obj)
729 (struct-ref obj (+ 1 vtable-offset-user))
730 (error 'not-a-record-type obj)))
732 (define* (record-constructor rtd #:optional field-names)
733 (if (not field-names)
734 (struct-ref rtd (+ 2 vtable-offset-user))
736 `(lambda ,field-names
737 (make-struct ',rtd 0 ,@(map (lambda (f)
738 (if (memq f field-names)
741 (record-type-fields rtd)))))))
743 (define (record-predicate rtd)
744 (lambda (obj) (and (struct? obj) (eq? rtd (struct-vtable obj)))))
746 (define (%record-type-error rtd obj) ;; private helper
747 (or (eq? rtd (record-type-descriptor obj))
748 (scm-error 'wrong-type-arg "%record-type-check"
749 "Wrong type record (want `~S'): ~S"
750 (list (record-type-name rtd) obj)
753 (define (record-accessor rtd field-name)
754 (let ((pos (list-index (record-type-fields rtd) field-name)))
756 (error 'no-such-field field-name))
758 (if (eq? (struct-vtable obj) rtd)
760 (%record-type-error rtd obj)))))
762 (define (record-modifier rtd field-name)
763 (let ((pos (list-index (record-type-fields rtd) field-name)))
765 (error 'no-such-field field-name))
767 (if (eq? (struct-vtable obj) rtd)
768 (struct-set! obj pos val)
769 (%record-type-error rtd obj)))))
771 (define (record? obj)
772 (and (struct? obj) (record-type? (struct-vtable obj))))
774 (define (record-type-descriptor obj)
777 (error 'not-a-record obj)))
786 (define (->bool x) (not (not x)))
793 (define (symbol-append . args)
794 (string->symbol (apply string-append (map symbol->string args))))
796 (define (list->symbol . args)
797 (string->symbol (apply list->string args)))
799 (define (symbol . args)
800 (string->symbol (apply string args)))
807 (define (list-index l k)
813 (loop (+ n 1) (cdr l))))))
817 (if (provided? 'posix)
818 (primitive-load-path "ice-9/posix"))
820 (if (provided? 'socket)
821 (primitive-load-path "ice-9/networking"))
823 ;; For reference, Emacs file-exists-p uses stat in this same way.
825 (if (provided? 'posix)
827 (->bool (stat str #f)))
829 (let ((port (catch 'system-error (lambda () (open-file str OPEN_READ))
831 (if port (begin (close-port port) #t)
834 (define file-is-directory?
835 (if (provided? 'posix)
837 (eq? (stat:type (stat str)) 'directory))
839 (let ((port (catch 'system-error
840 (lambda () (open-file (string-append str "/.")
843 (if port (begin (close-port port) #t)
846 (define (system-error-errno args)
847 (if (eq? (car args) 'system-error)
848 (car (list-ref args 4))
860 (scm-error 'misc-error #f "?" #f #f))
863 (let ((msg (string-join (cons "~A" (make-list (length args) "~S")))))
864 (scm-error 'misc-error #f msg (cons message args) #f)))))
868 ;;; {Time Structures}
871 (define (tm:sec obj) (vector-ref obj 0))
872 (define (tm:min obj) (vector-ref obj 1))
873 (define (tm:hour obj) (vector-ref obj 2))
874 (define (tm:mday obj) (vector-ref obj 3))
875 (define (tm:mon obj) (vector-ref obj 4))
876 (define (tm:year obj) (vector-ref obj 5))
877 (define (tm:wday obj) (vector-ref obj 6))
878 (define (tm:yday obj) (vector-ref obj 7))
879 (define (tm:isdst obj) (vector-ref obj 8))
880 (define (tm:gmtoff obj) (vector-ref obj 9))
881 (define (tm:zone obj) (vector-ref obj 10))
883 (define (set-tm:sec obj val) (vector-set! obj 0 val))
884 (define (set-tm:min obj val) (vector-set! obj 1 val))
885 (define (set-tm:hour obj val) (vector-set! obj 2 val))
886 (define (set-tm:mday obj val) (vector-set! obj 3 val))
887 (define (set-tm:mon obj val) (vector-set! obj 4 val))
888 (define (set-tm:year obj val) (vector-set! obj 5 val))
889 (define (set-tm:wday obj val) (vector-set! obj 6 val))
890 (define (set-tm:yday obj val) (vector-set! obj 7 val))
891 (define (set-tm:isdst obj val) (vector-set! obj 8 val))
892 (define (set-tm:gmtoff obj val) (vector-set! obj 9 val))
893 (define (set-tm:zone obj val) (vector-set! obj 10 val))
895 (define (tms:clock obj) (vector-ref obj 0))
896 (define (tms:utime obj) (vector-ref obj 1))
897 (define (tms:stime obj) (vector-ref obj 2))
898 (define (tms:cutime obj) (vector-ref obj 3))
899 (define (tms:cstime obj) (vector-ref obj 4))
903 ;;; {File Descriptors and Ports}
906 (define file-position ftell)
907 (define* (file-set-position port offset #:optional (whence SEEK_SET))
908 (seek port offset whence))
910 (define (move->fdes fd/port fd)
911 (cond ((integer? fd/port)
912 (dup->fdes fd/port fd)
916 (primitive-move->fdes fd/port fd)
917 (set-port-revealed! fd/port 1)
920 (define (release-port-handle port)
921 (let ((revealed (port-revealed port)))
923 (set-port-revealed! port (- revealed 1)))))
928 (fdopen (dup->fdes port/fd) mode))
929 ((port/fd mode new-fd)
930 (let ((port (fdopen (dup->fdes port/fd new-fd) mode)))
931 (set-port-revealed! port 1)
937 (dup->port port/fd "r"))
939 (dup->port port/fd "r" new-fd))))
944 (dup->port port/fd "w"))
946 (dup->port port/fd "w" new-fd))))
951 (if (integer? port/fd)
953 (dup->port port/fd (port-mode port/fd))))
955 (if (integer? port/fd)
956 (dup->fdes port/fd new-fd)
957 (dup->port port/fd (port-mode port/fd) new-fd)))))
959 (define (duplicate-port port modes)
960 (dup->port port modes))
962 (define (fdes->inport fdes)
963 (let loop ((rest-ports (fdes->ports fdes)))
964 (cond ((null? rest-ports)
965 (let ((result (fdopen fdes "r")))
966 (set-port-revealed! result 1)
968 ((input-port? (car rest-ports))
969 (set-port-revealed! (car rest-ports)
970 (+ (port-revealed (car rest-ports)) 1))
973 (loop (cdr rest-ports))))))
975 (define (fdes->outport fdes)
976 (let loop ((rest-ports (fdes->ports fdes)))
977 (cond ((null? rest-ports)
978 (let ((result (fdopen fdes "w")))
979 (set-port-revealed! result 1)
981 ((output-port? (car rest-ports))
982 (set-port-revealed! (car rest-ports)
983 (+ (port-revealed (car rest-ports)) 1))
986 (loop (cdr rest-ports))))))
988 (define (port->fdes port)
989 (set-port-revealed! port (+ (port-revealed port) 1))
992 (define (setenv name value)
994 (putenv (string-append name "=" value))
997 (define (unsetenv name)
998 "Remove the entry for NAME from the environment."
1006 (define (in-vicinity vicinity file)
1007 (let ((tail (let ((len (string-length vicinity)))
1010 (string-ref vicinity (- len 1))))))
1011 (string-append vicinity
1020 ;;; {Help for scm_shell}
1022 ;;; The argument-processing code used by Guile-based shells generates
1023 ;;; Scheme code based on the argument list. This page contains help
1024 ;;; functions for the code it generates.
1027 (define (command-line) (program-arguments))
1029 ;; This is mostly for the internal use of the code generated by
1030 ;; scm_compile_shell_switches.
1032 (define (turn-on-debugging)
1033 (debug-enable 'debug)
1034 (debug-enable 'backtrace)
1035 (read-enable 'positions))
1037 (define (load-user-init)
1038 (let* ((home (or (getenv "HOME")
1039 (false-if-exception (passwd:dir (getpwuid (getuid))))
1040 "/")) ;; fallback for cygwin etc.
1041 (init-file (in-vicinity home ".guile")))
1042 (if (file-exists? init-file)
1043 (primitive-load init-file))))
1047 ;;; {The interpreter stack}
1050 ;; %stacks defined in stacks.c
1051 (define (%start-stack tag thunk)
1052 (let ((prompt-tag (make-prompt-tag "start-stack")))
1056 (with-fluids ((%stacks (acons tag prompt-tag
1057 (or (fluid-ref %stacks) '()))))
1060 (%start-stack tag (lambda () (apply k args)))))))
1061 (define-syntax start-stack
1064 (%start-stack tag (lambda () exp)))))
1068 ;;; {Loading by paths}
1071 ;;; Load a Scheme source file named NAME, searching for it in the
1072 ;;; directories listed in %load-path, and applying each of the file
1073 ;;; name extensions listed in %load-extensions.
1074 (define (load-from-path name)
1075 (start-stack 'load-stack
1076 (primitive-load-path name)))
1078 (define %load-verbosely #f)
1079 (define (assert-load-verbosity v) (set! %load-verbosely v))
1081 (define (%load-announce file)
1083 (with-output-to-port (current-error-port)
1086 (display "loading ")
1091 (set! %load-hook %load-announce)
1093 (define* (load name #:optional reader)
1094 ;; Returns the .go file corresponding to `name'. Does not search load
1095 ;; paths, only the fallback path. If the .go file is missing or out of
1096 ;; date, and autocompilation is enabled, will try autocompilation, just
1097 ;; as primitive-load-path does internally. primitive-load is
1098 ;; unaffected. Returns #f if autocompilation failed or was disabled.
1100 ;; NB: Unless we need to compile the file, this function should not cause
1101 ;; (system base compile) to be loaded up. For that reason compiled-file-name
1102 ;; partially duplicates functionality from (system base compile).
1103 (define (compiled-file-name canon-path)
1104 (and %compile-fallback-path
1106 %compile-fallback-path
1107 ;; no need for '/' separator here, canon-path is absolute
1109 (cond ((or (null? %load-compiled-extensions)
1110 (string-null? (car %load-compiled-extensions)))
1111 (warn "invalid %load-compiled-extensions"
1112 %load-compiled-extensions)
1114 (else (car %load-compiled-extensions))))))
1115 (define (fresh-compiled-file-name go-path)
1118 (let* ((scmstat (stat name))
1119 (gostat (stat go-path #f)))
1120 (if (and gostat (= (stat:mtime gostat) (stat:mtime scmstat)))
1124 (format (current-error-port)
1125 ";;; note: source file ~a\n;;; newer than compiled ~a\n"
1128 (%load-should-autocompile
1129 (%warn-autocompilation-enabled)
1130 (format (current-error-port) ";;; compiling ~a\n" name)
1131 ;; This use of @ is (ironically?) boot-safe, as modules have
1132 ;; not been booted yet, so the resolve-module call in psyntax
1133 ;; doesn't try to load a module, and compile-file will be
1134 ;; treated as a function, not a macro.
1135 (let ((cfn ((@ (system base compile) compile-file) name
1136 #:env (current-module))))
1137 (format (current-error-port) ";;; compiled ~a\n" cfn)
1141 (format (current-error-port)
1142 ";;; WARNING: compilation of ~a failed:\n;;; key ~a, throw_args ~s\n"
1145 (with-fluids ((current-reader reader))
1146 (let ((cfn (and=> (and=> (false-if-exception (canonicalize-path name))
1148 fresh-compiled-file-name)))
1151 (start-stack 'load-stack
1152 (primitive-load name))))))
1156 ;;; {Reader Extensions}
1158 ;;; Reader code for various "#c" forms.
1161 (define read-eval? (make-fluid))
1162 (fluid-set! read-eval? #f)
1163 (read-hash-extend #\.
1165 (if (fluid-ref read-eval?)
1166 (eval (read port) (interaction-environment))
1168 "#. read expansion found and read-eval? is #f."))))
1172 ;;; {Low Level Modules}
1174 ;;; These are the low level data structures for modules.
1176 ;;; Every module object is of the type 'module-type', which is a record
1177 ;;; consisting of the following members:
1179 ;;; - eval-closure: the function that defines for its module the strategy that
1180 ;;; shall be followed when looking up symbols in the module.
1182 ;;; An eval-closure is a function taking two arguments: the symbol to be
1183 ;;; looked up and a boolean value telling whether a binding for the symbol
1184 ;;; should be created if it does not exist yet. If the symbol lookup
1185 ;;; succeeded (either because an existing binding was found or because a new
1186 ;;; binding was created), a variable object representing the binding is
1187 ;;; returned. Otherwise, the value #f is returned. Note that the eval
1188 ;;; closure does not take the module to be searched as an argument: During
1189 ;;; construction of the eval-closure, the eval-closure has to store the
1190 ;;; module it belongs to in its environment. This means, that any
1191 ;;; eval-closure can belong to only one module.
1193 ;;; The eval-closure of a module can be defined arbitrarily. However, three
1194 ;;; special cases of eval-closures are to be distinguished: During startup
1195 ;;; the module system is not yet activated. In this phase, no modules are
1196 ;;; defined and all bindings are automatically stored by the system in the
1197 ;;; pre-modules-obarray. Since no eval-closures exist at this time, the
1198 ;;; functions which require an eval-closure as their argument need to be
1199 ;;; passed the value #f.
1201 ;;; The other two special cases of eval-closures are the
1202 ;;; standard-eval-closure and the standard-interface-eval-closure. Both
1203 ;;; behave equally for the case that no new binding is to be created. The
1204 ;;; difference between the two comes in, when the boolean argument to the
1205 ;;; eval-closure indicates that a new binding shall be created if it is not
1208 ;;; Given that no new binding shall be created, both standard eval-closures
1209 ;;; define the following standard strategy of searching bindings in the
1210 ;;; module: First, the module's obarray is searched for the symbol. Second,
1211 ;;; if no binding for the symbol was found in the module's obarray, the
1212 ;;; module's binder procedure is exececuted. If this procedure did not
1213 ;;; return a binding for the symbol, the modules referenced in the module's
1214 ;;; uses list are recursively searched for a binding of the symbol. If the
1215 ;;; binding can not be found in these modules also, the symbol lookup has
1218 ;;; If a new binding shall be created, the standard-interface-eval-closure
1219 ;;; immediately returns indicating failure. That is, it does not even try
1220 ;;; to look up the symbol. In contrast, the standard-eval-closure would
1221 ;;; first search the obarray, and if no binding was found there, would
1222 ;;; create a new binding in the obarray, therefore not calling the binder
1223 ;;; procedure or searching the modules in the uses list.
1225 ;;; The explanation of the following members obarray, binder and uses
1226 ;;; assumes that the symbol lookup follows the strategy that is defined in
1227 ;;; the standard-eval-closure and the standard-interface-eval-closure.
1229 ;;; - obarray: a hash table that maps symbols to variable objects. In this
1230 ;;; hash table, the definitions are found that are local to the module (that
1231 ;;; is, not imported from other modules). When looking up bindings in the
1232 ;;; module, this hash table is searched first.
1234 ;;; - binder: either #f or a function taking a module and a symbol argument.
1235 ;;; If it is a function it is called after the obarray has been
1236 ;;; unsuccessfully searched for a binding. It then can provide bindings
1237 ;;; that would otherwise not be found locally in the module.
1239 ;;; - uses: a list of modules from which non-local bindings can be inherited.
1240 ;;; These modules are the third place queried for bindings after the obarray
1241 ;;; has been unsuccessfully searched and the binder function did not deliver
1242 ;;; a result either.
1244 ;;; - transformer: either #f or a function taking a scheme expression as
1245 ;;; delivered by read. If it is a function, it will be called to perform
1246 ;;; syntax transformations (e. g. makro expansion) on the given scheme
1247 ;;; expression. The output of the transformer function will then be passed
1248 ;;; to Guile's internal memoizer. This means that the output must be valid
1249 ;;; scheme code. The only exception is, that the output may make use of the
1250 ;;; syntax extensions provided to identify the modules that a binding
1253 ;;; - name: the name of the module. This is used for all kinds of printing
1254 ;;; outputs. In certain places the module name also serves as a way of
1255 ;;; identification. When adding a module to the uses list of another
1256 ;;; module, it is made sure that the new uses list will not contain two
1257 ;;; modules of the same name.
1259 ;;; - kind: classification of the kind of module. The value is (currently?)
1260 ;;; only used for printing. It has no influence on how a module is treated.
1261 ;;; Currently the following values are used when setting the module kind:
1262 ;;; 'module, 'directory, 'interface, 'custom-interface. If no explicit kind
1263 ;;; is set, it defaults to 'module.
1265 ;;; - duplicates-handlers: a list of procedures that get called to make a
1266 ;;; choice between two duplicate bindings when name clashes occur. See the
1267 ;;; `duplicate-handlers' global variable below.
1269 ;;; - observers: a list of procedures that get called when the module is
1272 ;;; - weak-observers: a weak-key hash table of procedures that get called
1273 ;;; when the module is modified. See `module-observe-weak' for details.
1275 ;;; In addition, the module may (must?) contain a binding for
1276 ;;; `%module-public-interface'. This variable should be bound to a module
1277 ;;; representing the exported interface of a module. See the
1278 ;;; `module-public-interface' and `module-export!' procedures.
1280 ;;; !!! warning: The interface to lazy binder procedures is going
1281 ;;; to be changed in an incompatible way to permit all the basic
1282 ;;; module ops to be virtualized.
1284 ;;; (make-module size use-list lazy-binding-proc) => module
1285 ;;; module-{obarray,uses,binder}[|-set!]
1286 ;;; (module? obj) => [#t|#f]
1287 ;;; (module-locally-bound? module symbol) => [#t|#f]
1288 ;;; (module-bound? module symbol) => [#t|#f]
1289 ;;; (module-symbol-locally-interned? module symbol) => [#t|#f]
1290 ;;; (module-symbol-interned? module symbol) => [#t|#f]
1291 ;;; (module-local-variable module symbol) => [#<variable ...> | #f]
1292 ;;; (module-variable module symbol) => [#<variable ...> | #f]
1293 ;;; (module-symbol-binding module symbol opt-value)
1294 ;;; => [ <obj> | opt-value | an error occurs ]
1295 ;;; (module-make-local-var! module symbol) => #<variable...>
1296 ;;; (module-add! module symbol var) => unspecified
1297 ;;; (module-remove! module symbol) => unspecified
1298 ;;; (module-for-each proc module) => unspecified
1299 ;;; (make-scm-module) => module ; a lazy copy of the symhash module
1300 ;;; (set-current-module module) => unspecified
1301 ;;; (current-module) => #<module...>
1307 ;;; {Printing Modules}
1310 ;; This is how modules are printed. You can re-define it.
1311 (define (%print-module mod port)
1313 (display (or (module-kind mod) "module") port)
1315 (display (module-name mod) port)
1317 (display (number->string (object-address mod) 16) port)
1321 ;; Locally extend the syntax to allow record accessors to be defined at
1322 ;; compile-time. Cache the rtd locally to the constructor, the getters and
1323 ;; the setters, in order to allow for redefinition of the record type; not
1324 ;; relevant in the case of modules, but perhaps if we make this public, it
1327 ((define-record-type
1329 (define (make-id scope . fragments)
1330 (datum->syntax #'scope
1331 (apply symbol-append
1333 (if (symbol? x) x (syntax->datum x)))
1336 (define (getter rtd type-name field slot)
1337 #`(define #,(make-id rtd type-name '- field)
1339 (lambda (#,type-name)
1340 (if (eq? (struct-vtable #,type-name) rtd)
1341 (struct-ref #,type-name #,slot)
1342 (%record-type-error rtd #,type-name))))))
1344 (define (setter rtd type-name field slot)
1345 #`(define #,(make-id rtd 'set- type-name '- field '!)
1347 (lambda (#,type-name val)
1348 (if (eq? (struct-vtable #,type-name) rtd)
1349 (struct-set! #,type-name #,slot val)
1350 (%record-type-error rtd #,type-name))))))
1352 (define (accessors rtd type-name fields n exp)
1353 (syntax-case fields ()
1355 (((field #:no-accessors) field* ...) (identifier? #'field)
1356 (accessors rtd type-name #'(field* ...) (1+ n)
1358 (((field #:no-setter) field* ...) (identifier? #'field)
1359 (accessors rtd type-name #'(field* ...) (1+ n)
1361 #,(getter rtd type-name #'field n))))
1362 (((field #:no-getter) field* ...) (identifier? #'field)
1363 (accessors rtd type-name #'(field* ...) (1+ n)
1365 #,(setter rtd type-name #'field n))))
1366 ((field field* ...) (identifier? #'field)
1367 (accessors rtd type-name #'(field* ...) (1+ n)
1369 #,(getter rtd type-name #'field n)
1370 #,(setter rtd type-name #'field n))))))
1372 (define (predicate rtd type-name fields exp)
1374 rtd type-name fields 0
1377 (define (#,(make-id rtd type-name '?) obj)
1378 (and (struct? obj) (eq? (struct-vtable obj) #,rtd))))))
1380 (define (field-list fields)
1381 (syntax-case fields ()
1383 (((f . opts) . rest) (identifier? #'f)
1384 (cons #'f (field-list #'rest)))
1385 ((f . rest) (identifier? #'f)
1386 (cons #'f (field-list #'rest)))))
1388 (define (constructor rtd type-name fields exp)
1389 (let ((ctor (make-id rtd type-name '-constructor))
1390 (args (field-list fields)))
1391 (predicate rtd type-name fields
1396 (make-struct rtd 0 #,@args))))
1397 (struct-set! #,rtd (+ vtable-offset-user 2)
1400 (define (type type-name printer fields)
1401 (define (make-layout)
1402 (let lp ((fields fields) (slots '()))
1403 (syntax-case fields ()
1404 (() (datum->syntax #'here
1406 (apply string-append slots))))
1407 ((_ . rest) (lp #'rest (cons "pw" slots))))))
1409 (let ((rtd (make-id type-name type-name '-type)))
1410 (constructor rtd type-name fields
1413 (make-struct record-type-vtable 0
1417 '#,(field-list fields)))
1418 (set-struct-vtable-name! #,rtd '#,type-name)))))
1421 ((_ type-name printer (field ...))
1422 (type #'type-name #'printer #'(field ...)))))))
1426 ;; A module is characterized by an obarray in which local symbols
1427 ;; are interned, a list of modules, "uses", from which non-local
1428 ;; bindings can be inherited, and an optional lazy-binder which
1429 ;; is a (CLOSURE module symbol) which, as a last resort, can provide
1430 ;; bindings that would otherwise not be found locally in the module.
1432 ;; NOTE: If you change the set of fields or their order, you also need to
1433 ;; change the constants in libguile/modules.h.
1435 ;; NOTE: The getter `module-eval-closure' is used in libguile/modules.c.
1436 ;; NOTE: The getter `module-transfomer' is defined libguile/modules.c.
1437 ;; NOTE: The getter `module-name' is defined later, due to boot reasons.
1438 ;; NOTE: The getter `module-public-interface' is used in libguile/modules.c.
1440 (define-record-type module
1441 (lambda (obj port) (%print-module obj port))
1446 (transformer #:no-getter)
1450 (import-obarray #:no-setter)
1452 (weak-observers #:no-setter)
1460 ;; make-module &opt size uses binder
1462 ;; Create a new module, perhaps with a particular size of obarray,
1463 ;; initial uses list, or binding procedure.
1468 (define (parse-arg index default)
1469 (if (> (length args) index)
1470 (list-ref args index)
1473 (define %default-import-size
1474 ;; Typical number of imported bindings actually used by a module.
1477 (if (> (length args) 3)
1478 (error "Too many args to make-module." args))
1480 (let ((size (parse-arg 0 31))
1481 (uses (parse-arg 1 '()))
1482 (binder (parse-arg 2 #f)))
1484 (if (not (integer? size))
1485 (error "Illegal size to make-module." size))
1486 (if (not (and (list? uses)
1487 (and-map module? uses)))
1488 (error "Incorrect use list." uses))
1489 (if (and binder (not (procedure? binder)))
1491 "Lazy-binder expected to be a procedure or #f." binder))
1493 (let ((module (module-constructor (make-hash-table size)
1494 uses binder #f macroexpand
1496 (make-hash-table %default-import-size)
1498 (make-weak-key-hash-table 31) #f
1499 (make-hash-table 7) #f #f #f)))
1501 ;; We can't pass this as an argument to module-constructor,
1502 ;; because we need it to close over a pointer to the module
1504 (set-module-eval-closure! module (standard-eval-closure module))
1511 ;;; {Observer protocol}
1514 (define (module-observe module proc)
1515 (set-module-observers! module (cons proc (module-observers module)))
1518 (define* (module-observe-weak module observer-id #:optional (proc observer-id))
1519 ;; Register PROC as an observer of MODULE under name OBSERVER-ID (which can
1520 ;; be any Scheme object). PROC is invoked and passed MODULE any time
1521 ;; MODULE is modified. PROC gets unregistered when OBSERVER-ID gets GC'd
1522 ;; (thus, it is never unregistered if OBSERVER-ID is an immediate value,
1525 ;; The two-argument version is kept for backward compatibility: when called
1526 ;; with two arguments, the observer gets unregistered when closure PROC
1527 ;; gets GC'd (making it impossible to use an anonymous lambda for PROC).
1528 (hashq-set! (module-weak-observers module) observer-id proc))
1530 (define (module-unobserve token)
1531 (let ((module (car token))
1534 (hash-remove! (module-weak-observers module) id)
1535 (set-module-observers! module (delq1! id (module-observers module)))))
1538 (define module-defer-observers #f)
1539 (define module-defer-observers-mutex (make-mutex 'recursive))
1540 (define module-defer-observers-table (make-hash-table))
1542 (define (module-modified m)
1543 (if module-defer-observers
1544 (hash-set! module-defer-observers-table m #t)
1545 (module-call-observers m)))
1547 ;;; This function can be used to delay calls to observers so that they
1548 ;;; can be called once only in the face of massive updating of modules.
1550 (define (call-with-deferred-observers thunk)
1553 (lock-mutex module-defer-observers-mutex)
1554 (set! module-defer-observers #t))
1557 (set! module-defer-observers #f)
1558 (hash-for-each (lambda (m dummy)
1559 (module-call-observers m))
1560 module-defer-observers-table)
1561 (hash-clear! module-defer-observers-table)
1562 (unlock-mutex module-defer-observers-mutex))))
1564 (define (module-call-observers m)
1565 (for-each (lambda (proc) (proc m)) (module-observers m))
1567 ;; We assume that weak observers don't (un)register themselves as they are
1568 ;; called since this would preclude proper iteration over the hash table
1570 (hash-for-each (lambda (id proc) (proc m)) (module-weak-observers m)))
1574 ;;; {Module Searching in General}
1576 ;;; We sometimes want to look for properties of a symbol
1577 ;;; just within the obarray of one module. If the property
1578 ;;; holds, then it is said to hold ``locally'' as in, ``The symbol
1579 ;;; DISPLAY is locally rebound in the module `safe-guile'.''
1582 ;;; Other times, we want to test for a symbol property in the obarray
1583 ;;; of M and, if it is not found there, try each of the modules in the
1584 ;;; uses list of M. This is the normal way of testing for some
1585 ;;; property, so we state these properties without qualification as
1586 ;;; in: ``The symbol 'fnord is interned in module M because it is
1587 ;;; interned locally in module M2 which is a member of the uses list
1591 ;; module-search fn m
1593 ;; return the first non-#f result of FN applied to M and then to
1594 ;; the modules in the uses of m, and so on recursively. If all applications
1595 ;; return #f, then so does this function.
1597 (define (module-search fn m v)
1600 (or (module-search fn (car pos) v)
1603 (loop (module-uses m))))
1606 ;;; {Is a symbol bound in a module?}
1608 ;;; Symbol S in Module M is bound if S is interned in M and if the binding
1609 ;;; of S in M has been set to some well-defined value.
1612 ;; module-locally-bound? module symbol
1614 ;; Is a symbol bound (interned and defined) locally in a given module?
1616 (define (module-locally-bound? m v)
1617 (let ((var (module-local-variable m v)))
1619 (variable-bound? var))))
1621 ;; module-bound? module symbol
1623 ;; Is a symbol bound (interned and defined) anywhere in a given module
1626 (define (module-bound? m v)
1627 (let ((var (module-variable m v)))
1629 (variable-bound? var))))
1631 ;;; {Is a symbol interned in a module?}
1633 ;;; Symbol S in Module M is interned if S occurs in
1634 ;;; of S in M has been set to some well-defined value.
1636 ;;; It is possible to intern a symbol in a module without providing
1637 ;;; an initial binding for the corresponding variable. This is done
1639 ;;; (module-add! module symbol (make-undefined-variable))
1641 ;;; In that case, the symbol is interned in the module, but not
1642 ;;; bound there. The unbound symbol shadows any binding for that
1643 ;;; symbol that might otherwise be inherited from a member of the uses list.
1646 (define (module-obarray-get-handle ob key)
1647 ((if (symbol? key) hashq-get-handle hash-get-handle) ob key))
1649 (define (module-obarray-ref ob key)
1650 ((if (symbol? key) hashq-ref hash-ref) ob key))
1652 (define (module-obarray-set! ob key val)
1653 ((if (symbol? key) hashq-set! hash-set!) ob key val))
1655 (define (module-obarray-remove! ob key)
1656 ((if (symbol? key) hashq-remove! hash-remove!) ob key))
1658 ;; module-symbol-locally-interned? module symbol
1660 ;; is a symbol interned (not neccessarily defined) locally in a given module
1661 ;; or its uses? Interned symbols shadow inherited bindings even if
1662 ;; they are not themselves bound to a defined value.
1664 (define (module-symbol-locally-interned? m v)
1665 (not (not (module-obarray-get-handle (module-obarray m) v))))
1667 ;; module-symbol-interned? module symbol
1669 ;; is a symbol interned (not neccessarily defined) anywhere in a given module
1670 ;; or its uses? Interned symbols shadow inherited bindings even if
1671 ;; they are not themselves bound to a defined value.
1673 (define (module-symbol-interned? m v)
1674 (module-search module-symbol-locally-interned? m v))
1677 ;;; {Mapping modules x symbols --> variables}
1680 ;; module-local-variable module symbol
1681 ;; return the local variable associated with a MODULE and SYMBOL.
1683 ;;; This function is very important. It is the only function that can
1684 ;;; return a variable from a module other than the mutators that store
1685 ;;; new variables in modules. Therefore, this function is the location
1686 ;;; of the "lazy binder" hack.
1688 ;;; If symbol is defined in MODULE, and if the definition binds symbol
1689 ;;; to a variable, return that variable object.
1691 ;;; If the symbols is not found at first, but the module has a lazy binder,
1692 ;;; then try the binder.
1694 ;;; If the symbol is not found at all, return #f.
1696 ;;; (This is now written in C, see `modules.c'.)
1699 ;;; {Mapping modules x symbols --> bindings}
1701 ;;; These are similar to the mapping to variables, except that the
1702 ;;; variable is dereferenced.
1705 ;; module-symbol-binding module symbol opt-value
1707 ;; return the binding of a variable specified by name within
1708 ;; a given module, signalling an error if the variable is unbound.
1709 ;; If the OPT-VALUE is passed, then instead of signalling an error,
1710 ;; return OPT-VALUE.
1712 (define (module-symbol-local-binding m v . opt-val)
1713 (let ((var (module-local-variable m v)))
1714 (if (and var (variable-bound? var))
1716 (if (not (null? opt-val))
1718 (error "Locally unbound variable." v)))))
1720 ;; module-symbol-binding module symbol opt-value
1722 ;; return the binding of a variable specified by name within
1723 ;; a given module, signalling an error if the variable is unbound.
1724 ;; If the OPT-VALUE is passed, then instead of signalling an error,
1725 ;; return OPT-VALUE.
1727 (define (module-symbol-binding m v . opt-val)
1728 (let ((var (module-variable m v)))
1729 (if (and var (variable-bound? var))
1731 (if (not (null? opt-val))
1733 (error "Unbound variable." v)))))
1738 ;;; {Adding Variables to Modules}
1741 ;; module-make-local-var! module symbol
1743 ;; ensure a variable for V in the local namespace of M.
1744 ;; If no variable was already there, then create a new and uninitialzied
1747 ;; This function is used in modules.c.
1749 (define (module-make-local-var! m v)
1750 (or (let ((b (module-obarray-ref (module-obarray m) v)))
1753 ;; Mark as modified since this function is called when
1754 ;; the standard eval closure defines a binding
1758 ;; Create a new local variable.
1759 (let ((local-var (make-undefined-variable)))
1760 (module-add! m v local-var)
1763 ;; module-ensure-local-variable! module symbol
1765 ;; Ensure that there is a local variable in MODULE for SYMBOL. If
1766 ;; there is no binding for SYMBOL, create a new uninitialized
1767 ;; variable. Return the local variable.
1769 (define (module-ensure-local-variable! module symbol)
1770 (or (module-local-variable module symbol)
1771 (let ((var (make-undefined-variable)))
1772 (module-add! module symbol var)
1775 ;; module-add! module symbol var
1777 ;; ensure a particular variable for V in the local namespace of M.
1779 (define (module-add! m v var)
1780 (if (not (variable? var))
1781 (error "Bad variable to module-add!" var))
1782 (module-obarray-set! (module-obarray m) v var)
1783 (module-modified m))
1787 ;; make sure that a symbol is undefined in the local namespace of M.
1789 (define (module-remove! m v)
1790 (module-obarray-remove! (module-obarray m) v)
1791 (module-modified m))
1793 (define (module-clear! m)
1794 (hash-clear! (module-obarray m))
1795 (module-modified m))
1797 ;; MODULE-FOR-EACH -- exported
1799 ;; Call PROC on each symbol in MODULE, with arguments of (SYMBOL VARIABLE).
1801 (define (module-for-each proc module)
1802 (hash-for-each proc (module-obarray module)))
1804 (define (module-map proc module)
1805 (hash-map->list proc (module-obarray module)))
1809 ;; Modules exist in a separate namespace from values, because you generally do
1810 ;; not want the name of a submodule, which you might not even use, to collide
1811 ;; with local variables that happen to be named the same as the submodule.
1813 (define (module-ref-submodule module name)
1814 (or (hashq-ref (module-submodules module) name)
1815 (and (module-submodule-binder module)
1816 ((module-submodule-binder module) module name))))
1818 (define (module-define-submodule! module name submodule)
1819 (hashq-set! (module-submodules module) name submodule))
1823 ;;; {Low Level Bootstrapping}
1828 ;; A root module uses the pre-modules-obarray as its obarray. This
1829 ;; special obarray accumulates all bindings that have been established
1830 ;; before the module system is fully booted.
1832 ;; (The obarray continues to be used by code that has been closed over
1833 ;; before the module system has been booted.)
1835 (define (make-root-module)
1836 (let ((m (make-module 0)))
1837 (set-module-obarray! m (%get-pre-modules-obarray))
1842 ;; The root interface is a module that uses the same obarray as the
1843 ;; root module. It does not allow new definitions, tho.
1845 (define (make-scm-module)
1846 (let ((m (make-module 0)))
1847 (set-module-obarray! m (%get-pre-modules-obarray))
1848 (set-module-eval-closure! m (standard-interface-eval-closure m))
1854 ;;; {Module-based Loading}
1857 (define (save-module-excursion thunk)
1858 (let ((inner-module (current-module))
1860 (dynamic-wind (lambda ()
1861 (set! outer-module (current-module))
1862 (set-current-module inner-module)
1863 (set! inner-module #f))
1866 (set! inner-module (current-module))
1867 (set-current-module outer-module)
1868 (set! outer-module #f)))))
1870 (define basic-load load)
1872 (define* (load-module filename #:optional reader)
1873 (save-module-excursion
1875 (let ((oldname (and (current-load-port)
1876 (port-filename (current-load-port)))))
1877 (basic-load (if (and oldname
1878 (> (string-length filename) 0)
1879 (not (char=? (string-ref filename 0) #\/))
1880 (not (string=? (dirname oldname) ".")))
1881 (string-append (dirname oldname) "/" filename)
1888 ;;; {MODULE-REF -- exported}
1891 ;; Returns the value of a variable called NAME in MODULE or any of its
1892 ;; used modules. If there is no such variable, then if the optional third
1893 ;; argument DEFAULT is present, it is returned; otherwise an error is signaled.
1895 (define (module-ref module name . rest)
1896 (let ((variable (module-variable module name)))
1897 (if (and variable (variable-bound? variable))
1898 (variable-ref variable)
1900 (error "No variable named" name 'in module)
1901 (car rest) ; default value
1904 ;; MODULE-SET! -- exported
1906 ;; Sets the variable called NAME in MODULE (or in a module that MODULE uses)
1907 ;; to VALUE; if there is no such variable, an error is signaled.
1909 (define (module-set! module name value)
1910 (let ((variable (module-variable module name)))
1912 (variable-set! variable value)
1913 (error "No variable named" name 'in module))))
1915 ;; MODULE-DEFINE! -- exported
1917 ;; Sets the variable called NAME in MODULE to VALUE; if there is no such
1918 ;; variable, it is added first.
1920 (define (module-define! module name value)
1921 (let ((variable (module-local-variable module name)))
1924 (variable-set! variable value)
1925 (module-modified module))
1926 (let ((variable (make-variable value)))
1927 (module-add! module name variable)))))
1929 ;; MODULE-DEFINED? -- exported
1931 ;; Return #t iff NAME is defined in MODULE (or in a module that MODULE
1934 (define (module-defined? module name)
1935 (let ((variable (module-variable module name)))
1936 (and variable (variable-bound? variable))))
1938 ;; MODULE-USE! module interface
1940 ;; Add INTERFACE to the list of interfaces used by MODULE.
1942 (define (module-use! module interface)
1943 (if (not (or (eq? module interface)
1944 (memq interface (module-uses module))))
1946 ;; Newly used modules must be appended rather than consed, so that
1947 ;; `module-variable' traverses the use list starting from the first
1949 (set-module-uses! module
1950 (append (filter (lambda (m)
1952 (equal? (module-name m)
1953 (module-name interface))))
1954 (module-uses module))
1956 (hash-clear! (module-import-obarray module))
1957 (module-modified module))))
1959 ;; MODULE-USE-INTERFACES! module interfaces
1961 ;; Same as MODULE-USE! but add multiple interfaces and check for duplicates
1963 (define (module-use-interfaces! module interfaces)
1964 (set-module-uses! module
1965 (append (module-uses module) interfaces))
1966 (hash-clear! (module-import-obarray module))
1967 (module-modified module))
1971 ;;; {Recursive Namespaces}
1973 ;;; A hierarchical namespace emerges if we consider some module to be
1974 ;;; root, and submodules of that module to be nested namespaces.
1976 ;;; The routines here manage variable names in hierarchical namespace.
1977 ;;; Each variable name is a list of elements, looked up in successively nested
1980 ;;; (nested-ref some-root-module '(foo bar baz))
1981 ;;; => <value of a variable named baz in the submodule bar of
1982 ;;; the submodule foo of some-root-module>
1987 ;;; ;; a-root is a module
1988 ;;; ;; name is a list of symbols
1990 ;;; nested-ref a-root name
1991 ;;; nested-set! a-root name val
1992 ;;; nested-define! a-root name val
1993 ;;; nested-remove! a-root name
1995 ;;; These functions manipulate values in namespaces. For referencing the
1996 ;;; namespaces themselves, use the following:
1998 ;;; nested-ref-module a-root name
1999 ;;; nested-define-module! a-root name mod
2001 ;;; (current-module) is a natural choice for a root so for convenience there are
2004 ;;; local-ref name == nested-ref (current-module) name
2005 ;;; local-set! name val == nested-set! (current-module) name val
2006 ;;; local-define name val == nested-define! (current-module) name val
2007 ;;; local-remove name == nested-remove! (current-module) name
2008 ;;; local-ref-module name == nested-ref-module (current-module) name
2009 ;;; local-define-module! name m == nested-define-module! (current-module) name m
2013 (define (nested-ref root names)
2016 (let loop ((cur root)
2020 (module-ref cur head #f)
2021 (let ((cur (module-ref-submodule cur head)))
2023 (loop cur (car tail) (cdr tail))))))))
2025 (define (nested-set! root names val)
2026 (let loop ((cur root)
2030 (module-set! cur head val)
2031 (let ((cur (module-ref-submodule cur head)))
2033 (error "failed to resolve module" names)
2034 (loop cur (car tail) (cdr tail)))))))
2036 (define (nested-define! root names val)
2037 (let loop ((cur root)
2041 (module-define! cur head val)
2042 (let ((cur (module-ref-submodule cur head)))
2044 (error "failed to resolve module" names)
2045 (loop cur (car tail) (cdr tail)))))))
2047 (define (nested-remove! root names)
2048 (let loop ((cur root)
2052 (module-remove! cur head)
2053 (let ((cur (module-ref-submodule cur head)))
2055 (error "failed to resolve module" names)
2056 (loop cur (car tail) (cdr tail)))))))
2059 (define (nested-ref-module root names)
2060 (let loop ((cur root)
2064 (let ((cur (module-ref-submodule cur (car names))))
2066 (loop cur (cdr names)))))))
2068 (define (nested-define-module! root names module)
2070 (error "can't redefine root module" root module)
2071 (let loop ((cur root)
2075 (module-define-submodule! cur head module)
2076 (let ((cur (or (module-ref-submodule cur head)
2077 (let ((m (make-module 31)))
2078 (set-module-kind! m 'directory)
2079 (set-module-name! m (append (module-name cur)
2081 (module-define-submodule! cur head m)
2083 (loop cur (car tail) (cdr tail)))))))
2086 (define (local-ref names) (nested-ref (current-module) names))
2087 (define (local-set! names val) (nested-set! (current-module) names val))
2088 (define (local-define names val) (nested-define! (current-module) names val))
2089 (define (local-remove names) (nested-remove! (current-module) names))
2090 (define (local-ref-module names) (nested-ref-module (current-module) names))
2091 (define (local-define-module names mod) (nested-define-module! (current-module) names mod))
2097 ;;; {The (guile) module}
2099 ;;; The standard module, which has the core Guile bindings. Also called the
2100 ;;; "root module", as it is imported by many other modules, but it is not
2101 ;;; necessarily the root of anything; and indeed, the module named '() might be
2102 ;;; better thought of as a root.
2105 (define (set-system-module! m s)
2106 (set-procedure-property! (module-eval-closure m) 'system-module s))
2107 (define the-root-module (make-root-module))
2108 (define the-scm-module (make-scm-module))
2109 (set-module-public-interface! the-root-module the-scm-module)
2110 (set-module-name! the-root-module '(guile))
2111 (set-module-name! the-scm-module '(guile))
2112 (set-module-kind! the-scm-module 'interface)
2113 (set-system-module! the-root-module #t)
2114 (set-system-module! the-scm-module #t)
2119 ;; Now that we have a root module, even though modules aren't fully booted,
2120 ;; expand the definition of resolve-module.
2122 (define (resolve-module name . args)
2123 (if (equal? name '(guile))
2125 (error "unexpected module to resolve during module boot" name)))
2127 ;; Cheat. These bindings are needed by modules.c, but we don't want
2128 ;; to move their real definition here because that would be unnatural.
2130 (define process-define-module #f)
2131 (define process-use-modules #f)
2132 (define module-export! #f)
2133 (define default-duplicate-binding-procedures #f)
2135 ;; This boots the module system. All bindings needed by modules.c
2136 ;; must have been defined by now.
2138 (set-current-module the-root-module)
2143 ;; Now that modules are booted, give module-name its final definition.
2146 (let ((accessor (record-accessor module-type 'name)))
2149 (let ((name (list (gensym))))
2150 ;; Name MOD and bind it in the module root so that it's visible to
2151 ;; `resolve-module'. This is important as `psyntax' stores module
2152 ;; names and relies on being able to `resolve-module' them.
2153 (set-module-name! mod name)
2154 (nested-define-module! (resolve-module '() #f) name mod)
2157 (define (make-modules-in module name)
2158 (or (nested-ref-module module name)
2159 (let ((m (make-module 31)))
2160 (set-module-kind! m 'directory)
2161 (set-module-name! m (append (module-name module) name))
2162 (nested-define-module! module name m)
2165 (define (beautify-user-module! module)
2166 (let ((interface (module-public-interface module)))
2167 (if (or (not interface)
2168 (eq? interface module))
2169 (let ((interface (make-module 31)))
2170 (set-module-name! interface (module-name module))
2171 (set-module-version! interface (module-version module))
2172 (set-module-kind! interface 'interface)
2173 (set-module-public-interface! module interface))))
2174 (if (and (not (memq the-scm-module (module-uses module)))
2175 (not (eq? module the-root-module)))
2176 ;; Import the default set of bindings (from the SCM module) in MODULE.
2177 (module-use! module the-scm-module)))
2179 (define (version-matches? version-ref target)
2180 (define (sub-versions-match? v-refs t)
2181 (define (sub-version-matches? v-ref t)
2182 (let ((matches? (lambda (v) (sub-version-matches? v t))))
2184 ((number? v-ref) (eqv? v-ref t))
2187 ((>=) (>= t (cadr v-ref)))
2188 ((<=) (<= t (cadr v-ref)))
2189 ((and) (and-map matches? (cdr v-ref)))
2190 ((or) (or-map matches? (cdr v-ref)))
2191 ((not) (not (matches? (cadr v-ref))))
2192 (else (error "Invalid sub-version reference" v-ref))))
2193 (else (error "Invalid sub-version reference" v-ref)))))
2195 (and (not (null? t))
2196 (sub-version-matches? (car v-refs) (car t))
2197 (sub-versions-match? (cdr v-refs) (cdr t)))))
2199 (let ((matches? (lambda (v) (version-matches? v target))))
2200 (or (null? version-ref)
2201 (case (car version-ref)
2202 ((and) (and-map matches? (cdr version-ref)))
2203 ((or) (or-map matches? (cdr version-ref)))
2204 ((not) (not (matches? (cadr version-ref))))
2205 (else (sub-versions-match? version-ref target))))))
2207 (define (make-fresh-user-module)
2208 (let ((m (make-module)))
2209 (beautify-user-module! m)
2212 ;; NOTE: This binding is used in libguile/modules.c.
2214 (define resolve-module
2215 (let ((root (make-module)))
2216 (set-module-name! root '())
2217 ;; Define the-root-module as '(guile).
2218 (module-define-submodule! root 'guile the-root-module)
2220 (lambda* (name #:optional (autoload #t) (version #f) #:key (ensure #t))
2221 (let ((already (nested-ref-module root name)))
2224 (or (not autoload) (module-public-interface already)))
2225 ;; A hit, a palpable hit.
2227 (not (version-matches? version (module-version already))))
2228 (error "incompatible module version already loaded" name))
2231 ;; Try to autoload the module, and recurse.
2232 (try-load-module name version)
2233 (resolve-module name #f #:ensure ensure))
2235 ;; No module found (or if one was, it had no public interface), and
2236 ;; we're not autoloading. Make an empty module if #:ensure is true.
2239 (make-modules-in root name)))))))))
2242 (define (try-load-module name version)
2243 (try-module-autoload name version))
2245 (define (purify-module! module)
2246 "Removes bindings in MODULE which are inherited from the (guile) module."
2247 (let ((use-list (module-uses module)))
2248 (if (and (pair? use-list)
2249 (eq? (car (last-pair use-list)) the-scm-module))
2250 (set-module-uses! module (reverse (cdr (reverse use-list)))))))
2252 ;; Return a module that is an interface to the module designated by
2255 ;; `resolve-interface' takes four keyword arguments:
2257 ;; #:select SELECTION
2259 ;; SELECTION is a list of binding-specs to be imported; A binding-spec
2260 ;; is either a symbol or a pair of symbols (ORIG . SEEN), where ORIG
2261 ;; is the name in the used module and SEEN is the name in the using
2262 ;; module. Note that SEEN is also passed through RENAMER, below. The
2263 ;; default is to select all bindings. If you specify no selection but
2264 ;; a renamer, only the bindings that already exist in the used module
2265 ;; are made available in the interface. Bindings that are added later
2266 ;; are not picked up.
2270 ;; BINDINGS is a list of bindings which should not be imported.
2274 ;; PREFIX is a symbol that will be appended to each exported name.
2275 ;; The default is to not perform any renaming.
2277 ;; #:renamer RENAMER
2279 ;; RENAMER is a procedure that takes a symbol and returns its new
2280 ;; name. The default is not perform any renaming.
2282 ;; Signal "no code for module" error if module name is not resolvable
2283 ;; or its public interface is not available. Signal "no binding"
2284 ;; error if selected binding does not exist in the used module.
2286 (define* (resolve-interface name #:key
2291 (symbol-prefix-proc prefix)
2294 (let* ((module (resolve-module name #t version #:ensure #f))
2295 (public-i (and module (module-public-interface module))))
2296 (and (or (not module) (not public-i))
2297 (error "no code for module" name))
2298 (if (and (not select) (null? hide) (eq? renamer identity))
2300 (let ((selection (or select (module-map (lambda (sym var) sym)
2302 (custom-i (make-module 31)))
2303 (set-module-kind! custom-i 'custom-interface)
2304 (set-module-name! custom-i name)
2305 ;; XXX - should use a lazy binder so that changes to the
2306 ;; used module are picked up automatically.
2307 (for-each (lambda (bspec)
2308 (let* ((direct? (symbol? bspec))
2309 (orig (if direct? bspec (car bspec)))
2310 (seen (if direct? bspec (cdr bspec)))
2311 (var (or (module-local-variable public-i orig)
2312 (module-local-variable module orig)
2314 ;; fixme: format manually for now
2316 #f "no binding `~A' in module ~A"
2318 (if (memq orig hide)
2319 (set! hide (delq! orig hide))
2320 (module-add! custom-i
2324 ;; Check that we are not hiding bindings which don't exist
2325 (for-each (lambda (binding)
2326 (if (not (module-local-variable public-i binding))
2329 #f "no binding `~A' to hide in module ~A"
2334 (define (symbol-prefix-proc prefix)
2336 (symbol-append prefix symbol)))
2338 ;; This function is called from "modules.c". If you change it, be
2339 ;; sure to update "modules.c" as well.
2341 (define (process-define-module args)
2342 (let* ((module-id (car args))
2343 (module (resolve-module module-id #f))
2345 (unrecognized (lambda (arg)
2346 (error "unrecognized define-module argument" arg))))
2347 (beautify-user-module! module)
2348 (let loop ((kws kws)
2349 (reversed-interfaces '())
2356 (call-with-deferred-observers
2358 (module-use-interfaces! module (reverse reversed-interfaces))
2359 (module-export! module exports)
2360 (module-replace! module replacements)
2361 (module-re-export! module re-exports)
2362 (if (not (null? autoloads))
2363 (apply module-autoload! module autoloads))))
2365 ((#:use-module #:use-syntax)
2366 (or (pair? (cdr kws))
2369 ((equal? (caadr kws) '(ice-9 syncase))
2370 (issue-deprecation-warning
2371 "(ice-9 syncase) is deprecated. Support for syntax-case is now in Guile core.")
2379 (let* ((interface-args (cadr kws))
2380 (interface (apply resolve-interface interface-args)))
2381 (and (eq? (car kws) #:use-syntax)
2382 (or (symbol? (caar interface-args))
2383 (error "invalid module name for use-syntax"
2384 (car interface-args)))
2385 (set-module-transformer!
2387 (module-ref interface
2388 (car (last-pair (car interface-args)))
2391 (cons interface reversed-interfaces)
2397 (or (and (pair? (cdr kws)) (pair? (cddr kws)))
2404 (let ((name (cadr kws))
2405 (bindings (caddr kws)))
2406 (cons* name bindings autoloads))))
2408 (set-system-module! module #t)
2409 (loop (cdr kws) reversed-interfaces exports re-exports
2410 replacements autoloads))
2412 (purify-module! module)
2413 (loop (cdr kws) reversed-interfaces exports re-exports
2414 replacements autoloads))
2416 (or (pair? (cdr kws))
2418 (let ((version (cadr kws)))
2419 (set-module-version! module version)
2420 (set-module-version! (module-public-interface module) version))
2421 (loop (cddr kws) reversed-interfaces exports re-exports
2422 replacements autoloads))
2424 (if (not (pair? (cdr kws)))
2426 (set-module-duplicates-handlers!
2428 (lookup-duplicates-handlers (cadr kws)))
2429 (loop (cddr kws) reversed-interfaces exports re-exports
2430 replacements autoloads))
2431 ((#:export #:export-syntax)
2432 (or (pair? (cdr kws))
2436 (append (cadr kws) exports)
2440 ((#:re-export #:re-export-syntax)
2441 (or (pair? (cdr kws))
2446 (append (cadr kws) re-exports)
2449 ((#:replace #:replace-syntax)
2450 (or (pair? (cdr kws))
2456 (append (cadr kws) replacements)
2459 (or (pair? (cdr kws))
2461 (set-module-filename! module (cadr kws))
2469 (unrecognized kws)))))
2470 (run-hook module-defined-hook module)
2473 ;; `module-defined-hook' is a hook that is run whenever a new module
2474 ;; is defined. Its members are called with one argument, the new
2476 (define module-defined-hook (make-hook 1))
2483 (define (make-autoload-interface module name bindings)
2484 (let ((b (lambda (a sym definep)
2485 (and (memq sym bindings)
2486 (let ((i (module-public-interface (resolve-module name))))
2488 (error "missing interface for module" name))
2489 (let ((autoload (memq a (module-uses module))))
2490 ;; Replace autoload-interface with actual interface if
2491 ;; that has not happened yet.
2492 (if (pair? autoload)
2493 (set-car! autoload i)))
2494 (module-local-variable i sym))))))
2495 (module-constructor (make-hash-table 0) '() b #f #f name 'autoload #f
2496 (make-hash-table 0) '() (make-weak-value-hash-table 31) #f
2497 (make-hash-table 0) #f #f #f)))
2499 (define (module-autoload! module . args)
2500 "Have @var{module} automatically load the module named @var{name} when one
2501 of the symbols listed in @var{bindings} is looked up. @var{args} should be a
2502 list of module-name/binding-list pairs, e.g., as in @code{(module-autoload!
2503 module '(ice-9 q) '(make-q q-length))}."
2504 (let loop ((args args))
2508 (error "invalid name+binding autoload list" args))
2510 (let ((name (car args))
2511 (bindings (cadr args)))
2512 (module-use! module (make-autoload-interface module
2514 (loop (cddr args)))))))
2519 ;;; {Autoloading modules}
2522 (define autoloads-in-progress '())
2524 ;; This function is called from "modules.c". If you change it, be
2525 ;; sure to update "modules.c" as well.
2527 (define* (try-module-autoload module-name #:optional version)
2528 (let* ((reverse-name (reverse module-name))
2529 (name (symbol->string (car reverse-name)))
2530 (dir-hint-module-name (reverse (cdr reverse-name)))
2531 (dir-hint (apply string-append
2533 (string-append (symbol->string elt) "/"))
2534 dir-hint-module-name))))
2535 (resolve-module dir-hint-module-name #f)
2536 (and (not (autoload-done-or-in-progress? dir-hint name))
2539 (lambda () (autoload-in-progress! dir-hint name))
2541 (with-fluids ((current-reader #f))
2542 (save-module-excursion
2544 ;; The initial environment when loading a module is a fresh
2546 (set-current-module (make-fresh-user-module))
2547 ;; Here we could allow some other search strategy (other than
2548 ;; primitive-load-path), for example using versions encoded
2549 ;; into the file system -- but then we would have to figure
2550 ;; out how to locate the compiled file, do autocompilation,
2551 ;; etc. Punt for now, and don't use versions when locating
2553 (primitive-load-path (in-vicinity dir-hint name) #f)
2555 (lambda () (set-autoloaded! dir-hint name didit)))
2560 ;;; {Dynamic linking of modules}
2563 (define autoloads-done '((guile . guile)))
2565 (define (autoload-done-or-in-progress? p m)
2566 (let ((n (cons p m)))
2567 (->bool (or (member n autoloads-done)
2568 (member n autoloads-in-progress)))))
2570 (define (autoload-done! p m)
2571 (let ((n (cons p m)))
2572 (set! autoloads-in-progress
2573 (delete! n autoloads-in-progress))
2574 (or (member n autoloads-done)
2575 (set! autoloads-done (cons n autoloads-done)))))
2577 (define (autoload-in-progress! p m)
2578 (let ((n (cons p m)))
2579 (set! autoloads-done
2580 (delete! n autoloads-done))
2581 (set! autoloads-in-progress (cons n autoloads-in-progress))))
2583 (define (set-autoloaded! p m done?)
2585 (autoload-done! p m)
2586 (let ((n (cons p m)))
2587 (set! autoloads-done (delete! n autoloads-done))
2588 (set! autoloads-in-progress (delete! n autoloads-in-progress)))))
2592 ;;; {Run-time options}
2595 (define-syntax define-option-interface
2597 ((_ (interface (options enable disable) (option-set!)))
2604 (begin (interface arg) (interface))
2607 (apply (lambda (name value documentation)
2609 (if (< (string-length (symbol->string name)) 8)
2614 (display documentation)
2618 (define (enable . flags)
2619 (interface (append flags (interface)))
2621 (define (disable . flags)
2622 (let ((options (interface)))
2623 (for-each (lambda (flag) (set! options (delq! flag options)))
2627 (define-syntax option-set!
2630 (options (append (options) (list 'opt val))))))))))
2632 (define-option-interface
2633 (eval-options-interface
2634 (eval-options eval-enable eval-disable)
2637 (define-option-interface
2638 (debug-options-interface
2639 (debug-options debug-enable debug-disable)
2642 (define-option-interface
2643 (evaluator-traps-interface
2644 (traps trap-enable trap-disable)
2647 (define-option-interface
2648 (read-options-interface
2649 (read-options read-enable read-disable)
2652 (define-option-interface
2653 (print-options-interface
2654 (print-options print-enable print-disable)
2659 ;;; {The Unspecified Value}
2661 ;;; Currently Guile represents unspecified values via one particular value,
2662 ;;; which may be obtained by evaluating (if #f #f). It would be nice in the
2663 ;;; future if we could replace this with a return of 0 values, though.
2665 (define-syntax *unspecified*
2666 (identifier-syntax (if #f #f)))
2668 (define (unspecified? v) (eq? v *unspecified*))
2676 (define (repl read evaler print)
2677 (let loop ((source (read (current-input-port))))
2678 (print (evaler source))
2679 (loop (read (current-input-port)))))
2681 ;; A provisional repl that acts like the SCM repl:
2683 (define (default-pre-unwind-handler key . args)
2684 ;; Narrow by two more frames: this one, and the throw handler.
2686 (apply throw key args))
2689 (define (pre-unwind-handler-dispatch key . args)
2690 (apply default-pre-unwind-handler key args)))
2692 (define abort-hook (make-hook))
2694 ;; these definitions are used if running a script.
2695 ;; otherwise redefined in error-catching-loop.
2696 (define (set-batch-mode?! arg) #t)
2697 (define (batch-mode?) #t)
2699 ;;(define the-last-stack (make-fluid)) Defined by scm_init_backtrace ()
2700 (define before-signal-stack (make-fluid))
2701 ;; FIXME: stack-saved? is broken in the presence of threads.
2702 (define stack-saved? #f)
2704 (define (save-stack . narrowing)
2705 (if (not stack-saved?)
2707 (let ((stacks (fluid-ref %stacks)))
2708 (fluid-set! the-last-stack
2709 ;; (make-stack obj inner outer inner outer ...)
2711 ;; In this case, cut away the make-stack frame, the
2712 ;; save-stack frame, and then narrow as specified by the
2713 ;; user, delimited by the nearest start-stack invocation,
2715 (apply make-stack #t
2717 (if (pair? stacks) (cdar stacks) 0)
2719 (set! stack-saved? #t))))
2721 (define before-error-hook (make-hook))
2722 (define after-error-hook (make-hook))
2723 (define before-backtrace-hook (make-hook))
2724 (define after-backtrace-hook (make-hook))
2726 (define has-shown-debugger-hint? #f)
2728 (define (handle-system-error key . args)
2729 (let ((cep (current-error-port)))
2730 (cond ((not (stack? (fluid-ref the-last-stack))))
2731 ((memq 'backtrace (debug-options-interface))
2732 (let ((highlights (if (or (eq? key 'wrong-type-arg)
2733 (eq? key 'out-of-range))
2736 (run-hook before-backtrace-hook)
2738 (display "Backtrace:\n")
2739 (display-backtrace (fluid-ref the-last-stack) cep
2742 (run-hook after-backtrace-hook))))
2743 (run-hook before-error-hook)
2744 (apply display-error (fluid-ref the-last-stack) cep args)
2745 (run-hook after-error-hook)
2747 (throw 'abort key)))
2749 (define (quit . args)
2750 (apply throw 'quit args))
2754 (define (gc-run-time)
2755 (cdr (assq 'gc-time-taken (gc-stats))))
2757 (define before-read-hook (make-hook))
2758 (define after-read-hook (make-hook))
2759 (define before-eval-hook (make-hook 1))
2760 (define after-eval-hook (make-hook 1))
2761 (define before-print-hook (make-hook 1))
2762 (define after-print-hook (make-hook 1))
2764 ;;; The default repl-reader function. We may override this if we've
2765 ;;; the readline library.
2767 (lambda* (prompt #:optional (reader (fluid-ref current-reader)))
2768 (if (not (char-ready?))
2769 (display (if (string? prompt) prompt (prompt))))
2771 (run-hook before-read-hook)
2772 ((or reader read) (current-input-port))))
2777 ;;; {IOTA functions: generating lists of numbers}
2781 (let loop ((count (1- n)) (result '()))
2782 (if (< count 0) result
2783 (loop (1- count) (cons count result)))))
2789 ;;; with `continue' and `break'.
2792 ;; The inliner will remove the prompts at compile-time if it finds that
2793 ;; `continue' or `break' are not used.
2795 (define-syntax while
2798 ((while cond body ...)
2799 #`(let ((break-tag (make-prompt-tag "break"))
2800 (continue-tag (make-prompt-tag "continue")))
2804 (define-syntax #,(datum->syntax #'while 'break)
2808 #'(abort-to-prompt break-tag))
2810 (syntax-violation 'break "too many arguments" x))
2813 (abort-to-prompt break-tag))))))
2818 (define-syntax #,(datum->syntax #'while 'continue)
2822 #'(abort-to-prompt continue-tag))
2824 (syntax-violation 'continue "too many arguments" x))
2827 (apply abort-to-prompt continue-tag args))))))
2828 (do () ((not cond)) body ...))
2829 (lambda (k) (lp)))))
2836 ;;; {Module System Macros}
2839 ;; Return a list of expressions that evaluate to the appropriate
2840 ;; arguments for resolve-interface according to SPEC.
2844 (if (memq 'prefix (read-options))
2845 (error "boot-9 must be compiled with #:kw, not :kw")))
2847 (define (keyword-like-symbol->keyword sym)
2848 (symbol->keyword (string->symbol (substring (symbol->string sym) 1))))
2850 ;; FIXME: we really need to clean up the guts of the module system.
2851 ;; We can compile to something better than process-define-module.
2852 (define-syntax define-module
2854 (define (keyword-like? stx)
2855 (let ((dat (syntax->datum stx)))
2857 (eqv? (string-ref (symbol->string dat) 0) #\:))))
2858 (define (->keyword sym)
2859 (symbol->keyword (string->symbol (substring (symbol->string sym) 1))))
2861 (define (quotify-iface args)
2862 (let loop ((in args) (out '()))
2865 ;; The user wanted #:foo, but wrote :foo. Fix it.
2866 ((sym . in) (keyword-like? #'sym)
2867 (loop #`(#,(->keyword (syntax->datum #'sym)) . in) out))
2868 ((kw . in) (not (keyword? (syntax->datum #'kw)))
2869 (syntax-violation 'define-module "expected keyword arg" x #'kw))
2870 ((#:renamer renamer . in)
2871 (loop #'in (cons* #'renamer #:renamer out)))
2873 (loop #'in (cons* #''val #'kw out))))))
2875 (define (quotify args)
2876 ;; Just quote everything except #:use-module and #:use-syntax. We
2877 ;; need to know about all arguments regardless since we want to turn
2878 ;; symbols that look like keywords into real keywords, and the
2879 ;; keyword args in a define-module form are not regular
2880 ;; (i.e. no-backtrace doesn't take a value).
2881 (let loop ((in args) (out '()))
2884 ;; The user wanted #:foo, but wrote :foo. Fix it.
2885 ((sym . in) (keyword-like? #'sym)
2886 (loop #`(#,(->keyword (syntax->datum #'sym)) . in) out))
2887 ((kw . in) (not (keyword? (syntax->datum #'kw)))
2888 (syntax-violation 'define-module "expected keyword arg" x #'kw))
2889 ((#:no-backtrace . in)
2890 (loop #'in (cons #:no-backtrace out)))
2892 (loop #'in (cons #:pure out)))
2894 (syntax-violation 'define-module "keyword arg without value" x #'kw))
2895 ((use-module (name name* ...) . in)
2896 (and (memq (syntax->datum #'use-module) '(#:use-module #:use-syntax))
2897 (and-map symbol? (syntax->datum #'(name name* ...))))
2899 (cons* #''((name name* ...))
2902 ((use-module ((name name* ...) arg ...) . in)
2903 (and (memq (syntax->datum #'use-module) '(#:use-module #:use-syntax))
2904 (and-map symbol? (syntax->datum #'(name name* ...))))
2906 (cons* #`(list '(name name* ...) #,@(quotify-iface #'(arg ...)))
2909 ((#:autoload name bindings . in)
2910 (loop #'in (cons* #''bindings #''name #:autoload out)))
2912 (loop #'in (cons* #''val #'kw out))))))
2915 ((_ (name name* ...) arg ...)
2916 (with-syntax (((quoted-arg ...) (quotify #'(arg ...))))
2917 #'(eval-when (eval load compile expand)
2918 (let ((m (process-define-module
2919 (list '(name name* ...)
2920 #:filename (assq-ref
2921 (or (current-source-location) '())
2924 (set-current-module m)
2927 ;; The guts of the use-modules macro. Add the interfaces of the named
2928 ;; modules to the use-list of the current module, in order.
2930 ;; This function is called by "modules.c". If you change it, be sure
2931 ;; to change scm_c_use_module as well.
2933 (define (process-use-modules module-interface-args)
2934 (let ((interfaces (map (lambda (mif-args)
2935 (or (apply resolve-interface mif-args)
2936 (error "no such module" mif-args)))
2937 module-interface-args)))
2938 (call-with-deferred-observers
2940 (module-use-interfaces! (current-module) interfaces)))))
2942 (define-syntax use-modules
2944 (define (keyword-like? stx)
2945 (let ((dat (syntax->datum stx)))
2947 (eqv? (string-ref (symbol->string dat) 0) #\:))))
2948 (define (->keyword sym)
2949 (symbol->keyword (string->symbol (substring (symbol->string sym) 1))))
2951 (define (quotify-iface args)
2952 (let loop ((in args) (out '()))
2955 ;; The user wanted #:foo, but wrote :foo. Fix it.
2956 ((sym . in) (keyword-like? #'sym)
2957 (loop #`(#,(->keyword (syntax->datum #'sym)) . in) out))
2958 ((kw . in) (not (keyword? (syntax->datum #'kw)))
2959 (syntax-violation 'define-module "expected keyword arg" x #'kw))
2960 ((#:renamer renamer . in)
2961 (loop #'in (cons* #'renamer #:renamer out)))
2963 (loop #'in (cons* #''val #'kw out))))))
2965 (define (quotify specs)
2966 (let lp ((in specs) (out '()))
2969 (((name name* ...) . in)
2970 (and-map symbol? (syntax->datum #'(name name* ...)))
2971 (lp #'in (cons #''((name name* ...)) out)))
2972 ((((name name* ...) arg ...) . in)
2973 (and-map symbol? (syntax->datum #'(name name* ...)))
2974 (with-syntax (((quoted-arg ...) (quotify-iface #'(arg ...))))
2975 (lp #'in (cons #`(list '(name name* ...) quoted-arg ...)
2980 (with-syntax (((quoted-args ...) (quotify #'(spec ...))))
2981 #'(eval-when (eval load compile expand)
2982 (process-use-modules (list quoted-args ...))
2985 (define-syntax use-syntax
2989 (eval-when (eval load compile expand)
2990 (issue-deprecation-warning
2991 "`use-syntax' is deprecated. Please contact guile-devel for more info."))
2992 (use-modules spec ...)))))
2994 (include-from-path "ice-9/r6rs-libraries")
2996 (define-syntax define-private
3001 (define-syntax define-public
3003 ((_ (name . args) . body)
3004 (define-public name (lambda args . body)))
3010 (define-syntax defmacro-public
3012 ((_ name args . body)
3014 (defmacro name args . body)
3015 (export-syntax name)))))
3017 ;; And now for the most important macro.
3020 ((_ formals body ...)
3021 (lambda formals body ...))))
3024 ;; Export a local variable
3026 ;; This function is called from "modules.c". If you change it, be
3027 ;; sure to update "modules.c" as well.
3029 (define (module-export! m names)
3030 (let ((public-i (module-public-interface m)))
3031 (for-each (lambda (name)
3032 (let* ((internal-name (if (pair? name) (car name) name))
3033 (external-name (if (pair? name) (cdr name) name))
3034 (var (module-ensure-local-variable! m internal-name)))
3035 (module-add! public-i external-name var)))
3038 (define (module-replace! m names)
3039 (let ((public-i (module-public-interface m)))
3040 (for-each (lambda (name)
3041 (let* ((internal-name (if (pair? name) (car name) name))
3042 (external-name (if (pair? name) (cdr name) name))
3043 (var (module-ensure-local-variable! m internal-name)))
3044 (set-object-property! var 'replace #t)
3045 (module-add! public-i external-name var)))
3048 ;; Export all local variables from a module
3050 (define (module-export-all! mod)
3051 (define (fresh-interface!)
3052 (let ((iface (make-module)))
3053 (set-module-name! iface (module-name mod))
3054 (set-module-version! iface (module-version mod))
3055 (set-module-kind! iface 'interface)
3056 (set-module-public-interface! mod iface)
3058 (let ((iface (or (module-public-interface mod)
3059 (fresh-interface!))))
3060 (set-module-obarray! iface (module-obarray mod))))
3062 ;; Re-export a imported variable
3064 (define (module-re-export! m names)
3065 (let ((public-i (module-public-interface m)))
3066 (for-each (lambda (name)
3067 (let* ((internal-name (if (pair? name) (car name) name))
3068 (external-name (if (pair? name) (cdr name) name))
3069 (var (module-variable m internal-name)))
3071 (error "Undefined variable:" internal-name))
3072 ((eq? var (module-local-variable m internal-name))
3073 (error "re-exporting local variable:" internal-name))
3075 (module-add! public-i external-name var)))))
3078 (define-syntax export
3081 (eval-when (eval load compile expand)
3082 (call-with-deferred-observers
3084 (module-export! (current-module) '(name ...))))))))
3086 (define-syntax re-export
3089 (eval-when (eval load compile expand)
3090 (call-with-deferred-observers
3092 (module-re-export! (current-module) '(name ...))))))))
3094 (define-syntax export-syntax
3097 (export name ...))))
3099 (define-syntax re-export-syntax
3102 (re-export name ...))))
3104 (define load load-module)
3111 (define make-mutable-parameter
3112 (let ((make (lambda (fluid converter)
3116 (fluid-set! fluid (converter (car args))))))))
3117 (lambda* (init #:optional (converter identity))
3118 (let ((fluid (make-fluid)))
3119 (fluid-set! fluid (converter init))
3120 (make fluid converter)))))
3124 ;;; {Handling of duplicate imported bindings}
3127 ;; Duplicate handlers take the following arguments:
3129 ;; module importing module
3130 ;; name conflicting name
3131 ;; int1 old interface where name occurs
3132 ;; val1 value of binding in old interface
3133 ;; int2 new interface where name occurs
3134 ;; val2 value of binding in new interface
3135 ;; var previous resolution or #f
3136 ;; val value of previous resolution
3138 ;; A duplicate handler can take three alternative actions:
3140 ;; 1. return #f => leave responsibility to next handler
3141 ;; 2. exit with an error
3142 ;; 3. return a variable resolving the conflict
3145 (define duplicate-handlers
3146 (let ((m (make-module 7)))
3148 (define (check module name int1 val1 int2 val2 var val)
3149 (scm-error 'misc-error
3151 "~A: `~A' imported from both ~A and ~A"
3152 (list (module-name module)
3158 (define (warn module name int1 val1 int2 val2 var val)
3159 (format (current-error-port)
3160 "WARNING: ~A: `~A' imported from both ~A and ~A\n"
3161 (module-name module)
3167 (define (replace module name int1 val1 int2 val2 var val)
3168 (let ((old (or (and var (object-property var 'replace) var)
3169 (module-variable int1 name)))
3170 (new (module-variable int2 name)))
3171 (if (object-property old 'replace)
3172 (and (or (eq? old new)
3173 (not (object-property new 'replace)))
3175 (and (object-property new 'replace)
3178 (define (warn-override-core module name int1 val1 int2 val2 var val)
3179 (and (eq? int1 the-scm-module)
3181 (format (current-error-port)
3182 "WARNING: ~A: imported module ~A overrides core binding `~A'\n"
3183 (module-name module)
3186 (module-local-variable int2 name))))
3188 (define (first module name int1 val1 int2 val2 var val)
3189 (or var (module-local-variable int1 name)))
3191 (define (last module name int1 val1 int2 val2 var val)
3192 (module-local-variable int2 name))
3194 (define (noop module name int1 val1 int2 val2 var val)
3197 (set-module-name! m 'duplicate-handlers)
3198 (set-module-kind! m 'interface)
3199 (module-define! m 'check check)
3200 (module-define! m 'warn warn)
3201 (module-define! m 'replace replace)
3202 (module-define! m 'warn-override-core warn-override-core)
3203 (module-define! m 'first first)
3204 (module-define! m 'last last)
3205 (module-define! m 'merge-generics noop)
3206 (module-define! m 'merge-accessors noop)
3209 (define (lookup-duplicates-handlers handler-names)
3211 (map (lambda (handler-name)
3212 (or (module-symbol-local-binding
3213 duplicate-handlers handler-name #f)
3214 (error "invalid duplicate handler name:"
3216 (if (list? handler-names)
3218 (list handler-names)))))
3220 (define default-duplicate-binding-procedures
3221 (make-mutable-parameter #f))
3223 (define default-duplicate-binding-handler
3224 (make-mutable-parameter '(replace warn-override-core warn last)
3225 (lambda (handler-names)
3226 (default-duplicate-binding-procedures
3227 (lookup-duplicates-handlers handler-names))
3232 ;;; {`cond-expand' for SRFI-0 support.}
3234 ;;; This syntactic form expands into different commands or
3235 ;;; definitions, depending on the features provided by the Scheme
3241 ;;; --> (cond-expand <cond-expand-clause>+)
3242 ;;; | (cond-expand <cond-expand-clause>* (else <command-or-definition>))
3243 ;;; <cond-expand-clause>
3244 ;;; --> (<feature-requirement> <command-or-definition>*)
3245 ;;; <feature-requirement>
3246 ;;; --> <feature-identifier>
3247 ;;; | (and <feature-requirement>*)
3248 ;;; | (or <feature-requirement>*)
3249 ;;; | (not <feature-requirement>)
3250 ;;; <feature-identifier>
3251 ;;; --> <a symbol which is the name or alias of a SRFI>
3253 ;;; Additionally, this implementation provides the
3254 ;;; <feature-identifier>s `guile' and `r5rs', so that programs can
3255 ;;; determine the implementation type and the supported standard.
3257 ;;; Currently, the following feature identifiers are supported:
3259 ;;; guile r5rs srfi-0 srfi-4 srfi-6 srfi-13 srfi-14 srfi-55 srfi-61
3261 ;;; Remember to update the features list when adding more SRFIs.
3264 (define %cond-expand-features
3265 ;; Adjust the above comment when changing this.
3269 srfi-0 ;; cond-expand itself
3270 srfi-4 ;; homogenous numeric vectors
3271 srfi-6 ;; open-input-string etc, in the guile core
3272 srfi-13 ;; string library
3273 srfi-14 ;; character sets
3274 srfi-55 ;; require-extension
3275 srfi-61 ;; general cond clause
3278 ;; This table maps module public interfaces to the list of features.
3280 (define %cond-expand-table (make-hash-table 31))
3282 ;; Add one or more features to the `cond-expand' feature list of the
3285 (define (cond-expand-provide module features)
3286 (let ((mod (module-public-interface module)))
3288 (hashq-set! %cond-expand-table mod
3289 (append (hashq-ref %cond-expand-table mod '())
3292 (define-macro (cond-expand . clauses)
3293 (let ((syntax-error (lambda (cl)
3294 (error "invalid clause in `cond-expand'" cl))))
3300 (or (memq clause %cond-expand-features)
3301 (let lp ((uses (module-uses (current-module))))
3304 (hashq-ref %cond-expand-table
3310 ((eq? 'and (car clause))
3311 (let lp ((l (cdr clause)))
3315 (and (test-clause (car l)) (lp (cdr l))))
3317 (syntax-error clause)))))
3318 ((eq? 'or (car clause))
3319 (let lp ((l (cdr clause)))
3323 (or (test-clause (car l)) (lp (cdr l))))
3325 (syntax-error clause)))))
3326 ((eq? 'not (car clause))
3327 (cond ((not (pair? (cdr clause)))
3328 (syntax-error clause))
3329 ((pair? (cddr clause))
3330 ((syntax-error clause))))
3331 (not (test-clause (cadr clause))))
3333 (syntax-error clause))))
3335 (syntax-error clause))))))
3336 (let lp ((c clauses))
3339 (error "Unfulfilled `cond-expand'"))
3342 ((not (pair? (car c)))
3343 (syntax-error (car c)))
3344 ((test-clause (caar c))
3345 `(begin ,@(cdar c)))
3346 ((eq? (caar c) 'else)
3349 `(begin ,@(cdar c)))
3353 ;; This procedure gets called from the startup code with a list of
3354 ;; numbers, which are the numbers of the SRFIs to be loaded on startup.
3356 (define (use-srfis srfis)
3357 (process-use-modules
3359 (list (list 'srfi (string->symbol
3360 (string-append "srfi-" (number->string num))))))
3365 ;;; srfi-55: require-extension
3368 (define-macro (require-extension extension-spec)
3369 ;; This macro only handles the srfi extension, which, at present, is
3370 ;; the only one defined by the standard.
3371 (if (not (pair? extension-spec))
3372 (scm-error 'wrong-type-arg "require-extension"
3373 "Not an extension: ~S" (list extension-spec) #f))
3374 (let ((extension (car extension-spec))
3375 (extension-args (cdr extension-spec)))
3378 (let ((use-list '()))
3381 (if (not (integer? i))
3382 (scm-error 'wrong-type-arg "require-extension"
3383 "Invalid srfi name: ~S" (list i) #f))
3384 (let ((srfi-sym (string->symbol
3385 (string-append "srfi-" (number->string i)))))
3386 (if (not (memq srfi-sym %cond-expand-features))
3387 (set! use-list (cons `(use-modules (srfi ,srfi-sym))
3390 (if (pair? use-list)
3391 ;; i.e. (begin (use-modules x) (use-modules y) (use-modules z))
3392 `(begin ,@(reverse! use-list)))))
3395 'wrong-type-arg "require-extension"
3396 "Not a recognized extension type: ~S" (list extension) #f)))))
3400 ;;; {Load emacs interface support if emacs option is given.}
3403 (define (named-module-use! user usee)
3404 (module-use! (resolve-module user) (resolve-interface usee)))
3406 (define (load-emacs-interface)
3407 (and (provided? 'debug-extensions)
3408 (debug-enable 'backtrace))
3409 (named-module-use! '(guile-user) '(ice-9 emacs)))
3413 (define using-readline?
3414 (let ((using-readline? (make-fluid)))
3415 (make-procedure-with-setter
3416 (lambda () (fluid-ref using-readline?))
3417 (lambda (v) (fluid-set! using-readline? v)))))
3420 (let ((guile-user-module (resolve-module '(guile-user))))
3422 ;; Load emacs interface support if emacs option is given.
3423 (if (and (module-defined? guile-user-module 'use-emacs-interface)
3424 (module-ref guile-user-module 'use-emacs-interface))
3425 (load-emacs-interface))
3427 ;; Use some convenient modules (in reverse order)
3429 (set-current-module guile-user-module)
3430 (process-use-modules
3435 (if (provided? 'regex)
3438 (if (provided? 'threads)
3439 '(((ice-9 threads)))
3441 ;; load debugger on demand
3442 (module-autoload! guile-user-module '(system vm debug) '(debug))
3444 ;; Note: SIGFPE, SIGSEGV and SIGBUS are actually "query-only" (see
3445 ;; scmsigs.c scm_sigaction_for_thread), so the handlers setup here have
3447 (let ((old-handlers #f)
3448 ;; We can't use @ here, as modules have been booted, but in Guile's
3449 ;; build the srfi-1 helper lib hasn't been built yet, which will
3450 ;; result in an error when (system repl repl) is loaded at compile
3451 ;; time (to see if it is a macro or not).
3452 (start-repl (module-ref (resolve-module '(system repl repl))
3454 (signals (if (provided? 'posix)
3455 `((,SIGINT . "User interrupt")
3456 (,SIGFPE . "Arithmetic error")
3458 . "Bad memory access (Segmentation violation)"))
3460 ;; no SIGBUS on mingw
3461 (if (defined? 'SIGBUS)
3462 (set! signals (acons SIGBUS "Bad memory access (bus error)"
3469 (let ((make-handler (lambda (msg)
3471 ;; Make a backup copy of the stack
3472 (fluid-set! before-signal-stack
3473 (fluid-ref the-last-stack))
3481 (map (lambda (sig-msg)
3482 (sigaction (car sig-msg)
3483 (make-handler (cdr sig-msg))))
3486 ;; the protected thunk.
3488 (let ((status (start-repl 'scheme)))
3489 (run-hook exit-hook)
3494 (map (lambda (sig-msg old-handler)
3495 (if (not (car old-handler))
3496 ;; restore original C handler.
3497 (sigaction (car sig-msg) #f)
3498 ;; restore Scheme handler, SIG_IGN or SIG_DFL.
3499 (sigaction (car sig-msg)
3501 (cdr old-handler))))
3502 signals old-handlers))))))
3504 ;;; This hook is run at the very end of an interactive session.
3506 (define exit-hook (make-hook))
3510 ;;; {Deprecated stuff}
3514 (module-use! the-scm-module (resolve-interface '(ice-9 deprecated))))
3518 ;;; Place the user in the guile-user module.
3522 (module-use! the-scm-module (resolve-interface '(srfi srfi-4)))
3524 (define-module (guile-user)
3525 #:autoload (system base compile) (compile))
3527 ;; Remain in the `(guile)' module at compilation-time so that the
3528 ;; `-Wunused-toplevel' warning works as expected.
3529 (eval-when (compile) (set-current-module the-root-module))
3531 ;;; boot-9.scm ends here