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 . stem)
52 (gensym (if (pair? stem) (car stem) "prompt")))
53 (define default-prompt-tag
54 ;; not sure if we should expose this to the user as a fluid
55 (let ((%default-prompt-tag (make-prompt-tag)))
57 %default-prompt-tag)))
59 (define (call-with-prompt tag thunk handler)
60 (@prompt tag (thunk) handler))
61 (define (abort-to-prompt tag . args)
65 ;; Define catch and with-throw-handler, using some common helper routines and a
66 ;; shared fluid. Hide the helpers in a lexical contour.
69 ;; Ideally we'd like to be able to give these default values for all threads,
70 ;; even threads not created by Guile; but alack, that does not currently seem
71 ;; possible. So wrap the getters in thunks.
72 (define %running-exception-handlers (make-fluid))
73 (define %exception-handler (make-fluid))
75 (define (running-exception-handlers)
76 (or (fluid-ref %running-exception-handlers)
78 (fluid-set! %running-exception-handlers '())
80 (define (exception-handler)
81 (or (fluid-ref %exception-handler)
83 (fluid-set! %exception-handler default-exception-handler)
84 default-exception-handler)))
86 (define (default-exception-handler k . args)
90 ((not (pair? args)) 0)
91 ((integer? (car args)) (car args))
95 (format (current-error-port) "guile: uncaught throw to ~a: ~a\n" k args)
98 (define (default-throw-handler prompt-tag catch-k)
99 (let ((prev (exception-handler)))
100 (lambda (thrown-k . args)
101 (if (or (eq? thrown-k catch-k) (eqv? catch-k #t))
102 (apply abort-to-prompt prompt-tag thrown-k args)
103 (apply prev thrown-k args)))))
105 (define (custom-throw-handler prompt-tag catch-k pre)
106 (let ((prev (exception-handler)))
107 (lambda (thrown-k . args)
108 (if (or (eq? thrown-k catch-k) (eqv? catch-k #t))
109 (let ((running (running-exception-handlers)))
110 (with-fluids ((%running-exception-handlers (cons pre running)))
111 (if (not (memq pre running))
112 (apply pre thrown-k args))
115 (apply abort-to-prompt prompt-tag thrown-k args)
116 (apply prev thrown-k args))))
117 (apply prev thrown-k args)))))
120 ;; Until we get optargs support into Guile's C evaluator, we have to fake it
122 (lambda (k thunk handler . 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 (null? pre-unwind-handler)
167 (default-throw-handler tag k)
168 (custom-throw-handler tag k
169 (car pre-unwind-handler)))))
171 (lambda (cont k . args)
172 (apply handler k args))))))
174 (define! 'with-throw-handler
175 (lambda (k thunk pre-unwind-handler)
176 "Add @var{handler} to the dynamic context as a throw handler
177 for key @var{key}, then invoke @var{thunk}."
178 (if (not (or (symbol? k) (eqv? k #t)))
179 (scm-error "with-throw-handler" 'wrong-type-arg
180 "Wrong type argument in position ~a: ~a"
181 (list 1 k) (list k)))
182 (with-fluids ((%exception-handler
183 (custom-throw-handler #f k pre-unwind-handler)))
188 "Invoke the catch form matching @var{key}, passing @var{args} to the
191 @var{key} is a symbol. It will match catches of the same symbol or of @code{#t}.
193 If there is no handler at all, Guile prints an error and then exits."
194 (if (not (symbol? key))
195 ((exception-handler) 'wrong-type-arg "throw"
196 "Wrong type argument in position ~a: ~a" (list 1 key) (list key))
197 (apply (exception-handler) key args)))))
202 ;;; {R4RS compliance}
205 (primitive-load-path "ice-9/r4rs")
209 ;;; {Simple Debugging Tools}
212 ;; peek takes any number of arguments, writes them to the
213 ;; current ouput port, and returns the last argument.
214 ;; It is handy to wrap around an expression to look at
215 ;; a value each time is evaluated, e.g.:
217 ;; (+ 10 (troublesome-fn))
218 ;; => (+ 10 (pk 'troublesome-fn-returned (troublesome-fn)))
221 (define (peek . stuff)
226 (car (last-pair stuff)))
231 (define (warn . stuff)
232 (with-output-to-port (current-error-port)
235 (display ";;; WARNING ")
238 (car (last-pair stuff)))))
245 (define (provide sym)
246 (if (not (memq sym *features*))
247 (set! *features* (cons sym *features*))))
249 ;; Return #t iff FEATURE is available to this Guile interpreter. In SLIB,
250 ;; provided? also checks to see if the module is available. We should do that
253 (define (provided? feature)
254 (and (memq feature *features*) #t))
258 ;;; {and-map and or-map}
260 ;;; (and-map fn lst) is like (and (fn (car lst)) (fn (cadr lst)) (fn...) ...)
261 ;;; (or-map fn lst) is like (or (fn (car lst)) (fn (cadr lst)) (fn...) ...)
266 ;; Apply f to successive elements of l until exhaustion or f returns #f.
267 ;; If returning early, return #f. Otherwise, return the last value returned
268 ;; by f. If f has never been called because l is empty, return #t.
270 (define (and-map f lst)
271 (let loop ((result #t)
276 (loop (f (car l)) (cdr l))))))
280 ;; Apply f to successive elements of l until exhaustion or while f returns #f.
281 ;; If returning early, return the return value of f.
283 (define (or-map f lst)
284 (let loop ((result #f)
288 (loop (f (car l)) (cdr l))))))
292 ;; let format alias simple-format until the more complete version is loaded
294 (define format simple-format)
296 ;; this is scheme wrapping the C code so the final pred call is a tail call,
298 (define (string-any char_pred s . rest)
299 (let ((start (if (null? rest)
301 (end (if (or (null? rest) (null? (cdr rest)))
302 (string-length s) (cadr rest))))
303 (if (and (procedure? char_pred)
305 (<= end (string-length s))) ;; let c-code handle range error
306 (or (string-any-c-code char_pred s start (1- end))
307 (char_pred (string-ref s (1- end))))
308 (string-any-c-code char_pred s start end))))
310 ;; this is scheme wrapping the C code so the final pred call is a tail call,
312 (define (string-every char_pred s . rest)
313 (let ((start (if (null? rest)
315 (end (if (or (null? rest) (null? (cdr rest)))
316 (string-length s) (cadr rest))))
317 (if (and (procedure? char_pred)
319 (<= end (string-length s))) ;; let c-code handle range error
320 (and (string-every-c-code char_pred s start (1- end))
321 (char_pred (string-ref s (1- end))))
322 (string-every-c-code char_pred s start end))))
324 ;; A variant of string-fill! that we keep for compatability
326 (define (substring-fill! str start end fill)
327 (string-fill! str fill start end))
331 ;; Define a minimal stub of the module API for psyntax, before modules
333 (define (module-name x)
335 (define (module-define! module sym val)
336 (let ((v (hashq-ref (%get-pre-modules-obarray) sym)))
338 (variable-set! v val)
339 (hashq-set! (%get-pre-modules-obarray) sym
340 (make-variable val)))))
341 (define (module-ref module sym)
342 (let ((v (module-variable module sym)))
343 (if v (variable-ref v) (error "badness!" (pk module) (pk sym)))))
344 (define (resolve-module . args)
347 ;; Input hook to syncase -- so that we might be able to pass annotated
348 ;; expressions in. Currently disabled. Maybe we should just use
349 ;; source-properties directly.
350 (define (annotation? x) #f)
352 ;; API provided by psyntax
353 (define syntax-violation #f)
354 (define datum->syntax #f)
355 (define syntax->datum #f)
356 (define identifier? #f)
357 (define generate-temporaries #f)
358 (define bound-identifier=? #f)
359 (define free-identifier=? #f)
361 ;; $sc-dispatch is an implementation detail of psyntax. It is used by
362 ;; expanded macros, to dispatch an input against a set of patterns.
363 (define $sc-dispatch #f)
366 (primitive-load-path "ice-9/psyntax-pp")
367 ;; The binding for `macroexpand' has now been overridden, making psyntax the
374 ((_ x y ...) (if x (and y ...) #f))))
380 ((_ x y ...) (let ((t x)) (if t t (or y ...))))))
382 ;; The "maybe-more" bits are something of a hack, so that we can support
383 ;; SRFI-61. Rewrites into a standalone syntax-case macro would be
386 (syntax-rules (=> else)
387 ((_ "maybe-more" test consequent)
388 (if test consequent))
390 ((_ "maybe-more" test consequent clause ...)
391 (if test consequent (cond clause ...)))
393 ((_ (else else1 else2 ...))
394 (begin else1 else2 ...))
396 ((_ (test => receiver) more-clause ...)
398 (cond "maybe-more" t (receiver t) more-clause ...)))
400 ((_ (generator guard => receiver) more-clause ...)
401 (call-with-values (lambda () generator)
404 (apply guard t) (apply receiver t) more-clause ...))))
406 ((_ (test => receiver ...) more-clause ...)
407 (syntax-violation 'cond "wrong number of receiver expressions"
408 '(test => receiver ...)))
409 ((_ (generator guard => receiver ...) more-clause ...)
410 (syntax-violation 'cond "wrong number of receiver expressions"
411 '(generator guard => receiver ...)))
413 ((_ (test) more-clause ...)
415 (cond "maybe-more" t t more-clause ...)))
417 ((_ (test body1 body2 ...) more-clause ...)
419 test (begin body1 body2 ...) more-clause ...))))
425 (let ((atom-key (key ...)))
426 (case atom-key clauses ...)))
428 (else result1 result2 ...))
429 (begin result1 result2 ...))
431 ((atoms ...) result1 result2 ...))
432 (if (memv key '(atoms ...))
433 (begin result1 result2 ...)))
435 ((atoms ...) result1 result2 ...)
437 (if (memv key '(atoms ...))
438 (begin result1 result2 ...)
439 (case key clause clauses ...)))))
443 ((do ((var init step ...) ...)
456 (loop (do "step" var step ...)
466 ((_ exp) (make-promise (lambda () exp)))))
468 (include-from-path "ice-9/quasisyntax")
475 (define-syntax define-macro
479 ((_ (macro . args) doc body1 body ...)
480 (string? (syntax->datum #'doc))
481 #'(define-macro macro doc (lambda args body1 body ...)))
482 ((_ (macro . args) body ...)
483 #'(define-macro macro #f (lambda args body ...)))
484 ((_ macro doc transformer)
485 (or (string? (syntax->datum #'doc))
486 (not (syntax->datum #'doc)))
487 #'(define-syntax macro
490 #((macro-type . defmacro)
491 (defmacro-args args))
494 (let ((v (syntax->datum #'args)))
495 (datum->syntax y (apply transformer v)))))))))))
497 (define-syntax defmacro
499 "Define a defmacro, with the old lispy defun syntax."
501 ((_ macro args doc body1 body ...)
502 (string? (syntax->datum #'doc))
503 #'(define-macro macro doc (lambda args body1 body ...)))
504 ((_ macro args body ...)
505 #'(define-macro macro #f (lambda args body ...))))))
513 ;;; Depends on: defmacro
516 (defmacro begin-deprecated forms
517 (if (include-deprecated-features)
523 ;;; {Trivial Functions}
526 (define (identity x) x)
527 (define (and=> value procedure) (and value (procedure value)))
528 (define call/cc call-with-current-continuation)
530 ;;; apply-to-args is functionally redundant with apply and, worse,
531 ;;; is less general than apply since it only takes two arguments.
533 ;;; On the other hand, apply-to-args is a syntacticly convenient way to
534 ;;; perform binding in many circumstances when the "let" family of
535 ;;; of forms don't cut it. E.g.:
537 ;;; (apply-to-args (return-3d-mouse-coords)
542 (define (apply-to-args args fn) (apply fn args))
544 (defmacro false-if-exception (expr)
547 ;; avoid saving backtraces inside false-if-exception
548 (with-fluids ((the-last-stack (fluid-ref the-last-stack)))
554 ;;; {General Properties}
557 ;; This is a more modern interface to properties. It will replace all
558 ;; other property-like things eventually.
560 (define (make-object-property)
561 (let ((prop (primitive-make-property #f)))
562 (make-procedure-with-setter
563 (lambda (obj) (primitive-property-ref prop obj))
564 (lambda (obj val) (primitive-property-set! prop obj val)))))
568 ;;; {Symbol Properties}
571 (define (symbol-property sym prop)
572 (let ((pair (assoc prop (symbol-pref sym))))
573 (and pair (cdr pair))))
575 (define (set-symbol-property! sym prop val)
576 (let ((pair (assoc prop (symbol-pref sym))))
579 (symbol-pset! sym (acons prop val (symbol-pref sym))))))
581 (define (symbol-property-remove! sym prop)
582 (let ((pair (assoc prop (symbol-pref sym))))
584 (symbol-pset! sym (delq! pair (symbol-pref sym))))))
591 (define (array-shape a)
592 (map (lambda (ind) (if (number? ind) (list 0 (+ -1 ind)) ind))
593 (array-dimensions a)))
600 (define (kw-arg-ref args kw)
601 (let ((rem (member kw args)))
602 (and rem (pair? (cdr rem)) (cadr rem))))
609 (define (struct-layout s)
610 (struct-ref (struct-vtable s) vtable-index-layout))
617 ;; Printing records: by default, records are printed as
619 ;; #<type-name field1: val1 field2: val2 ...>
621 ;; You can change that by giving a custom printing function to
622 ;; MAKE-RECORD-TYPE (after the list of field symbols). This function
623 ;; will be called like
625 ;; (<printer> object port)
627 ;; It should print OBJECT to PORT.
629 (define (inherit-print-state old-port new-port)
630 (if (get-print-state old-port)
631 (port-with-print-state new-port (get-print-state old-port))
634 ;; 0: type-name, 1: fields, 2: constructor
635 (define record-type-vtable
636 ;; FIXME: This should just call make-vtable, not make-vtable-vtable; but for
637 ;; that we need to expose the bare vtable-vtable to Scheme.
638 (make-vtable-vtable "prprpw" 0
640 (cond ((eq? s record-type-vtable)
641 (display "#<record-type-vtable>" p))
643 (display "#<record-type " p)
644 (display (record-type-name s) p)
647 (define (record-type? obj)
648 (and (struct? obj) (eq? record-type-vtable (struct-vtable obj))))
650 (define (make-record-type type-name fields . opt)
651 ;; Pre-generate constructors for nfields < 20.
652 (define-syntax make-constructor
654 (define *max-static-argument-count* 20)
655 (define (make-formals n)
661 (string (integer->char (+ (char->integer #\a) i)))))
665 ((_ rtd exp) (not (identifier? #'exp))
667 (make-constructor rtd n)))
671 (if (< n *max-static-argument-count*)
672 (cons (with-syntax (((formal ...) (make-formals n))
676 (make-struct rtd 0 formal ...))))
681 (if (= (length args) nfields)
682 (apply make-struct rtd 0 args)
683 (scm-error 'wrong-number-of-args
684 (format #f "make-~a" type-name)
685 "Wrong number of arguments" '() #f)))))))))
687 (define (default-record-printer s p)
689 (display (record-type-name (record-type-descriptor s)) p)
690 (let loop ((fields (record-type-fields (record-type-descriptor s)))
693 ((not (null? fields))
695 (display (car fields) p)
697 (display (struct-ref s off) p)
698 (loop (cdr fields) (+ 1 off)))))
701 (let ((rtd (make-struct record-type-vtable 0
704 (map (lambda (f) "pw") fields)))
705 (or (and (pair? opt) (car opt))
706 default-record-printer)
708 (copy-tree fields))))
709 (struct-set! rtd (+ vtable-offset-user 2)
710 (make-constructor rtd (length fields)))
711 ;; Temporary solution: Associate a name to the record type descriptor
712 ;; so that the object system can create a wrapper class for it.
713 (set-struct-vtable-name! rtd (if (symbol? type-name)
715 (string->symbol type-name)))
718 (define (record-type-name obj)
719 (if (record-type? obj)
720 (struct-ref obj vtable-offset-user)
721 (error 'not-a-record-type obj)))
723 (define (record-type-fields obj)
724 (if (record-type? obj)
725 (struct-ref obj (+ 1 vtable-offset-user))
726 (error 'not-a-record-type obj)))
728 (define (record-constructor rtd . opt)
730 (struct-ref rtd (+ 2 vtable-offset-user))
731 (let ((field-names (car opt)))
733 `(lambda ,field-names
734 (make-struct ',rtd 0 ,@(map (lambda (f)
735 (if (memq f field-names)
738 (record-type-fields rtd))))))))
740 (define (record-predicate rtd)
741 (lambda (obj) (and (struct? obj) (eq? rtd (struct-vtable obj)))))
743 (define (%record-type-error rtd obj) ;; private helper
744 (or (eq? rtd (record-type-descriptor obj))
745 (scm-error 'wrong-type-arg "%record-type-check"
746 "Wrong type record (want `~S'): ~S"
747 (list (record-type-name rtd) obj)
750 (define (record-accessor rtd field-name)
751 (let ((pos (list-index (record-type-fields rtd) field-name)))
753 (error 'no-such-field field-name))
755 (if (eq? (struct-vtable obj) rtd)
757 (%record-type-error rtd obj)))))
759 (define (record-modifier rtd field-name)
760 (let ((pos (list-index (record-type-fields rtd) field-name)))
762 (error 'no-such-field field-name))
764 (if (eq? (struct-vtable obj) rtd)
765 (struct-set! obj pos val)
766 (%record-type-error rtd obj)))))
768 (define (record? obj)
769 (and (struct? obj) (record-type? (struct-vtable obj))))
771 (define (record-type-descriptor obj)
774 (error 'not-a-record obj)))
783 (define (->bool x) (not (not x)))
790 (define (symbol-append . args)
791 (string->symbol (apply string-append (map symbol->string args))))
793 (define (list->symbol . args)
794 (string->symbol (apply list->string args)))
796 (define (symbol . args)
797 (string->symbol (apply string args)))
804 (define (list-index l k)
810 (loop (+ n 1) (cdr l))))))
814 (if (provided? 'posix)
815 (primitive-load-path "ice-9/posix"))
817 (if (provided? 'socket)
818 (primitive-load-path "ice-9/networking"))
820 ;; For reference, Emacs file-exists-p uses stat in this same way.
822 (if (provided? 'posix)
824 (->bool (stat str #f)))
826 (let ((port (catch 'system-error (lambda () (open-file str OPEN_READ))
828 (if port (begin (close-port port) #t)
831 (define file-is-directory?
832 (if (provided? 'posix)
834 (eq? (stat:type (stat str)) 'directory))
836 (let ((port (catch 'system-error
837 (lambda () (open-file (string-append str "/.")
840 (if port (begin (close-port port) #t)
843 (define (has-suffix? str suffix)
844 (string-suffix? suffix str))
846 (define (system-error-errno args)
847 (if (eq? (car args) 'system-error)
848 (car (list-ref args 4))
856 (define (error . args)
859 (scm-error 'misc-error #f "?" #f #f)
860 (let loop ((msg "~A")
862 (if (not (null? rest))
863 (loop (string-append msg " ~S")
865 (scm-error 'misc-error #f msg args #f)))))
867 ;; bad-throw is the hook that is called upon a throw to a an unhandled
868 ;; key (unless the throw has four arguments, in which case
869 ;; it's usually interpreted as an error throw.)
870 ;; If the key has a default handler (a throw-handler-default property),
871 ;; it is applied to the throw.
873 (define (bad-throw key . args)
874 (let ((default (symbol-property key 'throw-handler-default)))
875 (or (and default (apply default key args))
876 (apply error "unhandled-exception:" key args))))
880 (define (tm:sec obj) (vector-ref obj 0))
881 (define (tm:min obj) (vector-ref obj 1))
882 (define (tm:hour obj) (vector-ref obj 2))
883 (define (tm:mday obj) (vector-ref obj 3))
884 (define (tm:mon obj) (vector-ref obj 4))
885 (define (tm:year obj) (vector-ref obj 5))
886 (define (tm:wday obj) (vector-ref obj 6))
887 (define (tm:yday obj) (vector-ref obj 7))
888 (define (tm:isdst obj) (vector-ref obj 8))
889 (define (tm:gmtoff obj) (vector-ref obj 9))
890 (define (tm:zone obj) (vector-ref obj 10))
892 (define (set-tm:sec obj val) (vector-set! obj 0 val))
893 (define (set-tm:min obj val) (vector-set! obj 1 val))
894 (define (set-tm:hour obj val) (vector-set! obj 2 val))
895 (define (set-tm:mday obj val) (vector-set! obj 3 val))
896 (define (set-tm:mon obj val) (vector-set! obj 4 val))
897 (define (set-tm:year obj val) (vector-set! obj 5 val))
898 (define (set-tm:wday obj val) (vector-set! obj 6 val))
899 (define (set-tm:yday obj val) (vector-set! obj 7 val))
900 (define (set-tm:isdst obj val) (vector-set! obj 8 val))
901 (define (set-tm:gmtoff obj val) (vector-set! obj 9 val))
902 (define (set-tm:zone obj val) (vector-set! obj 10 val))
904 (define (tms:clock obj) (vector-ref obj 0))
905 (define (tms:utime obj) (vector-ref obj 1))
906 (define (tms:stime obj) (vector-ref obj 2))
907 (define (tms:cutime obj) (vector-ref obj 3))
908 (define (tms:cstime obj) (vector-ref obj 4))
910 (define file-position ftell)
911 (define (file-set-position port offset . whence)
912 (let ((whence (if (eq? whence '()) SEEK_SET (car whence))))
913 (seek port offset whence)))
915 (define (move->fdes fd/port fd)
916 (cond ((integer? fd/port)
917 (dup->fdes fd/port fd)
921 (primitive-move->fdes fd/port fd)
922 (set-port-revealed! fd/port 1)
925 (define (release-port-handle port)
926 (let ((revealed (port-revealed port)))
928 (set-port-revealed! port (- revealed 1)))))
930 (define (dup->port port/fd mode . maybe-fd)
931 (let ((port (fdopen (apply dup->fdes port/fd maybe-fd)
934 (set-port-revealed! port 1))
937 (define (dup->inport port/fd . maybe-fd)
938 (apply dup->port port/fd "r" maybe-fd))
940 (define (dup->outport port/fd . maybe-fd)
941 (apply dup->port port/fd "w" maybe-fd))
943 (define (dup port/fd . maybe-fd)
944 (if (integer? port/fd)
945 (apply dup->fdes port/fd maybe-fd)
946 (apply dup->port port/fd (port-mode port/fd) maybe-fd)))
948 (define (duplicate-port port modes)
949 (dup->port port modes))
951 (define (fdes->inport fdes)
952 (let loop ((rest-ports (fdes->ports fdes)))
953 (cond ((null? rest-ports)
954 (let ((result (fdopen fdes "r")))
955 (set-port-revealed! result 1)
957 ((input-port? (car rest-ports))
958 (set-port-revealed! (car rest-ports)
959 (+ (port-revealed (car rest-ports)) 1))
962 (loop (cdr rest-ports))))))
964 (define (fdes->outport fdes)
965 (let loop ((rest-ports (fdes->ports fdes)))
966 (cond ((null? rest-ports)
967 (let ((result (fdopen fdes "w")))
968 (set-port-revealed! result 1)
970 ((output-port? (car rest-ports))
971 (set-port-revealed! (car rest-ports)
972 (+ (port-revealed (car rest-ports)) 1))
975 (loop (cdr rest-ports))))))
977 (define (port->fdes port)
978 (set-port-revealed! port (+ (port-revealed port) 1))
981 (define (setenv name value)
983 (putenv (string-append name "=" value))
986 (define (unsetenv name)
987 "Remove the entry for NAME from the environment."
995 ;;; Here for backward compatability
997 (define scheme-file-suffix (lambda () ".scm"))
999 (define (in-vicinity vicinity file)
1000 (let ((tail (let ((len (string-length vicinity)))
1003 (string-ref vicinity (- len 1))))))
1004 (string-append vicinity
1013 ;;; {Help for scm_shell}
1015 ;;; The argument-processing code used by Guile-based shells generates
1016 ;;; Scheme code based on the argument list. This page contains help
1017 ;;; functions for the code it generates.
1020 (define (command-line) (program-arguments))
1022 ;; This is mostly for the internal use of the code generated by
1023 ;; scm_compile_shell_switches.
1025 (define (turn-on-debugging)
1026 (debug-enable 'debug)
1027 (debug-enable 'backtrace)
1028 (read-enable 'positions))
1030 (define (load-user-init)
1031 (let* ((home (or (getenv "HOME")
1032 (false-if-exception (passwd:dir (getpwuid (getuid))))
1033 "/")) ;; fallback for cygwin etc.
1034 (init-file (in-vicinity home ".guile")))
1035 (if (file-exists? init-file)
1036 (primitive-load init-file))))
1040 ;;; {The interpreter stack}
1043 ;; %stacks defined in stacks.c
1044 (define (%start-stack tag thunk)
1045 (let ((prompt-tag (make-prompt-tag "start-stack")))
1049 (with-fluids ((%stacks (acons tag prompt-tag
1050 (or (fluid-ref %stacks) '()))))
1053 (%start-stack tag (lambda () (apply k args)))))))
1054 (define-syntax start-stack
1057 (%start-stack tag (lambda () exp)))))
1061 ;;; {Loading by paths}
1064 ;;; Load a Scheme source file named NAME, searching for it in the
1065 ;;; directories listed in %load-path, and applying each of the file
1066 ;;; name extensions listed in %load-extensions.
1067 (define (load-from-path name)
1068 (start-stack 'load-stack
1069 (primitive-load-path name)))
1071 (define %load-verbosely #f)
1072 (define (assert-load-verbosity v) (set! %load-verbosely v))
1074 (define (%load-announce file)
1076 (with-output-to-port (current-error-port)
1079 (display "loading ")
1084 (set! %load-hook %load-announce)
1086 (define (load name . reader)
1087 ;; Returns the .go file corresponding to `name'. Does not search load
1088 ;; paths, only the fallback path. If the .go file is missing or out of
1089 ;; date, and autocompilation is enabled, will try autocompilation, just
1090 ;; as primitive-load-path does internally. primitive-load is
1091 ;; unaffected. Returns #f if autocompilation failed or was disabled.
1093 ;; NB: Unless we need to compile the file, this function should not cause
1094 ;; (system base compile) to be loaded up. For that reason compiled-file-name
1095 ;; partially duplicates functionality from (system base compile).
1096 (define (compiled-file-name canon-path)
1097 (and %compile-fallback-path
1099 %compile-fallback-path
1100 ;; no need for '/' separator here, canon-path is absolute
1102 (cond ((or (null? %load-compiled-extensions)
1103 (string-null? (car %load-compiled-extensions)))
1104 (warn "invalid %load-compiled-extensions"
1105 %load-compiled-extensions)
1107 (else (car %load-compiled-extensions))))))
1108 (define (fresh-compiled-file-name go-path)
1111 (let* ((scmstat (stat name))
1112 (gostat (stat go-path #f)))
1113 (if (and gostat (= (stat:mtime gostat) (stat:mtime scmstat)))
1117 (format (current-error-port)
1118 ";;; note: source file ~a\n;;; newer than compiled ~a\n"
1121 (%load-should-autocompile
1122 (%warn-autocompilation-enabled)
1123 (format (current-error-port) ";;; compiling ~a\n" name)
1124 (let ((cfn ((@ (system base compile) compile-file) name
1125 #:env (current-module))))
1126 (format (current-error-port) ";;; compiled ~a\n" cfn)
1130 (format (current-error-port)
1131 ";;; WARNING: compilation of ~a failed:\n;;; key ~a, throw_args ~s\n"
1134 (with-fluids ((current-reader (and (pair? reader) (car reader))))
1135 (let ((cfn (and=> (and=> (false-if-exception (canonicalize-path name))
1137 fresh-compiled-file-name)))
1140 (start-stack 'load-stack
1141 (primitive-load name))))))
1145 ;;; {Reader Extensions}
1147 ;;; Reader code for various "#c" forms.
1150 (define read-eval? (make-fluid))
1151 (fluid-set! read-eval? #f)
1152 (read-hash-extend #\.
1154 (if (fluid-ref read-eval?)
1155 (eval (read port) (interaction-environment))
1157 "#. read expansion found and read-eval? is #f."))))
1161 ;;; {Command Line Options}
1164 (define (get-option argv kw-opts kw-args return)
1167 (return #f #f argv))
1169 ((or (not (eq? #\- (string-ref (car argv) 0)))
1170 (eq? (string-length (car argv)) 1))
1171 (return 'normal-arg (car argv) (cdr argv)))
1173 ((eq? #\- (string-ref (car argv) 1))
1174 (let* ((kw-arg-pos (or (string-index (car argv) #\=)
1175 (string-length (car argv))))
1176 (kw (symbol->keyword (substring (car argv) 2 kw-arg-pos)))
1177 (kw-opt? (member kw kw-opts))
1178 (kw-arg? (member kw kw-args))
1179 (arg (or (and (not (eq? kw-arg-pos (string-length (car argv))))
1180 (substring (car argv)
1182 (string-length (car argv))))
1184 (begin (set! argv (cdr argv)) (car argv))))))
1185 (if (or kw-opt? kw-arg?)
1186 (return kw arg (cdr argv))
1187 (return 'usage-error kw (cdr argv)))))
1190 (let* ((char (substring (car argv) 1 2))
1191 (kw (symbol->keyword char)))
1194 ((member kw kw-opts)
1195 (let* ((rest-car (substring (car argv) 2 (string-length (car argv))))
1196 (new-argv (if (= 0 (string-length rest-car))
1198 (cons (string-append "-" rest-car) (cdr argv)))))
1199 (return kw #f new-argv)))
1201 ((member kw kw-args)
1202 (let* ((rest-car (substring (car argv) 2 (string-length (car argv))))
1203 (arg (if (= 0 (string-length rest-car))
1206 (new-argv (if (= 0 (string-length rest-car))
1209 (return kw arg new-argv)))
1211 (else (return 'usage-error kw argv)))))))
1213 (define (for-next-option proc argv kw-opts kw-args)
1214 (let loop ((argv argv))
1215 (get-option argv kw-opts kw-args
1216 (lambda (opt opt-arg argv)
1217 (and opt (proc opt opt-arg argv loop))))))
1219 (define (display-usage-report kw-desc)
1222 (or (eq? (car kw) #t)
1223 (eq? (car kw) 'else)
1224 (let* ((opt-desc kw)
1225 (help (cadr opt-desc))
1226 (opts (car opt-desc))
1227 (opts-proper (if (string? (car opts)) (cdr opts) opts))
1228 (arg-name (if (string? (car opts))
1229 (string-append "<" (car opts) ">")
1231 (left-part (string-append
1232 (with-output-to-string
1234 (map (lambda (x) (display (keyword->symbol x)) (display " "))
1237 (middle-part (if (and (< (string-length left-part) 30)
1238 (< (string-length help) 40))
1239 (make-string (- 30 (string-length left-part)) #\ )
1242 (display middle-part)
1249 (define (transform-usage-lambda cases)
1250 (let* ((raw-usage (delq! 'else (map car cases)))
1251 (usage-sans-specials (map (lambda (x)
1252 (or (and (not (list? x)) x)
1253 (and (symbol? (car x)) #t)
1254 (and (boolean? (car x)) #t)
1257 (usage-desc (delq! #t usage-sans-specials))
1258 (kw-desc (map car usage-desc))
1259 (kw-opts (apply append (map (lambda (x) (and (not (string? (car x))) x)) kw-desc)))
1260 (kw-args (apply append (map (lambda (x) (and (string? (car x)) (cdr x))) kw-desc)))
1261 (transmogrified-cases (map (lambda (case)
1262 (cons (let ((opts (car case)))
1263 (if (or (boolean? opts) (eq? 'else opts))
1266 ((symbol? (car opts)) opts)
1267 ((boolean? (car opts)) opts)
1268 ((string? (caar opts)) (cdar opts))
1269 (else (car opts)))))
1272 `(let ((%display-usage (lambda () (display-usage-report ',usage-desc))))
1274 (let %next-arg ((%argv %argv))
1278 (lambda (%opt %arg %new-argv)
1280 ,@ transmogrified-cases))))))))
1285 ;;; {Low Level Modules}
1287 ;;; These are the low level data structures for modules.
1289 ;;; Every module object is of the type 'module-type', which is a record
1290 ;;; consisting of the following members:
1292 ;;; - eval-closure: the function that defines for its module the strategy that
1293 ;;; shall be followed when looking up symbols in the module.
1295 ;;; An eval-closure is a function taking two arguments: the symbol to be
1296 ;;; looked up and a boolean value telling whether a binding for the symbol
1297 ;;; should be created if it does not exist yet. If the symbol lookup
1298 ;;; succeeded (either because an existing binding was found or because a new
1299 ;;; binding was created), a variable object representing the binding is
1300 ;;; returned. Otherwise, the value #f is returned. Note that the eval
1301 ;;; closure does not take the module to be searched as an argument: During
1302 ;;; construction of the eval-closure, the eval-closure has to store the
1303 ;;; module it belongs to in its environment. This means, that any
1304 ;;; eval-closure can belong to only one module.
1306 ;;; The eval-closure of a module can be defined arbitrarily. However, three
1307 ;;; special cases of eval-closures are to be distinguished: During startup
1308 ;;; the module system is not yet activated. In this phase, no modules are
1309 ;;; defined and all bindings are automatically stored by the system in the
1310 ;;; pre-modules-obarray. Since no eval-closures exist at this time, the
1311 ;;; functions which require an eval-closure as their argument need to be
1312 ;;; passed the value #f.
1314 ;;; The other two special cases of eval-closures are the
1315 ;;; standard-eval-closure and the standard-interface-eval-closure. Both
1316 ;;; behave equally for the case that no new binding is to be created. The
1317 ;;; difference between the two comes in, when the boolean argument to the
1318 ;;; eval-closure indicates that a new binding shall be created if it is not
1321 ;;; Given that no new binding shall be created, both standard eval-closures
1322 ;;; define the following standard strategy of searching bindings in the
1323 ;;; module: First, the module's obarray is searched for the symbol. Second,
1324 ;;; if no binding for the symbol was found in the module's obarray, the
1325 ;;; module's binder procedure is exececuted. If this procedure did not
1326 ;;; return a binding for the symbol, the modules referenced in the module's
1327 ;;; uses list are recursively searched for a binding of the symbol. If the
1328 ;;; binding can not be found in these modules also, the symbol lookup has
1331 ;;; If a new binding shall be created, the standard-interface-eval-closure
1332 ;;; immediately returns indicating failure. That is, it does not even try
1333 ;;; to look up the symbol. In contrast, the standard-eval-closure would
1334 ;;; first search the obarray, and if no binding was found there, would
1335 ;;; create a new binding in the obarray, therefore not calling the binder
1336 ;;; procedure or searching the modules in the uses list.
1338 ;;; The explanation of the following members obarray, binder and uses
1339 ;;; assumes that the symbol lookup follows the strategy that is defined in
1340 ;;; the standard-eval-closure and the standard-interface-eval-closure.
1342 ;;; - obarray: a hash table that maps symbols to variable objects. In this
1343 ;;; hash table, the definitions are found that are local to the module (that
1344 ;;; is, not imported from other modules). When looking up bindings in the
1345 ;;; module, this hash table is searched first.
1347 ;;; - binder: either #f or a function taking a module and a symbol argument.
1348 ;;; If it is a function it is called after the obarray has been
1349 ;;; unsuccessfully searched for a binding. It then can provide bindings
1350 ;;; that would otherwise not be found locally in the module.
1352 ;;; - uses: a list of modules from which non-local bindings can be inherited.
1353 ;;; These modules are the third place queried for bindings after the obarray
1354 ;;; has been unsuccessfully searched and the binder function did not deliver
1355 ;;; a result either.
1357 ;;; - transformer: either #f or a function taking a scheme expression as
1358 ;;; delivered by read. If it is a function, it will be called to perform
1359 ;;; syntax transformations (e. g. makro expansion) on the given scheme
1360 ;;; expression. The output of the transformer function will then be passed
1361 ;;; to Guile's internal memoizer. This means that the output must be valid
1362 ;;; scheme code. The only exception is, that the output may make use of the
1363 ;;; syntax extensions provided to identify the modules that a binding
1366 ;;; - name: the name of the module. This is used for all kinds of printing
1367 ;;; outputs. In certain places the module name also serves as a way of
1368 ;;; identification. When adding a module to the uses list of another
1369 ;;; module, it is made sure that the new uses list will not contain two
1370 ;;; modules of the same name.
1372 ;;; - kind: classification of the kind of module. The value is (currently?)
1373 ;;; only used for printing. It has no influence on how a module is treated.
1374 ;;; Currently the following values are used when setting the module kind:
1375 ;;; 'module, 'directory, 'interface, 'custom-interface. If no explicit kind
1376 ;;; is set, it defaults to 'module.
1378 ;;; - duplicates-handlers: a list of procedures that get called to make a
1379 ;;; choice between two duplicate bindings when name clashes occur. See the
1380 ;;; `duplicate-handlers' global variable below.
1382 ;;; - observers: a list of procedures that get called when the module is
1385 ;;; - weak-observers: a weak-key hash table of procedures that get called
1386 ;;; when the module is modified. See `module-observe-weak' for details.
1388 ;;; In addition, the module may (must?) contain a binding for
1389 ;;; `%module-public-interface'. This variable should be bound to a module
1390 ;;; representing the exported interface of a module. See the
1391 ;;; `module-public-interface' and `module-export!' procedures.
1393 ;;; !!! warning: The interface to lazy binder procedures is going
1394 ;;; to be changed in an incompatible way to permit all the basic
1395 ;;; module ops to be virtualized.
1397 ;;; (make-module size use-list lazy-binding-proc) => module
1398 ;;; module-{obarray,uses,binder}[|-set!]
1399 ;;; (module? obj) => [#t|#f]
1400 ;;; (module-locally-bound? module symbol) => [#t|#f]
1401 ;;; (module-bound? module symbol) => [#t|#f]
1402 ;;; (module-symbol-locally-interned? module symbol) => [#t|#f]
1403 ;;; (module-symbol-interned? module symbol) => [#t|#f]
1404 ;;; (module-local-variable module symbol) => [#<variable ...> | #f]
1405 ;;; (module-variable module symbol) => [#<variable ...> | #f]
1406 ;;; (module-symbol-binding module symbol opt-value)
1407 ;;; => [ <obj> | opt-value | an error occurs ]
1408 ;;; (module-make-local-var! module symbol) => #<variable...>
1409 ;;; (module-add! module symbol var) => unspecified
1410 ;;; (module-remove! module symbol) => unspecified
1411 ;;; (module-for-each proc module) => unspecified
1412 ;;; (make-scm-module) => module ; a lazy copy of the symhash module
1413 ;;; (set-current-module module) => unspecified
1414 ;;; (current-module) => #<module...>
1420 ;;; {Printing Modules}
1423 ;; This is how modules are printed. You can re-define it.
1424 (define (%print-module mod port)
1426 (display (or (module-kind mod) "module") port)
1428 (display (module-name mod) port)
1430 (display (number->string (object-address mod) 16) port)
1434 ;; Locally extend the syntax to allow record accessors to be defined at
1435 ;; compile-time. Cache the rtd locally to the constructor, the getters and
1436 ;; the setters, in order to allow for redefinition of the record type; not
1437 ;; relevant in the case of modules, but perhaps if we make this public, it
1440 ((define-record-type
1442 (define (make-id scope . fragments)
1443 (datum->syntax #'scope
1444 (apply symbol-append
1446 (if (symbol? x) x (syntax->datum x)))
1449 (define (getter rtd type-name field slot)
1450 #`(define #,(make-id rtd type-name '- field)
1452 (lambda (#,type-name)
1453 (if (eq? (struct-vtable #,type-name) rtd)
1454 (struct-ref #,type-name #,slot)
1455 (%record-type-error rtd #,type-name))))))
1457 (define (setter rtd type-name field slot)
1458 #`(define #,(make-id rtd 'set- type-name '- field '!)
1460 (lambda (#,type-name val)
1461 (if (eq? (struct-vtable #,type-name) rtd)
1462 (struct-set! #,type-name #,slot val)
1463 (%record-type-error rtd #,type-name))))))
1465 (define (accessors rtd type-name fields n exp)
1466 (syntax-case fields ()
1468 (((field #:no-accessors) field* ...) (identifier? #'field)
1469 (accessors rtd type-name #'(field* ...) (1+ n)
1471 (((field #:no-setter) field* ...) (identifier? #'field)
1472 (accessors rtd type-name #'(field* ...) (1+ n)
1474 #,(getter rtd type-name #'field n))))
1475 (((field #:no-getter) field* ...) (identifier? #'field)
1476 (accessors rtd type-name #'(field* ...) (1+ n)
1478 #,(setter rtd type-name #'field n))))
1479 ((field field* ...) (identifier? #'field)
1480 (accessors rtd type-name #'(field* ...) (1+ n)
1482 #,(getter rtd type-name #'field n)
1483 #,(setter rtd type-name #'field n))))))
1485 (define (predicate rtd type-name fields exp)
1487 rtd type-name fields 0
1490 (define (#,(make-id rtd type-name '?) obj)
1491 (and (struct? obj) (eq? (struct-vtable obj) #,rtd))))))
1493 (define (field-list fields)
1494 (syntax-case fields ()
1496 (((f . opts) . rest) (identifier? #'f)
1497 (cons #'f (field-list #'rest)))
1498 ((f . rest) (identifier? #'f)
1499 (cons #'f (field-list #'rest)))))
1501 (define (constructor rtd type-name fields exp)
1502 (let ((ctor (make-id rtd type-name '-constructor))
1503 (args (field-list fields)))
1504 (predicate rtd type-name fields
1509 (make-struct rtd 0 #,@args))))
1510 (struct-set! #,rtd (+ vtable-offset-user 2)
1513 (define (type type-name printer fields)
1514 (define (make-layout)
1515 (let lp ((fields fields) (slots '()))
1516 (syntax-case fields ()
1517 (() (datum->syntax #'here
1519 (apply string-append slots))))
1520 ((_ . rest) (lp #'rest (cons "pw" slots))))))
1522 (let ((rtd (make-id type-name type-name '-type)))
1523 (constructor rtd type-name fields
1526 (make-struct record-type-vtable 0
1530 '#,(field-list fields)))
1531 (set-struct-vtable-name! #,rtd '#,type-name)))))
1534 ((_ type-name printer (field ...))
1535 (type #'type-name #'printer #'(field ...)))))))
1539 ;; A module is characterized by an obarray in which local symbols
1540 ;; are interned, a list of modules, "uses", from which non-local
1541 ;; bindings can be inherited, and an optional lazy-binder which
1542 ;; is a (CLOSURE module symbol) which, as a last resort, can provide
1543 ;; bindings that would otherwise not be found locally in the module.
1545 ;; NOTE: If you change the set of fields or their order, you also need to
1546 ;; change the constants in libguile/modules.h.
1548 ;; NOTE: The getter `module-eval-closure' is used in libguile/modules.c.
1549 ;; NOTE: The getter `module-transfomer' is defined libguile/modules.c.
1550 ;; NOTE: The getter `module-name' is defined later, due to boot reasons.
1551 ;; NOTE: The getter `module-public-interface' is used in libguile/modules.c.
1553 (define-record-type module
1554 (lambda (obj port) (%print-module obj port))
1559 (transformer #:no-getter)
1563 (import-obarray #:no-setter)
1565 (weak-observers #:no-setter)
1572 ;; make-module &opt size uses binder
1574 ;; Create a new module, perhaps with a particular size of obarray,
1575 ;; initial uses list, or binding procedure.
1580 (define (parse-arg index default)
1581 (if (> (length args) index)
1582 (list-ref args index)
1585 (define %default-import-size
1586 ;; Typical number of imported bindings actually used by a module.
1589 (if (> (length args) 3)
1590 (error "Too many args to make-module." args))
1592 (let ((size (parse-arg 0 31))
1593 (uses (parse-arg 1 '()))
1594 (binder (parse-arg 2 #f)))
1596 (if (not (integer? size))
1597 (error "Illegal size to make-module." size))
1598 (if (not (and (list? uses)
1599 (and-map module? uses)))
1600 (error "Incorrect use list." uses))
1601 (if (and binder (not (procedure? binder)))
1603 "Lazy-binder expected to be a procedure or #f." binder))
1605 (let ((module (module-constructor (make-hash-table size)
1606 uses binder #f macroexpand
1608 (make-hash-table %default-import-size)
1610 (make-weak-key-hash-table 31) #f
1611 (make-hash-table 7) #f #f)))
1613 ;; We can't pass this as an argument to module-constructor,
1614 ;; because we need it to close over a pointer to the module
1616 (set-module-eval-closure! module (standard-eval-closure module))
1623 ;;; {Observer protocol}
1626 (define (module-observe module proc)
1627 (set-module-observers! module (cons proc (module-observers module)))
1630 (define (module-observe-weak module observer-id . proc)
1631 ;; Register PROC as an observer of MODULE under name OBSERVER-ID (which can
1632 ;; be any Scheme object). PROC is invoked and passed MODULE any time
1633 ;; MODULE is modified. PROC gets unregistered when OBSERVER-ID gets GC'd
1634 ;; (thus, it is never unregistered if OBSERVER-ID is an immediate value,
1637 ;; The two-argument version is kept for backward compatibility: when called
1638 ;; with two arguments, the observer gets unregistered when closure PROC
1639 ;; gets GC'd (making it impossible to use an anonymous lambda for PROC).
1641 (let ((proc (if (null? proc) observer-id (car proc))))
1642 (hashq-set! (module-weak-observers module) observer-id proc)))
1644 (define (module-unobserve token)
1645 (let ((module (car token))
1648 (hash-remove! (module-weak-observers module) id)
1649 (set-module-observers! module (delq1! id (module-observers module)))))
1652 (define module-defer-observers #f)
1653 (define module-defer-observers-mutex (make-mutex 'recursive))
1654 (define module-defer-observers-table (make-hash-table))
1656 (define (module-modified m)
1657 (if module-defer-observers
1658 (hash-set! module-defer-observers-table m #t)
1659 (module-call-observers m)))
1661 ;;; This function can be used to delay calls to observers so that they
1662 ;;; can be called once only in the face of massive updating of modules.
1664 (define (call-with-deferred-observers thunk)
1667 (lock-mutex module-defer-observers-mutex)
1668 (set! module-defer-observers #t))
1671 (set! module-defer-observers #f)
1672 (hash-for-each (lambda (m dummy)
1673 (module-call-observers m))
1674 module-defer-observers-table)
1675 (hash-clear! module-defer-observers-table)
1676 (unlock-mutex module-defer-observers-mutex))))
1678 (define (module-call-observers m)
1679 (for-each (lambda (proc) (proc m)) (module-observers m))
1681 ;; We assume that weak observers don't (un)register themselves as they are
1682 ;; called since this would preclude proper iteration over the hash table
1684 (hash-for-each (lambda (id proc) (proc m)) (module-weak-observers m)))
1688 ;;; {Module Searching in General}
1690 ;;; We sometimes want to look for properties of a symbol
1691 ;;; just within the obarray of one module. If the property
1692 ;;; holds, then it is said to hold ``locally'' as in, ``The symbol
1693 ;;; DISPLAY is locally rebound in the module `safe-guile'.''
1696 ;;; Other times, we want to test for a symbol property in the obarray
1697 ;;; of M and, if it is not found there, try each of the modules in the
1698 ;;; uses list of M. This is the normal way of testing for some
1699 ;;; property, so we state these properties without qualification as
1700 ;;; in: ``The symbol 'fnord is interned in module M because it is
1701 ;;; interned locally in module M2 which is a member of the uses list
1705 ;; module-search fn m
1707 ;; return the first non-#f result of FN applied to M and then to
1708 ;; the modules in the uses of m, and so on recursively. If all applications
1709 ;; return #f, then so does this function.
1711 (define (module-search fn m v)
1714 (or (module-search fn (car pos) v)
1717 (loop (module-uses m))))
1720 ;;; {Is a symbol bound in a module?}
1722 ;;; Symbol S in Module M is bound if S is interned in M and if the binding
1723 ;;; of S in M has been set to some well-defined value.
1726 ;; module-locally-bound? module symbol
1728 ;; Is a symbol bound (interned and defined) locally in a given module?
1730 (define (module-locally-bound? m v)
1731 (let ((var (module-local-variable m v)))
1733 (variable-bound? var))))
1735 ;; module-bound? module symbol
1737 ;; Is a symbol bound (interned and defined) anywhere in a given module
1740 (define (module-bound? m v)
1741 (let ((var (module-variable m v)))
1743 (variable-bound? var))))
1745 ;;; {Is a symbol interned in a module?}
1747 ;;; Symbol S in Module M is interned if S occurs in
1748 ;;; of S in M has been set to some well-defined value.
1750 ;;; It is possible to intern a symbol in a module without providing
1751 ;;; an initial binding for the corresponding variable. This is done
1753 ;;; (module-add! module symbol (make-undefined-variable))
1755 ;;; In that case, the symbol is interned in the module, but not
1756 ;;; bound there. The unbound symbol shadows any binding for that
1757 ;;; symbol that might otherwise be inherited from a member of the uses list.
1760 (define (module-obarray-get-handle ob key)
1761 ((if (symbol? key) hashq-get-handle hash-get-handle) ob key))
1763 (define (module-obarray-ref ob key)
1764 ((if (symbol? key) hashq-ref hash-ref) ob key))
1766 (define (module-obarray-set! ob key val)
1767 ((if (symbol? key) hashq-set! hash-set!) ob key val))
1769 (define (module-obarray-remove! ob key)
1770 ((if (symbol? key) hashq-remove! hash-remove!) ob key))
1772 ;; module-symbol-locally-interned? module symbol
1774 ;; is a symbol interned (not neccessarily defined) locally in a given module
1775 ;; or its uses? Interned symbols shadow inherited bindings even if
1776 ;; they are not themselves bound to a defined value.
1778 (define (module-symbol-locally-interned? m v)
1779 (not (not (module-obarray-get-handle (module-obarray m) v))))
1781 ;; module-symbol-interned? module symbol
1783 ;; is a symbol interned (not neccessarily defined) anywhere in a given module
1784 ;; or its uses? Interned symbols shadow inherited bindings even if
1785 ;; they are not themselves bound to a defined value.
1787 (define (module-symbol-interned? m v)
1788 (module-search module-symbol-locally-interned? m v))
1791 ;;; {Mapping modules x symbols --> variables}
1794 ;; module-local-variable module symbol
1795 ;; return the local variable associated with a MODULE and SYMBOL.
1797 ;;; This function is very important. It is the only function that can
1798 ;;; return a variable from a module other than the mutators that store
1799 ;;; new variables in modules. Therefore, this function is the location
1800 ;;; of the "lazy binder" hack.
1802 ;;; If symbol is defined in MODULE, and if the definition binds symbol
1803 ;;; to a variable, return that variable object.
1805 ;;; If the symbols is not found at first, but the module has a lazy binder,
1806 ;;; then try the binder.
1808 ;;; If the symbol is not found at all, return #f.
1810 ;;; (This is now written in C, see `modules.c'.)
1813 ;;; {Mapping modules x symbols --> bindings}
1815 ;;; These are similar to the mapping to variables, except that the
1816 ;;; variable is dereferenced.
1819 ;; module-symbol-binding module symbol opt-value
1821 ;; return the binding of a variable specified by name within
1822 ;; a given module, signalling an error if the variable is unbound.
1823 ;; If the OPT-VALUE is passed, then instead of signalling an error,
1824 ;; return OPT-VALUE.
1826 (define (module-symbol-local-binding m v . opt-val)
1827 (let ((var (module-local-variable m v)))
1828 (if (and var (variable-bound? var))
1830 (if (not (null? opt-val))
1832 (error "Locally unbound variable." v)))))
1834 ;; module-symbol-binding module symbol opt-value
1836 ;; return the binding of a variable specified by name within
1837 ;; a given module, signalling an error if the variable is unbound.
1838 ;; If the OPT-VALUE is passed, then instead of signalling an error,
1839 ;; return OPT-VALUE.
1841 (define (module-symbol-binding m v . opt-val)
1842 (let ((var (module-variable m v)))
1843 (if (and var (variable-bound? var))
1845 (if (not (null? opt-val))
1847 (error "Unbound variable." v)))))
1852 ;;; {Adding Variables to Modules}
1855 ;; module-make-local-var! module symbol
1857 ;; ensure a variable for V in the local namespace of M.
1858 ;; If no variable was already there, then create a new and uninitialzied
1861 ;; This function is used in modules.c.
1863 (define (module-make-local-var! m v)
1864 (or (let ((b (module-obarray-ref (module-obarray m) v)))
1867 ;; Mark as modified since this function is called when
1868 ;; the standard eval closure defines a binding
1872 ;; Create a new local variable.
1873 (let ((local-var (make-undefined-variable)))
1874 (module-add! m v local-var)
1877 ;; module-ensure-local-variable! module symbol
1879 ;; Ensure that there is a local variable in MODULE for SYMBOL. If
1880 ;; there is no binding for SYMBOL, create a new uninitialized
1881 ;; variable. Return the local variable.
1883 (define (module-ensure-local-variable! module symbol)
1884 (or (module-local-variable module symbol)
1885 (let ((var (make-undefined-variable)))
1886 (module-add! module symbol var)
1889 ;; module-add! module symbol var
1891 ;; ensure a particular variable for V in the local namespace of M.
1893 (define (module-add! m v var)
1894 (if (not (variable? var))
1895 (error "Bad variable to module-add!" var))
1896 (module-obarray-set! (module-obarray m) v var)
1897 (module-modified m))
1901 ;; make sure that a symbol is undefined in the local namespace of M.
1903 (define (module-remove! m v)
1904 (module-obarray-remove! (module-obarray m) v)
1905 (module-modified m))
1907 (define (module-clear! m)
1908 (hash-clear! (module-obarray m))
1909 (module-modified m))
1911 ;; MODULE-FOR-EACH -- exported
1913 ;; Call PROC on each symbol in MODULE, with arguments of (SYMBOL VARIABLE).
1915 (define (module-for-each proc module)
1916 (hash-for-each proc (module-obarray module)))
1918 (define (module-map proc module)
1919 (hash-map->list proc (module-obarray module)))
1923 ;; Modules exist in a separate namespace from values, because you generally do
1924 ;; not want the name of a submodule, which you might not even use, to collide
1925 ;; with local variables that happen to be named the same as the submodule.
1927 (define (module-ref-submodule module name)
1928 (or (hashq-ref (module-submodules module) name)
1929 (and (module-submodule-binder module)
1930 ((module-submodule-binder module) module name))))
1932 (define (module-define-submodule! module name submodule)
1933 (hashq-set! (module-submodules module) name submodule))
1937 ;;; {Low Level Bootstrapping}
1942 ;; A root module uses the pre-modules-obarray as its obarray. This
1943 ;; special obarray accumulates all bindings that have been established
1944 ;; before the module system is fully booted.
1946 ;; (The obarray continues to be used by code that has been closed over
1947 ;; before the module system has been booted.)
1949 (define (make-root-module)
1950 (let ((m (make-module 0)))
1951 (set-module-obarray! m (%get-pre-modules-obarray))
1956 ;; The root interface is a module that uses the same obarray as the
1957 ;; root module. It does not allow new definitions, tho.
1959 (define (make-scm-module)
1960 (let ((m (make-module 0)))
1961 (set-module-obarray! m (%get-pre-modules-obarray))
1962 (set-module-eval-closure! m (standard-interface-eval-closure m))
1968 ;;; {Module-based Loading}
1971 (define (save-module-excursion thunk)
1972 (let ((inner-module (current-module))
1974 (dynamic-wind (lambda ()
1975 (set! outer-module (current-module))
1976 (set-current-module inner-module)
1977 (set! inner-module #f))
1980 (set! inner-module (current-module))
1981 (set-current-module outer-module)
1982 (set! outer-module #f)))))
1984 (define basic-load load)
1986 (define (load-module filename . reader)
1987 (save-module-excursion
1989 (let ((oldname (and (current-load-port)
1990 (port-filename (current-load-port)))))
1993 (> (string-length filename) 0)
1994 (not (char=? (string-ref filename 0) #\/))
1995 (not (string=? (dirname oldname) ".")))
1996 (string-append (dirname oldname) "/" filename)
2003 ;;; {MODULE-REF -- exported}
2006 ;; Returns the value of a variable called NAME in MODULE or any of its
2007 ;; used modules. If there is no such variable, then if the optional third
2008 ;; argument DEFAULT is present, it is returned; otherwise an error is signaled.
2010 (define (module-ref module name . rest)
2011 (let ((variable (module-variable module name)))
2012 (if (and variable (variable-bound? variable))
2013 (variable-ref variable)
2015 (error "No variable named" name 'in module)
2016 (car rest) ; default value
2019 ;; MODULE-SET! -- exported
2021 ;; Sets the variable called NAME in MODULE (or in a module that MODULE uses)
2022 ;; to VALUE; if there is no such variable, an error is signaled.
2024 (define (module-set! module name value)
2025 (let ((variable (module-variable module name)))
2027 (variable-set! variable value)
2028 (error "No variable named" name 'in module))))
2030 ;; MODULE-DEFINE! -- exported
2032 ;; Sets the variable called NAME in MODULE to VALUE; if there is no such
2033 ;; variable, it is added first.
2035 (define (module-define! module name value)
2036 (let ((variable (module-local-variable module name)))
2039 (variable-set! variable value)
2040 (module-modified module))
2041 (let ((variable (make-variable value)))
2042 (module-add! module name variable)))))
2044 ;; MODULE-DEFINED? -- exported
2046 ;; Return #t iff NAME is defined in MODULE (or in a module that MODULE
2049 (define (module-defined? module name)
2050 (let ((variable (module-variable module name)))
2051 (and variable (variable-bound? variable))))
2053 ;; MODULE-USE! module interface
2055 ;; Add INTERFACE to the list of interfaces used by MODULE.
2057 (define (module-use! module interface)
2058 (if (not (or (eq? module interface)
2059 (memq interface (module-uses module))))
2061 ;; Newly used modules must be appended rather than consed, so that
2062 ;; `module-variable' traverses the use list starting from the first
2064 (set-module-uses! module
2065 (append (filter (lambda (m)
2067 (equal? (module-name m)
2068 (module-name interface))))
2069 (module-uses module))
2071 (hash-clear! (module-import-obarray module))
2072 (module-modified module))))
2074 ;; MODULE-USE-INTERFACES! module interfaces
2076 ;; Same as MODULE-USE! but add multiple interfaces and check for duplicates
2078 (define (module-use-interfaces! module interfaces)
2079 (set-module-uses! module
2080 (append (module-uses module) interfaces))
2081 (hash-clear! (module-import-obarray module))
2082 (module-modified module))
2086 ;;; {Recursive Namespaces}
2088 ;;; A hierarchical namespace emerges if we consider some module to be
2089 ;;; root, and submodules of that module to be nested namespaces.
2091 ;;; The routines here manage variable names in hierarchical namespace.
2092 ;;; Each variable name is a list of elements, looked up in successively nested
2095 ;;; (nested-ref some-root-module '(foo bar baz))
2096 ;;; => <value of a variable named baz in the submodule bar of
2097 ;;; the submodule foo of some-root-module>
2102 ;;; ;; a-root is a module
2103 ;;; ;; name is a list of symbols
2105 ;;; nested-ref a-root name
2106 ;;; nested-set! a-root name val
2107 ;;; nested-define! a-root name val
2108 ;;; nested-remove! a-root name
2110 ;;; These functions manipulate values in namespaces. For referencing the
2111 ;;; namespaces themselves, use the following:
2113 ;;; nested-ref-module a-root name
2114 ;;; nested-define-module! a-root name mod
2116 ;;; (current-module) is a natural choice for a root so for convenience there are
2119 ;;; local-ref name == nested-ref (current-module) name
2120 ;;; local-set! name val == nested-set! (current-module) name val
2121 ;;; local-define name val == nested-define! (current-module) name val
2122 ;;; local-remove name == nested-remove! (current-module) name
2123 ;;; local-ref-module name == nested-ref-module (current-module) name
2124 ;;; local-define-module! name m == nested-define-module! (current-module) name m
2128 (define (nested-ref root names)
2131 (let loop ((cur root)
2135 (module-ref cur head #f)
2136 (let ((cur (module-ref-submodule cur head)))
2138 (loop cur (car tail) (cdr tail))))))))
2140 (define (nested-set! root names val)
2141 (let loop ((cur root)
2145 (module-set! cur head val)
2146 (let ((cur (module-ref-submodule cur head)))
2148 (error "failed to resolve module" names)
2149 (loop cur (car tail) (cdr tail)))))))
2151 (define (nested-define! root names val)
2152 (let loop ((cur root)
2156 (module-define! cur head val)
2157 (let ((cur (module-ref-submodule cur head)))
2159 (error "failed to resolve module" names)
2160 (loop cur (car tail) (cdr tail)))))))
2162 (define (nested-remove! root names)
2163 (let loop ((cur root)
2167 (module-remove! cur head)
2168 (let ((cur (module-ref-submodule cur head)))
2170 (error "failed to resolve module" names)
2171 (loop cur (car tail) (cdr tail)))))))
2174 (define (nested-ref-module root names)
2175 (let loop ((cur root)
2179 (let ((cur (module-ref-submodule cur (car names))))
2181 (loop cur (cdr names)))))))
2183 (define (nested-define-module! root names module)
2185 (error "can't redefine root module" root module)
2186 (let loop ((cur root)
2190 (module-define-submodule! cur head module)
2191 (let ((cur (or (module-ref-submodule cur head)
2192 (let ((m (make-module 31)))
2193 (set-module-kind! m 'directory)
2194 (set-module-name! m (append (module-name cur)
2196 (module-define-submodule! cur head m)
2198 (loop cur (car tail) (cdr tail)))))))
2201 (define (local-ref names) (nested-ref (current-module) names))
2202 (define (local-set! names val) (nested-set! (current-module) names val))
2203 (define (local-define names val) (nested-define! (current-module) names val))
2204 (define (local-remove names) (nested-remove! (current-module) names))
2205 (define (local-ref-module names) (nested-ref-module (current-module) names))
2206 (define (local-define-module names mod) (nested-define-module! (current-module) names mod))
2212 ;;; {The (guile) module}
2214 ;;; The standard module, which has the core Guile bindings. Also called the
2215 ;;; "root module", as it is imported by many other modules, but it is not
2216 ;;; necessarily the root of anything; and indeed, the module named '() might be
2217 ;;; better thought of as a root.
2220 (define (set-system-module! m s)
2221 (set-procedure-property! (module-eval-closure m) 'system-module s))
2222 (define the-root-module (make-root-module))
2223 (define the-scm-module (make-scm-module))
2224 (set-module-public-interface! the-root-module the-scm-module)
2225 (set-module-name! the-root-module '(guile))
2226 (set-module-name! the-scm-module '(guile))
2227 (set-module-kind! the-scm-module 'interface)
2228 (set-system-module! the-root-module #t)
2229 (set-system-module! the-scm-module #t)
2234 ;; Now that we have a root module, even though modules aren't fully booted,
2235 ;; expand the definition of resolve-module.
2237 (define (resolve-module name . args)
2238 (if (equal? name '(guile))
2240 (error "unexpected module to resolve during module boot" name)))
2242 ;; Cheat. These bindings are needed by modules.c, but we don't want
2243 ;; to move their real definition here because that would be unnatural.
2245 (define process-define-module #f)
2246 (define process-use-modules #f)
2247 (define module-export! #f)
2248 (define default-duplicate-binding-procedures #f)
2250 ;; This boots the module system. All bindings needed by modules.c
2251 ;; must have been defined by now.
2253 (set-current-module the-root-module)
2258 ;; Now that modules are booted, give module-name its final definition.
2261 (let ((accessor (record-accessor module-type 'name)))
2264 (let ((name (list (gensym))))
2265 ;; Name MOD and bind it in the module root so that it's visible to
2266 ;; `resolve-module'. This is important as `psyntax' stores module
2267 ;; names and relies on being able to `resolve-module' them.
2268 (set-module-name! mod name)
2269 (nested-define-module! (resolve-module '() #f) name mod)
2272 (define (make-modules-in module name)
2273 (or (nested-ref-module module name)
2274 (let ((m (make-module 31)))
2275 (set-module-kind! m 'directory)
2276 (set-module-name! m (append (module-name module) name))
2277 (nested-define-module! module name m)
2280 (define (beautify-user-module! module)
2281 (let ((interface (module-public-interface module)))
2282 (if (or (not interface)
2283 (eq? interface module))
2284 (let ((interface (make-module 31)))
2285 (set-module-name! interface (module-name module))
2286 (set-module-version! interface (module-version module))
2287 (set-module-kind! interface 'interface)
2288 (set-module-public-interface! module interface))))
2289 (if (and (not (memq the-scm-module (module-uses module)))
2290 (not (eq? module the-root-module)))
2291 ;; Import the default set of bindings (from the SCM module) in MODULE.
2292 (module-use! module the-scm-module)))
2294 (define (version-matches? version-ref target)
2295 (define (any pred lst)
2296 (and (not (null? lst)) (or (pred (car lst)) (any pred (cdr lst)))))
2297 (define (every pred lst)
2298 (or (null? lst) (and (pred (car lst)) (every pred (cdr lst)))))
2299 (define (sub-versions-match? v-refs t)
2300 (define (sub-version-matches? v-ref t)
2301 (define (curried-sub-version-matches? v)
2302 (sub-version-matches? v t))
2303 (cond ((number? v-ref) (eqv? v-ref t))
2305 (let ((cv (car v-ref)))
2306 (cond ((eq? cv '>=) (>= t (cadr v-ref)))
2307 ((eq? cv '<=) (<= t (cadr v-ref)))
2309 (every curried-sub-version-matches? (cdr v-ref)))
2311 (any curried-sub-version-matches? (cdr v-ref)))
2312 ((eq? cv 'not) (not (sub-version-matches? (cadr v-ref) t)))
2313 (else (error "Incompatible sub-version reference" cv)))))
2314 (else (error "Incompatible sub-version reference" v-ref))))
2316 (and (not (null? t))
2317 (sub-version-matches? (car v-refs) (car t))
2318 (sub-versions-match? (cdr v-refs) (cdr t)))))
2319 (define (curried-version-matches? v)
2320 (version-matches? v target))
2321 (or (null? version-ref)
2322 (let ((cv (car version-ref)))
2323 (cond ((eq? cv 'and) (every curried-version-matches? (cdr version-ref)))
2324 ((eq? cv 'or) (any curried-version-matches? (cdr version-ref)))
2325 ((eq? cv 'not) (not (version-matches? (cadr version-ref) target)))
2326 (else (sub-versions-match? version-ref target))))))
2328 (define (find-versioned-module dir-hint name version-ref roots)
2329 (define (subdir-pair-less pair1 pair2)
2330 (define (numlist-less lst1 lst2)
2332 (and (not (null? lst1))
2333 (cond ((> (car lst1) (car lst2)) #t)
2334 ((< (car lst1) (car lst2)) #f)
2335 (else (numlist-less (cdr lst1) (cdr lst2)))))))
2336 (numlist-less (car pair1) (car pair2)))
2337 (define (match-version-and-file pair)
2338 (and (version-matches? version-ref (car pair))
2340 (filter (lambda (file)
2341 (let ((s (false-if-exception (stat file))))
2342 (and s (eq? (stat:type s) 'regular))))
2344 (string-append (cdr pair) "/" name ext))
2345 %load-extensions))))
2346 (and (not (null? filenames))
2347 (cons (car pair) (car filenames))))))
2349 (define (match-version-recursive root-pairs leaf-pairs)
2350 (define (filter-subdirs root-pairs ret)
2351 (define (filter-subdir root-pair dstrm subdir-pairs)
2352 (let ((entry (readdir dstrm)))
2353 (if (eof-object? entry)
2355 (let* ((subdir (string-append (cdr root-pair) "/" entry))
2356 (num (string->number entry))
2357 (num (and num (append (car root-pair) (list num)))))
2358 (if (and num (eq? (stat:type (stat subdir)) 'directory))
2360 root-pair dstrm (cons (cons num subdir) subdir-pairs))
2361 (filter-subdir root-pair dstrm subdir-pairs))))))
2363 (or (and (null? root-pairs) ret)
2364 (let* ((rp (car root-pairs))
2365 (dstrm (false-if-exception (opendir (cdr rp)))))
2367 (let ((subdir-pairs (filter-subdir rp dstrm '())))
2369 (filter-subdirs (cdr root-pairs)
2370 (or (and (null? subdir-pairs) ret)
2371 (append ret subdir-pairs))))
2372 (filter-subdirs (cdr root-pairs) ret)))))
2374 (or (and (null? root-pairs) leaf-pairs)
2375 (let ((matching-subdir-pairs (filter-subdirs root-pairs '())))
2376 (match-version-recursive
2377 matching-subdir-pairs
2378 (append leaf-pairs (filter pair? (map match-version-and-file
2379 matching-subdir-pairs)))))))
2380 (define (make-root-pair root)
2381 (cons '() (string-append root "/" dir-hint)))
2383 (let* ((root-pairs (map make-root-pair roots))
2384 (matches (if (null? version-ref)
2385 (filter pair? (map match-version-and-file root-pairs))
2387 (matches (append matches (match-version-recursive root-pairs '()))))
2388 (and (null? matches) (error "No matching modules found."))
2389 (cdar (sort matches subdir-pair-less))))
2391 (define (make-fresh-user-module)
2392 (let ((m (make-module)))
2393 (beautify-user-module! m)
2396 ;; NOTE: This binding is used in libguile/modules.c.
2398 (define resolve-module
2399 (let ((root (make-module)))
2400 (set-module-name! root '())
2401 ;; Define the-root-module as '(guile).
2402 (module-define-submodule! root 'guile the-root-module)
2404 (lambda (name . args) ;; #:optional (autoload #t) (version #f)
2405 (let* ((already (nested-ref-module root name))
2406 (numargs (length args))
2407 (autoload (or (= numargs 0) (car args)))
2408 (version (and (> numargs 1) (cadr args))))
2411 (or (not autoload) (module-public-interface already)))
2412 ;; A hit, a palpable hit.
2414 (not (version-matches? version (module-version already))))
2415 (error "incompatible module version already loaded" name))
2418 ;; Try to autoload the module, and recurse.
2419 (try-load-module name version)
2420 (resolve-module name #f))
2422 ;; No module found (or if one was, it had no public interface), and
2423 ;; we're not autoloading. Here's the weird semantics: we ensure
2424 ;; there's an empty module.
2425 (or already (make-modules-in root name))))))))
2428 (define (try-load-module name version)
2429 (try-module-autoload name version))
2431 (define (purify-module! module)
2432 "Removes bindings in MODULE which are inherited from the (guile) module."
2433 (let ((use-list (module-uses module)))
2434 (if (and (pair? use-list)
2435 (eq? (car (last-pair use-list)) the-scm-module))
2436 (set-module-uses! module (reverse (cdr (reverse use-list)))))))
2438 ;; Return a module that is an interface to the module designated by
2441 ;; `resolve-interface' takes four keyword arguments:
2443 ;; #:select SELECTION
2445 ;; SELECTION is a list of binding-specs to be imported; A binding-spec
2446 ;; is either a symbol or a pair of symbols (ORIG . SEEN), where ORIG
2447 ;; is the name in the used module and SEEN is the name in the using
2448 ;; module. Note that SEEN is also passed through RENAMER, below. The
2449 ;; default is to select all bindings. If you specify no selection but
2450 ;; a renamer, only the bindings that already exist in the used module
2451 ;; are made available in the interface. Bindings that are added later
2452 ;; are not picked up.
2456 ;; BINDINGS is a list of bindings which should not be imported.
2460 ;; PREFIX is a symbol that will be appended to each exported name.
2461 ;; The default is to not perform any renaming.
2463 ;; #:renamer RENAMER
2465 ;; RENAMER is a procedure that takes a symbol and returns its new
2466 ;; name. The default is not perform any renaming.
2468 ;; Signal "no code for module" error if module name is not resolvable
2469 ;; or its public interface is not available. Signal "no binding"
2470 ;; error if selected binding does not exist in the used module.
2472 (define (resolve-interface name . args)
2474 (define (get-keyword-arg args kw def)
2475 (cond ((memq kw args)
2477 (if (null? (cdr kw-arg))
2478 (error "keyword without value: " kw))
2483 (let* ((select (get-keyword-arg args #:select #f))
2484 (hide (get-keyword-arg args #:hide '()))
2485 (renamer (or (get-keyword-arg args #:renamer #f)
2486 (let ((prefix (get-keyword-arg args #:prefix #f)))
2487 (and prefix (symbol-prefix-proc prefix)))
2489 (version (get-keyword-arg args #:version #f))
2490 (module (resolve-module name #t version))
2491 (public-i (and module (module-public-interface module))))
2492 (and (or (not module) (not public-i))
2493 (error "no code for module" name))
2494 (if (and (not select) (null? hide) (eq? renamer identity))
2496 (let ((selection (or select (module-map (lambda (sym var) sym)
2498 (custom-i (make-module 31)))
2499 (set-module-kind! custom-i 'custom-interface)
2500 (set-module-name! custom-i name)
2501 ;; XXX - should use a lazy binder so that changes to the
2502 ;; used module are picked up automatically.
2503 (for-each (lambda (bspec)
2504 (let* ((direct? (symbol? bspec))
2505 (orig (if direct? bspec (car bspec)))
2506 (seen (if direct? bspec (cdr bspec)))
2507 (var (or (module-local-variable public-i orig)
2508 (module-local-variable module orig)
2510 ;; fixme: format manually for now
2512 #f "no binding `~A' in module ~A"
2514 (if (memq orig hide)
2515 (set! hide (delq! orig hide))
2516 (module-add! custom-i
2520 ;; Check that we are not hiding bindings which don't exist
2521 (for-each (lambda (binding)
2522 (if (not (module-local-variable public-i binding))
2525 #f "no binding `~A' to hide in module ~A"
2530 (define (symbol-prefix-proc prefix)
2532 (symbol-append prefix symbol)))
2534 ;; This function is called from "modules.c". If you change it, be
2535 ;; sure to update "modules.c" as well.
2537 (define (process-define-module args)
2538 (let* ((module-id (car args))
2539 (module (resolve-module module-id #f))
2541 (unrecognized (lambda (arg)
2542 (error "unrecognized define-module argument" arg))))
2543 (beautify-user-module! module)
2544 (let loop ((kws kws)
2545 (reversed-interfaces '())
2552 (call-with-deferred-observers
2554 (module-use-interfaces! module (reverse reversed-interfaces))
2555 (module-export! module exports)
2556 (module-replace! module replacements)
2557 (module-re-export! module re-exports)
2558 (if (not (null? autoloads))
2559 (apply module-autoload! module autoloads))))
2561 ((#:use-module #:use-syntax)
2562 (or (pair? (cdr kws))
2565 ((equal? (caadr kws) '(ice-9 syncase))
2566 (issue-deprecation-warning
2567 "(ice-9 syncase) is deprecated. Support for syntax-case is now in Guile core.")
2575 (let* ((interface-args (cadr kws))
2576 (interface (apply resolve-interface interface-args)))
2577 (and (eq? (car kws) #:use-syntax)
2578 (or (symbol? (caar interface-args))
2579 (error "invalid module name for use-syntax"
2580 (car interface-args)))
2581 (set-module-transformer!
2583 (module-ref interface
2584 (car (last-pair (car interface-args)))
2587 (cons interface reversed-interfaces)
2593 (or (and (pair? (cdr kws)) (pair? (cddr kws)))
2600 (let ((name (cadr kws))
2601 (bindings (caddr kws)))
2602 (cons* name bindings autoloads))))
2604 (set-system-module! module #t)
2605 (loop (cdr kws) reversed-interfaces exports re-exports
2606 replacements autoloads))
2608 (purify-module! module)
2609 (loop (cdr kws) reversed-interfaces exports re-exports
2610 replacements autoloads))
2612 (or (pair? (cdr kws))
2614 (let ((version (cadr kws)))
2615 (set-module-version! module version)
2616 (set-module-version! (module-public-interface module) version))
2617 (loop (cddr kws) reversed-interfaces exports re-exports
2618 replacements autoloads))
2620 (if (not (pair? (cdr kws)))
2622 (set-module-duplicates-handlers!
2624 (lookup-duplicates-handlers (cadr kws)))
2625 (loop (cddr kws) reversed-interfaces exports re-exports
2626 replacements autoloads))
2627 ((#:export #:export-syntax)
2628 (or (pair? (cdr kws))
2632 (append (cadr kws) exports)
2636 ((#:re-export #:re-export-syntax)
2637 (or (pair? (cdr kws))
2642 (append (cadr kws) re-exports)
2645 ((#:replace #:replace-syntax)
2646 (or (pair? (cdr kws))
2652 (append (cadr kws) replacements)
2655 (unrecognized kws)))))
2656 (run-hook module-defined-hook module)
2659 ;; `module-defined-hook' is a hook that is run whenever a new module
2660 ;; is defined. Its members are called with one argument, the new
2662 (define module-defined-hook (make-hook 1))
2669 (define (make-autoload-interface module name bindings)
2670 (let ((b (lambda (a sym definep)
2671 (and (memq sym bindings)
2672 (let ((i (module-public-interface (resolve-module name))))
2674 (error "missing interface for module" name))
2675 (let ((autoload (memq a (module-uses module))))
2676 ;; Replace autoload-interface with actual interface if
2677 ;; that has not happened yet.
2678 (if (pair? autoload)
2679 (set-car! autoload i)))
2680 (module-local-variable i sym))))))
2681 (module-constructor (make-hash-table 0) '() b #f #f name 'autoload #f
2682 (make-hash-table 0) '() (make-weak-value-hash-table 31) #f
2683 (make-hash-table 0) #f #f)))
2685 (define (module-autoload! module . args)
2686 "Have @var{module} automatically load the module named @var{name} when one
2687 of the symbols listed in @var{bindings} is looked up. @var{args} should be a
2688 list of module-name/binding-list pairs, e.g., as in @code{(module-autoload!
2689 module '(ice-9 q) '(make-q q-length))}."
2690 (let loop ((args args))
2694 (error "invalid name+binding autoload list" args))
2696 (let ((name (car args))
2697 (bindings (cadr args)))
2698 (module-use! module (make-autoload-interface module
2700 (loop (cddr args)))))))
2705 ;;; {Autoloading modules}
2708 (define autoloads-in-progress '())
2710 ;; This function is called from "modules.c". If you change it, be
2711 ;; sure to update "modules.c" as well.
2713 (define (try-module-autoload module-name . args)
2714 (let* ((reverse-name (reverse module-name))
2715 (name (symbol->string (car reverse-name)))
2716 (version (and (not (null? args)) (car args)))
2717 (dir-hint-module-name (reverse (cdr reverse-name)))
2718 (dir-hint (apply string-append
2720 (string-append (symbol->string elt) "/"))
2721 dir-hint-module-name))))
2722 (resolve-module dir-hint-module-name #f)
2723 (and (not (autoload-done-or-in-progress? dir-hint name))
2726 (lambda () (autoload-in-progress! dir-hint name))
2728 (with-fluids ((current-reader #f))
2729 (save-module-excursion
2732 (load (find-versioned-module
2733 dir-hint name version %load-path))
2734 (primitive-load-path (in-vicinity dir-hint name) #f))
2736 (lambda () (set-autoloaded! dir-hint name didit)))
2741 ;;; {Dynamic linking of modules}
2744 (define autoloads-done '((guile . guile)))
2746 (define (autoload-done-or-in-progress? p m)
2747 (let ((n (cons p m)))
2748 (->bool (or (member n autoloads-done)
2749 (member n autoloads-in-progress)))))
2751 (define (autoload-done! p m)
2752 (let ((n (cons p m)))
2753 (set! autoloads-in-progress
2754 (delete! n autoloads-in-progress))
2755 (or (member n autoloads-done)
2756 (set! autoloads-done (cons n autoloads-done)))))
2758 (define (autoload-in-progress! p m)
2759 (let ((n (cons p m)))
2760 (set! autoloads-done
2761 (delete! n autoloads-done))
2762 (set! autoloads-in-progress (cons n autoloads-in-progress))))
2764 (define (set-autoloaded! p m done?)
2766 (autoload-done! p m)
2767 (let ((n (cons p m)))
2768 (set! autoloads-done (delete! n autoloads-done))
2769 (set! autoloads-in-progress (delete! n autoloads-in-progress)))))
2773 ;;; {Run-time options}
2776 (defmacro define-option-interface (option-group)
2777 (let* ((option-name 'car)
2778 (option-value 'cadr)
2779 (option-documentation 'caddr)
2781 ;; Below follow the macros defining the run-time option interfaces.
2783 (make-options (lambda (interface)
2785 (cond ((null? args) (,interface))
2787 (,interface (car args)) (,interface))
2790 (display (,option-name option))
2791 (if (< (string-length
2792 (symbol->string (,option-name option)))
2796 (display (,option-value option))
2798 (display (,option-documentation option))
2800 (,interface #t)))))))
2802 (make-enable (lambda (interface)
2804 (,interface (append flags (,interface)))
2807 (make-disable (lambda (interface)
2809 (let ((options (,interface)))
2810 (for-each (lambda (flag)
2811 (set! options (delq! flag options)))
2813 (,interface options)
2815 (let* ((interface (car option-group))
2816 (options/enable/disable (cadr option-group)))
2818 (define ,(car options/enable/disable)
2819 ,(make-options interface))
2820 (define ,(cadr options/enable/disable)
2821 ,(make-enable interface))
2822 (define ,(caddr options/enable/disable)
2823 ,(make-disable interface))
2824 (defmacro ,(caaddr option-group) (opt val)
2825 `(,',(car options/enable/disable)
2826 (append (,',(car options/enable/disable))
2827 (list ',opt ,val))))))))
2829 (define-option-interface
2830 (eval-options-interface
2831 (eval-options eval-enable eval-disable)
2834 (define-option-interface
2835 (debug-options-interface
2836 (debug-options debug-enable debug-disable)
2839 (define-option-interface
2840 (evaluator-traps-interface
2841 (traps trap-enable trap-disable)
2844 (define-option-interface
2845 (read-options-interface
2846 (read-options read-enable read-disable)
2849 (define-option-interface
2850 (print-options-interface
2851 (print-options print-enable print-disable)
2859 (define (repl read evaler print)
2860 (let loop ((source (read (current-input-port))))
2861 (print (evaler source))
2862 (loop (read (current-input-port)))))
2864 ;; A provisional repl that acts like the SCM repl:
2866 (define scm-repl-silent #f)
2867 (define (assert-repl-silence v) (set! scm-repl-silent v))
2869 (define *unspecified* (if #f #f))
2870 (define (unspecified? v) (eq? v *unspecified*))
2872 (define scm-repl-print-unspecified #f)
2873 (define (assert-repl-print-unspecified v) (set! scm-repl-print-unspecified v))
2875 (define scm-repl-verbose #f)
2876 (define (assert-repl-verbosity v) (set! scm-repl-verbose v))
2878 (define scm-repl-prompt "guile> ")
2880 (define (set-repl-prompt! v) (set! scm-repl-prompt v))
2882 (define (default-pre-unwind-handler key . args)
2883 ;; Narrow by two more frames: this one, and the throw handler.
2885 (apply throw key args))
2888 (define (pre-unwind-handler-dispatch key . args)
2889 (apply default-pre-unwind-handler key args)))
2891 (define abort-hook (make-hook))
2893 ;; these definitions are used if running a script.
2894 ;; otherwise redefined in error-catching-loop.
2895 (define (set-batch-mode?! arg) #t)
2896 (define (batch-mode?) #t)
2898 (define (error-catching-loop thunk)
2901 (define (loop first)
2906 (call-with-unblocked-asyncs
2912 ;; This line is needed because mark
2913 ;; doesn't do closures quite right.
2914 ;; Unreferenced locals should be
2917 (let loop ((v (thunk)))
2921 (lambda (key . args)
2928 (apply throw 'switch-repl args))
2931 ;; This is one of the closures that require
2932 ;; (set! first #f) above
2935 (run-hook abort-hook)
2936 (force-output (current-output-port))
2937 (display "ABORT: " (current-error-port))
2938 (write args (current-error-port))
2939 (newline (current-error-port))
2943 (not has-shown-debugger-hint?)
2944 (not (memq 'backtrace
2945 (debug-options-interface)))
2946 (stack? (fluid-ref the-last-stack)))
2948 (newline (current-error-port))
2950 "Type \"(backtrace)\" to get more information or \"(debug)\" to enter the debugger.\n"
2951 (current-error-port))
2952 (set! has-shown-debugger-hint? #t)))
2953 (force-output (current-error-port)))
2955 (primitive-exit 1)))
2956 (set! stack-saved? #f)))
2959 ;; This is the other cons-leak closure...
2961 (cond ((= (length args) 4)
2962 (apply handle-system-error key args))
2964 (apply bad-throw key args)))))))
2966 default-pre-unwind-handler)))
2968 (if next (loop next) status)))
2969 (set! set-batch-mode?! (lambda (arg)
2971 (set! interactive #f)
2974 (error "sorry, not implemented")))))
2975 (set! batch-mode? (lambda () (not interactive)))
2976 (call-with-blocked-asyncs
2977 (lambda () (loop (lambda () #t))))))
2979 ;;(define the-last-stack (make-fluid)) Defined by scm_init_backtrace ()
2980 (define before-signal-stack (make-fluid))
2981 ;; FIXME: stack-saved? is broken in the presence of threads.
2982 (define stack-saved? #f)
2984 (define (save-stack . narrowing)
2985 (if (not stack-saved?)
2987 (let ((stacks (fluid-ref %stacks)))
2988 (fluid-set! the-last-stack
2989 ;; (make-stack obj inner outer inner outer ...)
2991 ;; In this case, cut away the make-stack frame, the
2992 ;; save-stack frame, and then narrow as specified by the
2993 ;; user, delimited by the nearest start-stack invocation,
2995 (apply make-stack #t
2997 (if (pair? stacks) (cdar stacks) 0)
2999 (set! stack-saved? #t))))
3001 (define before-error-hook (make-hook))
3002 (define after-error-hook (make-hook))
3003 (define before-backtrace-hook (make-hook))
3004 (define after-backtrace-hook (make-hook))
3006 (define has-shown-debugger-hint? #f)
3008 (define (handle-system-error key . args)
3009 (let ((cep (current-error-port)))
3010 (cond ((not (stack? (fluid-ref the-last-stack))))
3011 ((memq 'backtrace (debug-options-interface))
3012 (let ((highlights (if (or (eq? key 'wrong-type-arg)
3013 (eq? key 'out-of-range))
3016 (run-hook before-backtrace-hook)
3018 (display "Backtrace:\n")
3019 (display-backtrace (fluid-ref the-last-stack) cep
3022 (run-hook after-backtrace-hook))))
3023 (run-hook before-error-hook)
3024 (apply display-error (fluid-ref the-last-stack) cep args)
3025 (run-hook after-error-hook)
3027 (throw 'abort key)))
3029 (define (quit . args)
3030 (apply throw 'quit args))
3034 ;;(define has-shown-backtrace-hint? #f) Defined by scm_init_backtrace ()
3036 ;; Replaced by C code:
3037 ;;(define (backtrace)
3038 ;; (if (fluid-ref the-last-stack)
3041 ;; (display-backtrace (fluid-ref the-last-stack) (current-output-port))
3043 ;; (if (and (not has-shown-backtrace-hint?)
3044 ;; (not (memq 'backtrace (debug-options-interface))))
3047 ;;"Type \"(debug-enable 'backtrace)\" if you would like a backtrace
3048 ;;automatically if an error occurs in the future.\n")
3049 ;; (set! has-shown-backtrace-hint? #t))))
3050 ;; (display "No backtrace available.\n")))
3052 (define (error-catching-repl r e p)
3053 (error-catching-loop
3055 (call-with-values (lambda () (e (r)))
3056 (lambda the-values (for-each p the-values))))))
3058 (define (gc-run-time)
3059 (cdr (assq 'gc-time-taken (gc-stats))))
3061 (define before-read-hook (make-hook))
3062 (define after-read-hook (make-hook))
3063 (define before-eval-hook (make-hook 1))
3064 (define after-eval-hook (make-hook 1))
3065 (define before-print-hook (make-hook 1))
3066 (define after-print-hook (make-hook 1))
3068 ;;; The default repl-reader function. We may override this if we've
3069 ;;; the readline library.
3071 (lambda (prompt . reader)
3072 (if (not (char-ready?))
3073 (display (if (string? prompt) prompt (prompt))))
3075 (run-hook before-read-hook)
3076 ((or (and (pair? reader) (car reader))
3077 (fluid-ref current-reader)
3079 (current-input-port))))
3081 (define (scm-style-repl)
3086 (repl-report-start-timing (lambda ()
3087 (set! start-gc-rt (gc-run-time))
3088 (set! start-rt (get-internal-run-time))))
3089 (repl-report (lambda ()
3091 (display (inexact->exact
3092 (* 1000 (/ (- (get-internal-run-time) start-rt)
3093 internal-time-units-per-second))))
3095 (display (inexact->exact
3096 (* 1000 (/ (- (gc-run-time) start-gc-rt)
3097 internal-time-units-per-second))))
3098 (display " msec in gc)\n")))
3100 (consume-trailing-whitespace
3102 (let ((ch (peek-char)))
3105 ((or (char=? ch #\space) (char=? ch #\tab))
3107 (consume-trailing-whitespace))
3108 ((char=? ch #\newline)
3112 (let ((prompt (cond ((string? scm-repl-prompt)
3114 ((thunk? scm-repl-prompt)
3116 (scm-repl-prompt "> ")
3118 (repl-reader prompt))))
3120 ;; As described in R4RS, the READ procedure updates the
3121 ;; port to point to the first character past the end of
3122 ;; the external representation of the object. This
3123 ;; means that it doesn't consume the newline typically
3124 ;; found after an expression. This means that, when
3125 ;; debugging Guile with GDB, GDB gets the newline, which
3126 ;; it often interprets as a "continue" command, making
3127 ;; breakpoints kind of useless. So, consume any
3128 ;; trailing newline here, as well as any whitespace
3130 ;; But not if EOF, for control-D.
3131 (if (not (eof-object? val))
3132 (consume-trailing-whitespace))
3133 (run-hook after-read-hook)
3134 (if (eof-object? val)
3136 (repl-report-start-timing)
3137 (if scm-repl-verbose
3140 (display ";;; EOF -- quitting")
3145 (-eval (lambda (sourc)
3146 (repl-report-start-timing)
3147 (run-hook before-eval-hook sourc)
3148 (let ((val (start-stack 'repl-stack
3149 ;; If you change this procedure
3150 ;; (primitive-eval), please also
3151 ;; modify the repl-stack case in
3152 ;; save-stack so that stack cutting
3153 ;; continues to work.
3154 (primitive-eval sourc))))
3155 (run-hook after-eval-hook sourc)
3159 (-print (let ((maybe-print (lambda (result)
3160 (if (or scm-repl-print-unspecified
3161 (not (unspecified? result)))
3166 (if (not scm-repl-silent)
3168 (run-hook before-print-hook result)
3169 (maybe-print result)
3170 (run-hook after-print-hook result)
3171 (if scm-repl-verbose
3175 (-quit (lambda (args)
3176 (if scm-repl-verbose
3178 (display ";;; QUIT executed, repl exitting")
3183 (let ((status (error-catching-repl -read
3191 ;;; {IOTA functions: generating lists of numbers}
3195 (let loop ((count (1- n)) (result '()))
3196 (if (< count 0) result
3197 (loop (1- count) (cons count result)))))
3203 ;;; Similar to `begin' but returns a list of the results of all constituent
3204 ;;; forms instead of the result of the last form.
3205 ;;; (The definition relies on the current left-to-right
3206 ;;; order of evaluation of operands in applications.)
3209 (defmacro collect forms
3216 ;;; with `continue' and `break'.
3219 ;; The inner `do' loop avoids re-establishing a catch every iteration,
3220 ;; that's only necessary if continue is actually used. A new key is
3221 ;; generated every time, so break and continue apply to their originating
3222 ;; `while' even when recursing.
3224 ;; FIXME: This macro is unintentionally unhygienic with respect to let,
3225 ;; make-symbol, do, throw, catch, lambda, and not.
3227 (define-macro (while cond . body)
3228 (let ((keyvar (make-symbol "while-keyvar")))
3229 `(let ((,keyvar (make-symbol "while-key")))
3233 (let ((break (lambda () (throw ,keyvar #t)))
3234 (continue (lambda () (throw ,keyvar #f))))
3245 ;;; {Module System Macros}
3248 ;; Return a list of expressions that evaluate to the appropriate
3249 ;; arguments for resolve-interface according to SPEC.
3253 (if (memq 'prefix (read-options))
3254 (error "boot-9 must be compiled with #:kw, not :kw")))
3256 (define (keyword-like-symbol->keyword sym)
3257 (symbol->keyword (string->symbol (substring (symbol->string sym) 1))))
3259 ;; FIXME: we really need to clean up the guts of the module system.
3260 ;; We can compile to something better than process-define-module.
3261 (define-syntax define-module
3263 (define (keyword-like? stx)
3264 (let ((dat (syntax->datum stx)))
3266 (eqv? (string-ref (symbol->string dat) 0) #\:))))
3267 (define (->keyword sym)
3268 (symbol->keyword (string->symbol (substring (symbol->string sym) 1))))
3270 (define (quotify-iface args)
3271 (let loop ((in args) (out '()))
3274 ;; The user wanted #:foo, but wrote :foo. Fix it.
3275 ((sym . in) (keyword-like? #'sym)
3276 (loop #`(#,(->keyword (syntax->datum #'sym)) . in) out))
3277 ((kw . in) (not (keyword? (syntax->datum #'kw)))
3278 (syntax-violation 'define-module "expected keyword arg" x #'kw))
3279 ((#:renamer renamer . in)
3280 (loop #'in (cons* #'renamer #:renamer out)))
3282 (loop #'in (cons* #''val #'kw out))))))
3284 (define (quotify args)
3285 ;; Just quote everything except #:use-module and #:use-syntax. We
3286 ;; need to know about all arguments regardless since we want to turn
3287 ;; symbols that look like keywords into real keywords, and the
3288 ;; keyword args in a define-module form are not regular
3289 ;; (i.e. no-backtrace doesn't take a value).
3290 (let loop ((in args) (out '()))
3293 ;; The user wanted #:foo, but wrote :foo. Fix it.
3294 ((sym . in) (keyword-like? #'sym)
3295 (loop #`(#,(->keyword (syntax->datum #'sym)) . in) out))
3296 ((kw . in) (not (keyword? (syntax->datum #'kw)))
3297 (syntax-violation 'define-module "expected keyword arg" x #'kw))
3298 ((#:no-backtrace . in)
3299 (loop #'in (cons #:no-backtrace out)))
3301 (loop #'in (cons #:pure out)))
3303 (syntax-violation 'define-module "keyword arg without value" x #'kw))
3304 ((use-module (name name* ...) . in)
3305 (and (memq (syntax->datum #'use-module) '(#:use-module #:use-syntax))
3306 (and-map symbol? (syntax->datum #'(name name* ...))))
3308 (cons* #''((name name* ...))
3311 ((use-module ((name name* ...) arg ...) . in)
3312 (and (memq (syntax->datum #'use-module) '(#:use-module #:use-syntax))
3313 (and-map symbol? (syntax->datum #'(name name* ...))))
3315 (cons* #`(list '(name name* ...) #,@(quotify-iface #'(arg ...)))
3318 ((#:autoload name bindings . in)
3319 (loop #'in (cons* #''bindings #''name #:autoload out)))
3321 (loop #'in (cons* #''val #'kw out))))))
3324 ((_ (name name* ...) arg ...)
3325 (with-syntax (((quoted-arg ...) (quotify #'(arg ...))))
3326 #'(eval-when (eval load compile expand)
3327 (let ((m (process-define-module
3328 (list '(name name* ...) quoted-arg ...))))
3329 (set-current-module m)
3332 ;; The guts of the use-modules macro. Add the interfaces of the named
3333 ;; modules to the use-list of the current module, in order.
3335 ;; This function is called by "modules.c". If you change it, be sure
3336 ;; to change scm_c_use_module as well.
3338 (define (process-use-modules module-interface-args)
3339 (let ((interfaces (map (lambda (mif-args)
3340 (or (apply resolve-interface mif-args)
3341 (error "no such module" mif-args)))
3342 module-interface-args)))
3343 (call-with-deferred-observers
3345 (module-use-interfaces! (current-module) interfaces)))))
3347 (define-syntax use-modules
3349 (define (keyword-like? stx)
3350 (let ((dat (syntax->datum stx)))
3352 (eqv? (string-ref (symbol->string dat) 0) #\:))))
3353 (define (->keyword sym)
3354 (symbol->keyword (string->symbol (substring (symbol->string sym) 1))))
3356 (define (quotify-iface args)
3357 (let loop ((in args) (out '()))
3360 ;; The user wanted #:foo, but wrote :foo. Fix it.
3361 ((sym . in) (keyword-like? #'sym)
3362 (loop #`(#,(->keyword (syntax->datum #'sym)) . in) out))
3363 ((kw . in) (not (keyword? (syntax->datum #'kw)))
3364 (syntax-violation 'define-module "expected keyword arg" x #'kw))
3365 ((#:renamer renamer . in)
3366 (loop #'in (cons* #'renamer #:renamer out)))
3368 (loop #'in (cons* #''val #'kw out))))))
3370 (define (quotify specs)
3371 (let lp ((in specs) (out '()))
3374 (((name name* ...) . in)
3375 (and-map symbol? (syntax->datum #'(name name* ...)))
3376 (lp #'in (cons #''((name name* ...)) out)))
3377 ((((name name* ...) arg ...) . in)
3378 (and-map symbol? (syntax->datum #'(name name* ...)))
3379 (with-syntax (((quoted-arg ...) (quotify-iface #'(arg ...))))
3380 (lp #'in (cons #`(list '(name name* ...) quoted-arg ...)
3385 (with-syntax (((quoted-args ...) (quotify #'(spec ...))))
3386 #'(eval-when (eval load compile expand)
3387 (process-use-modules (list quoted-args ...))
3390 (define-syntax use-syntax
3394 (eval-when (eval load compile expand)
3395 (issue-deprecation-warning
3396 "`use-syntax' is deprecated. Please contact guile-devel for more info."))
3397 (use-modules spec ...)))))
3399 (include-from-path "ice-9/r6rs-libraries")
3401 (define-syntax define-private
3406 (define-syntax define-public
3408 ((_ (name . args) . body)
3409 (define-public name (lambda args . body)))
3415 (define-syntax defmacro-public
3417 ((_ name args . body)
3419 (defmacro name args . body)
3420 (export-syntax name)))))
3422 ;; And now for the most important macro.
3425 ((_ formals body ...)
3426 (lambda formals body ...))))
3429 ;; Export a local variable
3431 ;; This function is called from "modules.c". If you change it, be
3432 ;; sure to update "modules.c" as well.
3434 (define (module-export! m names)
3435 (let ((public-i (module-public-interface m)))
3436 (for-each (lambda (name)
3437 (let* ((internal-name (if (pair? name) (car name) name))
3438 (external-name (if (pair? name) (cdr name) name))
3439 (var (module-ensure-local-variable! m internal-name)))
3440 (module-add! public-i external-name var)))
3443 (define (module-replace! m names)
3444 (let ((public-i (module-public-interface m)))
3445 (for-each (lambda (name)
3446 (let* ((internal-name (if (pair? name) (car name) name))
3447 (external-name (if (pair? name) (cdr name) name))
3448 (var (module-ensure-local-variable! m internal-name)))
3449 (set-object-property! var 'replace #t)
3450 (module-add! public-i external-name var)))
3453 ;; Export all local variables from a module
3455 (define (module-export-all! mod)
3456 (define (fresh-interface!)
3457 (let ((iface (make-module)))
3458 (set-module-name! iface (module-name mod))
3459 ;; for guile 2: (set-module-version! iface (module-version mod))
3460 (set-module-kind! iface 'interface)
3461 (set-module-public-interface! mod iface)
3463 (let ((iface (or (module-public-interface mod)
3464 (fresh-interface!))))
3465 (set-module-obarray! iface (module-obarray mod))))
3467 ;; Re-export a imported variable
3469 (define (module-re-export! m names)
3470 (let ((public-i (module-public-interface m)))
3471 (for-each (lambda (name)
3472 (let* ((internal-name (if (pair? name) (car name) name))
3473 (external-name (if (pair? name) (cdr name) name))
3474 (var (module-variable m internal-name)))
3476 (error "Undefined variable:" internal-name))
3477 ((eq? var (module-local-variable m internal-name))
3478 (error "re-exporting local variable:" internal-name))
3480 (module-add! public-i external-name var)))))
3483 (define-syntax export
3486 (eval-when (eval load compile expand)
3487 (call-with-deferred-observers
3489 (module-export! (current-module) '(name ...))))))))
3491 (define-syntax re-export
3494 (eval-when (eval load compile expand)
3495 (call-with-deferred-observers
3497 (module-re-export! (current-module) '(name ...))))))))
3499 (define-syntax export-syntax
3502 (export name ...))))
3504 (define-syntax re-export-syntax
3507 (re-export name ...))))
3509 (define load load-module)
3516 (define make-mutable-parameter
3517 (let ((make (lambda (fluid converter)
3521 (fluid-set! fluid (converter (car args))))))))
3522 (lambda (init . converter)
3523 (let ((fluid (make-fluid))
3524 (converter (if (null? converter)
3527 (fluid-set! fluid (converter init))
3528 (make fluid converter)))))
3532 ;;; {Handling of duplicate imported bindings}
3535 ;; Duplicate handlers take the following arguments:
3537 ;; module importing module
3538 ;; name conflicting name
3539 ;; int1 old interface where name occurs
3540 ;; val1 value of binding in old interface
3541 ;; int2 new interface where name occurs
3542 ;; val2 value of binding in new interface
3543 ;; var previous resolution or #f
3544 ;; val value of previous resolution
3546 ;; A duplicate handler can take three alternative actions:
3548 ;; 1. return #f => leave responsibility to next handler
3549 ;; 2. exit with an error
3550 ;; 3. return a variable resolving the conflict
3553 (define duplicate-handlers
3554 (let ((m (make-module 7)))
3556 (define (check module name int1 val1 int2 val2 var val)
3557 (scm-error 'misc-error
3559 "~A: `~A' imported from both ~A and ~A"
3560 (list (module-name module)
3566 (define (warn module name int1 val1 int2 val2 var val)
3567 (format (current-error-port)
3568 "WARNING: ~A: `~A' imported from both ~A and ~A\n"
3569 (module-name module)
3575 (define (replace module name int1 val1 int2 val2 var val)
3576 (let ((old (or (and var (object-property var 'replace) var)
3577 (module-variable int1 name)))
3578 (new (module-variable int2 name)))
3579 (if (object-property old 'replace)
3580 (and (or (eq? old new)
3581 (not (object-property new 'replace)))
3583 (and (object-property new 'replace)
3586 (define (warn-override-core module name int1 val1 int2 val2 var val)
3587 (and (eq? int1 the-scm-module)
3589 (format (current-error-port)
3590 "WARNING: ~A: imported module ~A overrides core binding `~A'\n"
3591 (module-name module)
3594 (module-local-variable int2 name))))
3596 (define (first module name int1 val1 int2 val2 var val)
3597 (or var (module-local-variable int1 name)))
3599 (define (last module name int1 val1 int2 val2 var val)
3600 (module-local-variable int2 name))
3602 (define (noop module name int1 val1 int2 val2 var val)
3605 (set-module-name! m 'duplicate-handlers)
3606 (set-module-kind! m 'interface)
3607 (module-define! m 'check check)
3608 (module-define! m 'warn warn)
3609 (module-define! m 'replace replace)
3610 (module-define! m 'warn-override-core warn-override-core)
3611 (module-define! m 'first first)
3612 (module-define! m 'last last)
3613 (module-define! m 'merge-generics noop)
3614 (module-define! m 'merge-accessors noop)
3617 (define (lookup-duplicates-handlers handler-names)
3619 (map (lambda (handler-name)
3620 (or (module-symbol-local-binding
3621 duplicate-handlers handler-name #f)
3622 (error "invalid duplicate handler name:"
3624 (if (list? handler-names)
3626 (list handler-names)))))
3628 (define default-duplicate-binding-procedures
3629 (make-mutable-parameter #f))
3631 (define default-duplicate-binding-handler
3632 (make-mutable-parameter '(replace warn-override-core warn last)
3633 (lambda (handler-names)
3634 (default-duplicate-binding-procedures
3635 (lookup-duplicates-handlers handler-names))
3640 ;;; {`cond-expand' for SRFI-0 support.}
3642 ;;; This syntactic form expands into different commands or
3643 ;;; definitions, depending on the features provided by the Scheme
3649 ;;; --> (cond-expand <cond-expand-clause>+)
3650 ;;; | (cond-expand <cond-expand-clause>* (else <command-or-definition>))
3651 ;;; <cond-expand-clause>
3652 ;;; --> (<feature-requirement> <command-or-definition>*)
3653 ;;; <feature-requirement>
3654 ;;; --> <feature-identifier>
3655 ;;; | (and <feature-requirement>*)
3656 ;;; | (or <feature-requirement>*)
3657 ;;; | (not <feature-requirement>)
3658 ;;; <feature-identifier>
3659 ;;; --> <a symbol which is the name or alias of a SRFI>
3661 ;;; Additionally, this implementation provides the
3662 ;;; <feature-identifier>s `guile' and `r5rs', so that programs can
3663 ;;; determine the implementation type and the supported standard.
3665 ;;; Currently, the following feature identifiers are supported:
3667 ;;; guile r5rs srfi-0 srfi-4 srfi-6 srfi-13 srfi-14 srfi-55 srfi-61
3669 ;;; Remember to update the features list when adding more SRFIs.
3672 (define %cond-expand-features
3673 ;; Adjust the above comment when changing this.
3677 srfi-0 ;; cond-expand itself
3678 srfi-4 ;; homogenous numeric vectors
3679 srfi-6 ;; open-input-string etc, in the guile core
3680 srfi-13 ;; string library
3681 srfi-14 ;; character sets
3682 srfi-55 ;; require-extension
3683 srfi-61 ;; general cond clause
3686 ;; This table maps module public interfaces to the list of features.
3688 (define %cond-expand-table (make-hash-table 31))
3690 ;; Add one or more features to the `cond-expand' feature list of the
3693 (define (cond-expand-provide module features)
3694 (let ((mod (module-public-interface module)))
3696 (hashq-set! %cond-expand-table mod
3697 (append (hashq-ref %cond-expand-table mod '())
3700 (define-macro (cond-expand . clauses)
3701 (let ((syntax-error (lambda (cl)
3702 (error "invalid clause in `cond-expand'" cl))))
3708 (or (memq clause %cond-expand-features)
3709 (let lp ((uses (module-uses (current-module))))
3712 (hashq-ref %cond-expand-table
3718 ((eq? 'and (car clause))
3719 (let lp ((l (cdr clause)))
3723 (and (test-clause (car l)) (lp (cdr l))))
3725 (syntax-error clause)))))
3726 ((eq? 'or (car clause))
3727 (let lp ((l (cdr clause)))
3731 (or (test-clause (car l)) (lp (cdr l))))
3733 (syntax-error clause)))))
3734 ((eq? 'not (car clause))
3735 (cond ((not (pair? (cdr clause)))
3736 (syntax-error clause))
3737 ((pair? (cddr clause))
3738 ((syntax-error clause))))
3739 (not (test-clause (cadr clause))))
3741 (syntax-error clause))))
3743 (syntax-error clause))))))
3744 (let lp ((c clauses))
3747 (error "Unfulfilled `cond-expand'"))
3750 ((not (pair? (car c)))
3751 (syntax-error (car c)))
3752 ((test-clause (caar c))
3753 `(begin ,@(cdar c)))
3754 ((eq? (caar c) 'else)
3757 `(begin ,@(cdar c)))
3761 ;; This procedure gets called from the startup code with a list of
3762 ;; numbers, which are the numbers of the SRFIs to be loaded on startup.
3764 (define (use-srfis srfis)
3765 (process-use-modules
3767 (list (list 'srfi (string->symbol
3768 (string-append "srfi-" (number->string num))))))
3773 ;;; srfi-55: require-extension
3776 (define-macro (require-extension extension-spec)
3777 ;; This macro only handles the srfi extension, which, at present, is
3778 ;; the only one defined by the standard.
3779 (if (not (pair? extension-spec))
3780 (scm-error 'wrong-type-arg "require-extension"
3781 "Not an extension: ~S" (list extension-spec) #f))
3782 (let ((extension (car extension-spec))
3783 (extension-args (cdr extension-spec)))
3786 (let ((use-list '()))
3789 (if (not (integer? i))
3790 (scm-error 'wrong-type-arg "require-extension"
3791 "Invalid srfi name: ~S" (list i) #f))
3792 (let ((srfi-sym (string->symbol
3793 (string-append "srfi-" (number->string i)))))
3794 (if (not (memq srfi-sym %cond-expand-features))
3795 (set! use-list (cons `(use-modules (srfi ,srfi-sym))
3798 (if (pair? use-list)
3799 ;; i.e. (begin (use-modules x) (use-modules y) (use-modules z))
3800 `(begin ,@(reverse! use-list)))))
3803 'wrong-type-arg "require-extension"
3804 "Not a recognized extension type: ~S" (list extension) #f)))))
3808 ;;; {Load emacs interface support if emacs option is given.}
3811 (define (named-module-use! user usee)
3812 (module-use! (resolve-module user) (resolve-interface usee)))
3814 (define (load-emacs-interface)
3815 (and (provided? 'debug-extensions)
3816 (debug-enable 'backtrace))
3817 (named-module-use! '(guile-user) '(ice-9 emacs)))
3821 (define using-readline?
3822 (let ((using-readline? (make-fluid)))
3823 (make-procedure-with-setter
3824 (lambda () (fluid-ref using-readline?))
3825 (lambda (v) (fluid-set! using-readline? v)))))
3828 (let ((guile-user-module (resolve-module '(guile-user))))
3830 ;; Load emacs interface support if emacs option is given.
3831 (if (and (module-defined? guile-user-module 'use-emacs-interface)
3832 (module-ref guile-user-module 'use-emacs-interface))
3833 (load-emacs-interface))
3835 ;; Use some convenient modules (in reverse order)
3837 (set-current-module guile-user-module)
3838 (process-use-modules
3843 (if (provided? 'regex)
3846 (if (provided? 'threads)
3847 '(((ice-9 threads)))
3849 ;; load debugger on demand
3850 (module-autoload! guile-user-module '(system vm debug) '(debug))
3852 ;; Note: SIGFPE, SIGSEGV and SIGBUS are actually "query-only" (see
3853 ;; scmsigs.c scm_sigaction_for_thread), so the handlers setup here have
3855 (let ((old-handlers #f)
3856 (start-repl (module-ref (resolve-interface '(system repl repl))
3858 (signals (if (provided? 'posix)
3859 `((,SIGINT . "User interrupt")
3860 (,SIGFPE . "Arithmetic error")
3862 . "Bad memory access (Segmentation violation)"))
3864 ;; no SIGBUS on mingw
3865 (if (defined? 'SIGBUS)
3866 (set! signals (acons SIGBUS "Bad memory access (bus error)"
3873 (let ((make-handler (lambda (msg)
3875 ;; Make a backup copy of the stack
3876 (fluid-set! before-signal-stack
3877 (fluid-ref the-last-stack))
3885 (map (lambda (sig-msg)
3886 (sigaction (car sig-msg)
3887 (make-handler (cdr sig-msg))))
3890 ;; the protected thunk.
3892 (let ((status (start-repl 'scheme)))
3893 (run-hook exit-hook)
3898 (map (lambda (sig-msg old-handler)
3899 (if (not (car old-handler))
3900 ;; restore original C handler.
3901 (sigaction (car sig-msg) #f)
3902 ;; restore Scheme handler, SIG_IGN or SIG_DFL.
3903 (sigaction (car sig-msg)
3905 (cdr old-handler))))
3906 signals old-handlers))))))
3908 ;;; This hook is run at the very end of an interactive session.
3910 (define exit-hook (make-hook))
3914 ;;; {Deprecated stuff}
3918 (module-use! the-scm-module (resolve-interface '(ice-9 deprecated))))
3922 ;;; Place the user in the guile-user module.
3925 ;;; FIXME: annotate ?
3926 ;; (define (syncase exp)
3927 ;; (with-fluids ((expansion-eval-closure
3928 ;; (module-eval-closure (current-module))))
3929 ;; (deannotate/source-properties (macroexpand (annotate exp)))))
3932 (module-use! the-scm-module (resolve-interface '(srfi srfi-4)))
3934 (define-module (guile-user)
3935 #:autoload (system base compile) (compile))
3937 ;; Remain in the `(guile)' module at compilation-time so that the
3938 ;; `-Wunused-toplevel' warning works as expected.
3939 (eval-when (compile) (set-current-module the-root-module))
3941 ;;; boot-9.scm ends here