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)
360 (define macroexpand #f)
362 ;; $sc-dispatch is an implementation detail of psyntax. It is used by
363 ;; expanded macros, to dispatch an input against a set of patterns.
364 (define $sc-dispatch #f)
367 (primitive-load-path "ice-9/psyntax-pp")
369 ;; %pre-modules-transformer is the Scheme expander from now until the
370 ;; module system has booted up.
371 (define %pre-modules-transformer macroexpand)
377 ((_ x y ...) (if x (and y ...) #f))))
383 ((_ x y ...) (let ((t x)) (if t t (or y ...))))))
385 ;; The "maybe-more" bits are something of a hack, so that we can support
386 ;; SRFI-61. Rewrites into a standalone syntax-case macro would be
389 (syntax-rules (=> else)
390 ((_ "maybe-more" test consequent)
391 (if test consequent))
393 ((_ "maybe-more" test consequent clause ...)
394 (if test consequent (cond clause ...)))
396 ((_ (else else1 else2 ...))
397 (begin else1 else2 ...))
399 ((_ (test => receiver) more-clause ...)
401 (cond "maybe-more" t (receiver t) more-clause ...)))
403 ((_ (generator guard => receiver) more-clause ...)
404 (call-with-values (lambda () generator)
407 (apply guard t) (apply receiver t) more-clause ...))))
409 ((_ (test => receiver ...) more-clause ...)
410 (syntax-violation 'cond "wrong number of receiver expressions"
411 '(test => receiver ...)))
412 ((_ (generator guard => receiver ...) more-clause ...)
413 (syntax-violation 'cond "wrong number of receiver expressions"
414 '(generator guard => receiver ...)))
416 ((_ (test) more-clause ...)
418 (cond "maybe-more" t t more-clause ...)))
420 ((_ (test body1 body2 ...) more-clause ...)
422 test (begin body1 body2 ...) more-clause ...))))
428 (let ((atom-key (key ...)))
429 (case atom-key clauses ...)))
431 (else result1 result2 ...))
432 (begin result1 result2 ...))
434 ((atoms ...) result1 result2 ...))
435 (if (memv key '(atoms ...))
436 (begin result1 result2 ...)))
438 ((atoms ...) result1 result2 ...)
440 (if (memv key '(atoms ...))
441 (begin result1 result2 ...)
442 (case key clause clauses ...)))))
446 ((do ((var init step ...) ...)
459 (loop (do "step" var step ...)
469 ((_ exp) (make-promise (lambda () exp)))))
471 (include-from-path "ice-9/quasisyntax")
473 ;;; @bind is used by the old elisp code as a dynamic scoping mechanism.
474 ;;; Please let the Guile developers know if you are using this macro.
478 (define (bound-member id ids)
479 (cond ((null? ids) #f)
480 ((bound-identifier=? id (car ids)) #t)
481 ((bound-member (car ids) (cdr ids)))))
485 #'(let () b0 b1 ...))
486 ((_ ((id val) ...) b0 b1 ...)
487 (and-map identifier? #'(id ...))
488 (if (let lp ((ids #'(id ...)))
489 (cond ((null? ids) #f)
490 ((bound-member (car ids) (cdr ids)) #t)
491 (else (lp (cdr ids)))))
492 (syntax-violation '@bind "duplicate bound identifier" x)
493 (with-syntax (((old-v ...) (generate-temporaries #'(id ...)))
494 ((v ...) (generate-temporaries #'(id ...))))
495 #'(let ((old-v id) ...
500 (lambda () b0 b1 ...)
502 (set! id old-v) ...)))))))))
510 (define-syntax define-macro
514 ((_ (macro . args) doc body1 body ...)
515 (string? (syntax->datum #'doc))
516 #'(define-macro macro doc (lambda args body1 body ...)))
517 ((_ (macro . args) body ...)
518 #'(define-macro macro #f (lambda args body ...)))
519 ((_ macro doc transformer)
520 (or (string? (syntax->datum #'doc))
521 (not (syntax->datum #'doc)))
522 #'(define-syntax macro
525 #((macro-type . defmacro)
526 (defmacro-args args))
529 (let ((v (syntax->datum #'args)))
530 (datum->syntax y (apply transformer v)))))))))))
532 (define-syntax defmacro
534 "Define a defmacro, with the old lispy defun syntax."
536 ((_ macro args doc body1 body ...)
537 (string? (syntax->datum #'doc))
538 #'(define-macro macro doc (lambda args body1 body ...)))
539 ((_ macro args body ...)
540 #'(define-macro macro #f (lambda args body ...))))))
548 ;;; Depends on: defmacro
551 (defmacro begin-deprecated forms
552 (if (include-deprecated-features)
558 ;;; {Trivial Functions}
561 (define (identity x) x)
562 (define (and=> value procedure) (and value (procedure value)))
563 (define call/cc call-with-current-continuation)
565 ;;; apply-to-args is functionally redundant with apply and, worse,
566 ;;; is less general than apply since it only takes two arguments.
568 ;;; On the other hand, apply-to-args is a syntacticly convenient way to
569 ;;; perform binding in many circumstances when the "let" family of
570 ;;; of forms don't cut it. E.g.:
572 ;;; (apply-to-args (return-3d-mouse-coords)
577 (define (apply-to-args args fn) (apply fn args))
579 (defmacro false-if-exception (expr)
582 ;; avoid saving backtraces inside false-if-exception
583 (with-fluids ((the-last-stack (fluid-ref the-last-stack)))
589 ;;; {General Properties}
592 ;; This is a more modern interface to properties. It will replace all
593 ;; other property-like things eventually.
595 (define (make-object-property)
596 (let ((prop (primitive-make-property #f)))
597 (make-procedure-with-setter
598 (lambda (obj) (primitive-property-ref prop obj))
599 (lambda (obj val) (primitive-property-set! prop obj val)))))
603 ;;; {Symbol Properties}
606 (define (symbol-property sym prop)
607 (let ((pair (assoc prop (symbol-pref sym))))
608 (and pair (cdr pair))))
610 (define (set-symbol-property! sym prop val)
611 (let ((pair (assoc prop (symbol-pref sym))))
614 (symbol-pset! sym (acons prop val (symbol-pref sym))))))
616 (define (symbol-property-remove! sym prop)
617 (let ((pair (assoc prop (symbol-pref sym))))
619 (symbol-pset! sym (delq! pair (symbol-pref sym))))))
626 (define (array-shape a)
627 (map (lambda (ind) (if (number? ind) (list 0 (+ -1 ind)) ind))
628 (array-dimensions a)))
635 (define (kw-arg-ref args kw)
636 (let ((rem (member kw args)))
637 (and rem (pair? (cdr rem)) (cadr rem))))
644 (define (struct-layout s)
645 (struct-ref (struct-vtable s) vtable-index-layout))
652 ;; Printing records: by default, records are printed as
654 ;; #<type-name field1: val1 field2: val2 ...>
656 ;; You can change that by giving a custom printing function to
657 ;; MAKE-RECORD-TYPE (after the list of field symbols). This function
658 ;; will be called like
660 ;; (<printer> object port)
662 ;; It should print OBJECT to PORT.
664 (define (inherit-print-state old-port new-port)
665 (if (get-print-state old-port)
666 (port-with-print-state new-port (get-print-state old-port))
669 ;; 0: type-name, 1: fields
670 (define record-type-vtable
671 (make-vtable-vtable "prpr" 0
673 (cond ((eq? s record-type-vtable)
674 (display "#<record-type-vtable>" p))
676 (display "#<record-type " p)
677 (display (record-type-name s) p)
680 (define (record-type? obj)
681 (and (struct? obj) (eq? record-type-vtable (struct-vtable obj))))
683 (define (make-record-type type-name fields . opt)
684 (let ((printer-fn (and (pair? opt) (car opt))))
685 (let ((struct (make-struct record-type-vtable 0
688 (map (lambda (f) "pw") fields)))
692 (display type-name p)
693 (let loop ((fields fields)
696 ((not (null? fields))
698 (display (car fields) p)
700 (display (struct-ref s off) p)
701 (loop (cdr fields) (+ 1 off)))))
704 (copy-tree fields))))
705 ;; Temporary solution: Associate a name to the record type descriptor
706 ;; so that the object system can create a wrapper class for it.
707 (set-struct-vtable-name! struct (if (symbol? type-name)
709 (string->symbol type-name)))
712 (define (record-type-name obj)
713 (if (record-type? obj)
714 (struct-ref obj vtable-offset-user)
715 (error 'not-a-record-type obj)))
717 (define (record-type-fields obj)
718 (if (record-type? obj)
719 (struct-ref obj (+ 1 vtable-offset-user))
720 (error 'not-a-record-type obj)))
722 (define (record-constructor rtd . opt)
723 (let ((field-names (if (pair? opt) (car opt) (record-type-fields rtd))))
725 `(lambda ,field-names
726 (make-struct ',rtd 0 ,@(map (lambda (f)
727 (if (memq f field-names)
730 (record-type-fields rtd)))))))
732 (define (record-predicate rtd)
733 (lambda (obj) (and (struct? obj) (eq? rtd (struct-vtable obj)))))
735 (define (%record-type-error rtd obj) ;; private helper
736 (or (eq? rtd (record-type-descriptor obj))
737 (scm-error 'wrong-type-arg "%record-type-check"
738 "Wrong type record (want `~S'): ~S"
739 (list (record-type-name rtd) obj)
742 (define (record-accessor rtd field-name)
743 (let ((pos (list-index (record-type-fields rtd) field-name)))
745 (error 'no-such-field field-name))
747 (if (eq? (struct-vtable obj) rtd)
749 (%record-type-error rtd obj)))))
751 (define (record-modifier rtd field-name)
752 (let ((pos (list-index (record-type-fields rtd) field-name)))
754 (error 'no-such-field field-name))
756 (if (eq? (struct-vtable obj) rtd)
757 (struct-set! obj pos val)
758 (%record-type-error rtd obj)))))
760 (define (record? obj)
761 (and (struct? obj) (record-type? (struct-vtable obj))))
763 (define (record-type-descriptor obj)
766 (error 'not-a-record obj)))
775 (define (->bool x) (not (not x)))
782 (define (symbol-append . args)
783 (string->symbol (apply string-append (map symbol->string args))))
785 (define (list->symbol . args)
786 (string->symbol (apply list->string args)))
788 (define (symbol . args)
789 (string->symbol (apply string args)))
796 (define (list-index l k)
802 (loop (+ n 1) (cdr l))))))
806 (if (provided? 'posix)
807 (primitive-load-path "ice-9/posix"))
809 (if (provided? 'socket)
810 (primitive-load-path "ice-9/networking"))
812 ;; For reference, Emacs file-exists-p uses stat in this same way.
814 (if (provided? 'posix)
816 (->bool (stat str #f)))
818 (let ((port (catch 'system-error (lambda () (open-file str OPEN_READ))
820 (if port (begin (close-port port) #t)
823 (define file-is-directory?
824 (if (provided? 'posix)
826 (eq? (stat:type (stat str)) 'directory))
828 (let ((port (catch 'system-error
829 (lambda () (open-file (string-append str "/.")
832 (if port (begin (close-port port) #t)
835 (define (has-suffix? str suffix)
836 (string-suffix? suffix str))
838 (define (system-error-errno args)
839 (if (eq? (car args) 'system-error)
840 (car (list-ref args 4))
848 (define (error . args)
851 (scm-error 'misc-error #f "?" #f #f)
852 (let loop ((msg "~A")
854 (if (not (null? rest))
855 (loop (string-append msg " ~S")
857 (scm-error 'misc-error #f msg args #f)))))
859 ;; bad-throw is the hook that is called upon a throw to a an unhandled
860 ;; key (unless the throw has four arguments, in which case
861 ;; it's usually interpreted as an error throw.)
862 ;; If the key has a default handler (a throw-handler-default property),
863 ;; it is applied to the throw.
865 (define (bad-throw key . args)
866 (let ((default (symbol-property key 'throw-handler-default)))
867 (or (and default (apply default key args))
868 (apply error "unhandled-exception:" key args))))
872 (define (tm:sec obj) (vector-ref obj 0))
873 (define (tm:min obj) (vector-ref obj 1))
874 (define (tm:hour obj) (vector-ref obj 2))
875 (define (tm:mday obj) (vector-ref obj 3))
876 (define (tm:mon obj) (vector-ref obj 4))
877 (define (tm:year obj) (vector-ref obj 5))
878 (define (tm:wday obj) (vector-ref obj 6))
879 (define (tm:yday obj) (vector-ref obj 7))
880 (define (tm:isdst obj) (vector-ref obj 8))
881 (define (tm:gmtoff obj) (vector-ref obj 9))
882 (define (tm:zone obj) (vector-ref obj 10))
884 (define (set-tm:sec obj val) (vector-set! obj 0 val))
885 (define (set-tm:min obj val) (vector-set! obj 1 val))
886 (define (set-tm:hour obj val) (vector-set! obj 2 val))
887 (define (set-tm:mday obj val) (vector-set! obj 3 val))
888 (define (set-tm:mon obj val) (vector-set! obj 4 val))
889 (define (set-tm:year obj val) (vector-set! obj 5 val))
890 (define (set-tm:wday obj val) (vector-set! obj 6 val))
891 (define (set-tm:yday obj val) (vector-set! obj 7 val))
892 (define (set-tm:isdst obj val) (vector-set! obj 8 val))
893 (define (set-tm:gmtoff obj val) (vector-set! obj 9 val))
894 (define (set-tm:zone obj val) (vector-set! obj 10 val))
896 (define (tms:clock obj) (vector-ref obj 0))
897 (define (tms:utime obj) (vector-ref obj 1))
898 (define (tms:stime obj) (vector-ref obj 2))
899 (define (tms:cutime obj) (vector-ref obj 3))
900 (define (tms:cstime obj) (vector-ref obj 4))
902 (define file-position ftell)
903 (define (file-set-position port offset . whence)
904 (let ((whence (if (eq? whence '()) SEEK_SET (car whence))))
905 (seek port offset whence)))
907 (define (move->fdes fd/port fd)
908 (cond ((integer? fd/port)
909 (dup->fdes fd/port fd)
913 (primitive-move->fdes fd/port fd)
914 (set-port-revealed! fd/port 1)
917 (define (release-port-handle port)
918 (let ((revealed (port-revealed port)))
920 (set-port-revealed! port (- revealed 1)))))
922 (define (dup->port port/fd mode . maybe-fd)
923 (let ((port (fdopen (apply dup->fdes port/fd maybe-fd)
926 (set-port-revealed! port 1))
929 (define (dup->inport port/fd . maybe-fd)
930 (apply dup->port port/fd "r" maybe-fd))
932 (define (dup->outport port/fd . maybe-fd)
933 (apply dup->port port/fd "w" maybe-fd))
935 (define (dup port/fd . maybe-fd)
936 (if (integer? port/fd)
937 (apply dup->fdes port/fd maybe-fd)
938 (apply dup->port port/fd (port-mode port/fd) maybe-fd)))
940 (define (duplicate-port port modes)
941 (dup->port port modes))
943 (define (fdes->inport fdes)
944 (let loop ((rest-ports (fdes->ports fdes)))
945 (cond ((null? rest-ports)
946 (let ((result (fdopen fdes "r")))
947 (set-port-revealed! result 1)
949 ((input-port? (car rest-ports))
950 (set-port-revealed! (car rest-ports)
951 (+ (port-revealed (car rest-ports)) 1))
954 (loop (cdr rest-ports))))))
956 (define (fdes->outport fdes)
957 (let loop ((rest-ports (fdes->ports fdes)))
958 (cond ((null? rest-ports)
959 (let ((result (fdopen fdes "w")))
960 (set-port-revealed! result 1)
962 ((output-port? (car rest-ports))
963 (set-port-revealed! (car rest-ports)
964 (+ (port-revealed (car rest-ports)) 1))
967 (loop (cdr rest-ports))))))
969 (define (port->fdes port)
970 (set-port-revealed! port (+ (port-revealed port) 1))
973 (define (setenv name value)
975 (putenv (string-append name "=" value))
978 (define (unsetenv name)
979 "Remove the entry for NAME from the environment."
987 ;;; Here for backward compatability
989 (define scheme-file-suffix (lambda () ".scm"))
991 (define (in-vicinity vicinity file)
992 (let ((tail (let ((len (string-length vicinity)))
995 (string-ref vicinity (- len 1))))))
996 (string-append vicinity
1005 ;;; {Help for scm_shell}
1007 ;;; The argument-processing code used by Guile-based shells generates
1008 ;;; Scheme code based on the argument list. This page contains help
1009 ;;; functions for the code it generates.
1012 (define (command-line) (program-arguments))
1014 ;; This is mostly for the internal use of the code generated by
1015 ;; scm_compile_shell_switches.
1017 (define (turn-on-debugging)
1018 (debug-enable 'debug)
1019 (debug-enable 'backtrace)
1020 (read-enable 'positions))
1022 (define (load-user-init)
1023 (let* ((home (or (getenv "HOME")
1024 (false-if-exception (passwd:dir (getpwuid (getuid))))
1025 "/")) ;; fallback for cygwin etc.
1026 (init-file (in-vicinity home ".guile")))
1027 (if (file-exists? init-file)
1028 (primitive-load init-file))))
1032 ;;; {The interpreter stack}
1035 ;; %stacks defined in stacks.c
1036 (define (%start-stack tag thunk)
1037 (let ((prompt-tag (make-prompt-tag "start-stack")))
1041 (with-fluids ((%stacks (acons tag prompt-tag
1042 (or (fluid-ref %stacks) '()))))
1045 (%start-stack tag (lambda () (apply k args)))))))
1046 (define-syntax start-stack
1049 (%start-stack tag (lambda () exp)))))
1053 ;;; {Loading by paths}
1056 ;;; Load a Scheme source file named NAME, searching for it in the
1057 ;;; directories listed in %load-path, and applying each of the file
1058 ;;; name extensions listed in %load-extensions.
1059 (define (load-from-path name)
1060 (start-stack 'load-stack
1061 (primitive-load-path name)))
1063 (define %load-verbosely #f)
1064 (define (assert-load-verbosity v) (set! %load-verbosely v))
1066 (define (%load-announce file)
1068 (with-output-to-port (current-error-port)
1071 (display "loading ")
1076 (set! %load-hook %load-announce)
1078 (define (load name . reader)
1079 ;; Returns the .go file corresponding to `name'. Does not search load
1080 ;; paths, only the fallback path. If the .go file is missing or out of
1081 ;; date, and autocompilation is enabled, will try autocompilation, just
1082 ;; as primitive-load-path does internally. primitive-load is
1083 ;; unaffected. Returns #f if autocompilation failed or was disabled.
1085 ;; NB: Unless we need to compile the file, this function should not cause
1086 ;; (system base compile) to be loaded up. For that reason compiled-file-name
1087 ;; partially duplicates functionality from (system base compile).
1088 (define (compiled-file-name canon-path)
1089 (and %compile-fallback-path
1091 %compile-fallback-path
1092 ;; no need for '/' separator here, canon-path is absolute
1094 (cond ((or (null? %load-compiled-extensions)
1095 (string-null? (car %load-compiled-extensions)))
1096 (warn "invalid %load-compiled-extensions"
1097 %load-compiled-extensions)
1099 (else (car %load-compiled-extensions))))))
1100 (define (fresh-compiled-file-name go-path)
1103 (let* ((scmstat (stat name))
1104 (gostat (stat go-path #f)))
1105 (if (and gostat (= (stat:mtime gostat) (stat:mtime scmstat)))
1109 (format (current-error-port)
1110 ";;; note: source file ~a\n;;; newer than compiled ~a\n"
1113 (%load-should-autocompile
1114 (%warn-autocompilation-enabled)
1115 (format (current-error-port) ";;; compiling ~a\n" name)
1116 (let ((cfn ((@ (system base compile) compile-file) name
1117 #:env (current-module))))
1118 (format (current-error-port) ";;; compiled ~a\n" cfn)
1122 (format (current-error-port)
1123 ";;; WARNING: compilation of ~a failed:\n;;; key ~a, throw_args ~s\n"
1126 (with-fluids ((current-reader (and (pair? reader) (car reader))))
1127 (let ((cfn (and=> (and=> (false-if-exception (canonicalize-path name))
1129 fresh-compiled-file-name)))
1132 (start-stack 'load-stack
1133 (primitive-load name))))))
1137 ;;; {Reader Extensions}
1139 ;;; Reader code for various "#c" forms.
1142 (define read-eval? (make-fluid))
1143 (fluid-set! read-eval? #f)
1144 (read-hash-extend #\.
1146 (if (fluid-ref read-eval?)
1147 (eval (read port) (interaction-environment))
1149 "#. read expansion found and read-eval? is #f."))))
1153 ;;; {Command Line Options}
1156 (define (get-option argv kw-opts kw-args return)
1159 (return #f #f argv))
1161 ((or (not (eq? #\- (string-ref (car argv) 0)))
1162 (eq? (string-length (car argv)) 1))
1163 (return 'normal-arg (car argv) (cdr argv)))
1165 ((eq? #\- (string-ref (car argv) 1))
1166 (let* ((kw-arg-pos (or (string-index (car argv) #\=)
1167 (string-length (car argv))))
1168 (kw (symbol->keyword (substring (car argv) 2 kw-arg-pos)))
1169 (kw-opt? (member kw kw-opts))
1170 (kw-arg? (member kw kw-args))
1171 (arg (or (and (not (eq? kw-arg-pos (string-length (car argv))))
1172 (substring (car argv)
1174 (string-length (car argv))))
1176 (begin (set! argv (cdr argv)) (car argv))))))
1177 (if (or kw-opt? kw-arg?)
1178 (return kw arg (cdr argv))
1179 (return 'usage-error kw (cdr argv)))))
1182 (let* ((char (substring (car argv) 1 2))
1183 (kw (symbol->keyword char)))
1186 ((member kw kw-opts)
1187 (let* ((rest-car (substring (car argv) 2 (string-length (car argv))))
1188 (new-argv (if (= 0 (string-length rest-car))
1190 (cons (string-append "-" rest-car) (cdr argv)))))
1191 (return kw #f new-argv)))
1193 ((member kw kw-args)
1194 (let* ((rest-car (substring (car argv) 2 (string-length (car argv))))
1195 (arg (if (= 0 (string-length rest-car))
1198 (new-argv (if (= 0 (string-length rest-car))
1201 (return kw arg new-argv)))
1203 (else (return 'usage-error kw argv)))))))
1205 (define (for-next-option proc argv kw-opts kw-args)
1206 (let loop ((argv argv))
1207 (get-option argv kw-opts kw-args
1208 (lambda (opt opt-arg argv)
1209 (and opt (proc opt opt-arg argv loop))))))
1211 (define (display-usage-report kw-desc)
1214 (or (eq? (car kw) #t)
1215 (eq? (car kw) 'else)
1216 (let* ((opt-desc kw)
1217 (help (cadr opt-desc))
1218 (opts (car opt-desc))
1219 (opts-proper (if (string? (car opts)) (cdr opts) opts))
1220 (arg-name (if (string? (car opts))
1221 (string-append "<" (car opts) ">")
1223 (left-part (string-append
1224 (with-output-to-string
1226 (map (lambda (x) (display (keyword->symbol x)) (display " "))
1229 (middle-part (if (and (< (string-length left-part) 30)
1230 (< (string-length help) 40))
1231 (make-string (- 30 (string-length left-part)) #\ )
1234 (display middle-part)
1241 (define (transform-usage-lambda cases)
1242 (let* ((raw-usage (delq! 'else (map car cases)))
1243 (usage-sans-specials (map (lambda (x)
1244 (or (and (not (list? x)) x)
1245 (and (symbol? (car x)) #t)
1246 (and (boolean? (car x)) #t)
1249 (usage-desc (delq! #t usage-sans-specials))
1250 (kw-desc (map car usage-desc))
1251 (kw-opts (apply append (map (lambda (x) (and (not (string? (car x))) x)) kw-desc)))
1252 (kw-args (apply append (map (lambda (x) (and (string? (car x)) (cdr x))) kw-desc)))
1253 (transmogrified-cases (map (lambda (case)
1254 (cons (let ((opts (car case)))
1255 (if (or (boolean? opts) (eq? 'else opts))
1258 ((symbol? (car opts)) opts)
1259 ((boolean? (car opts)) opts)
1260 ((string? (caar opts)) (cdar opts))
1261 (else (car opts)))))
1264 `(let ((%display-usage (lambda () (display-usage-report ',usage-desc))))
1266 (let %next-arg ((%argv %argv))
1270 (lambda (%opt %arg %new-argv)
1272 ,@ transmogrified-cases))))))))
1277 ;;; {Low Level Modules}
1279 ;;; These are the low level data structures for modules.
1281 ;;; Every module object is of the type 'module-type', which is a record
1282 ;;; consisting of the following members:
1284 ;;; - eval-closure: the function that defines for its module the strategy that
1285 ;;; shall be followed when looking up symbols in the module.
1287 ;;; An eval-closure is a function taking two arguments: the symbol to be
1288 ;;; looked up and a boolean value telling whether a binding for the symbol
1289 ;;; should be created if it does not exist yet. If the symbol lookup
1290 ;;; succeeded (either because an existing binding was found or because a new
1291 ;;; binding was created), a variable object representing the binding is
1292 ;;; returned. Otherwise, the value #f is returned. Note that the eval
1293 ;;; closure does not take the module to be searched as an argument: During
1294 ;;; construction of the eval-closure, the eval-closure has to store the
1295 ;;; module it belongs to in its environment. This means, that any
1296 ;;; eval-closure can belong to only one module.
1298 ;;; The eval-closure of a module can be defined arbitrarily. However, three
1299 ;;; special cases of eval-closures are to be distinguished: During startup
1300 ;;; the module system is not yet activated. In this phase, no modules are
1301 ;;; defined and all bindings are automatically stored by the system in the
1302 ;;; pre-modules-obarray. Since no eval-closures exist at this time, the
1303 ;;; functions which require an eval-closure as their argument need to be
1304 ;;; passed the value #f.
1306 ;;; The other two special cases of eval-closures are the
1307 ;;; standard-eval-closure and the standard-interface-eval-closure. Both
1308 ;;; behave equally for the case that no new binding is to be created. The
1309 ;;; difference between the two comes in, when the boolean argument to the
1310 ;;; eval-closure indicates that a new binding shall be created if it is not
1313 ;;; Given that no new binding shall be created, both standard eval-closures
1314 ;;; define the following standard strategy of searching bindings in the
1315 ;;; module: First, the module's obarray is searched for the symbol. Second,
1316 ;;; if no binding for the symbol was found in the module's obarray, the
1317 ;;; module's binder procedure is exececuted. If this procedure did not
1318 ;;; return a binding for the symbol, the modules referenced in the module's
1319 ;;; uses list are recursively searched for a binding of the symbol. If the
1320 ;;; binding can not be found in these modules also, the symbol lookup has
1323 ;;; If a new binding shall be created, the standard-interface-eval-closure
1324 ;;; immediately returns indicating failure. That is, it does not even try
1325 ;;; to look up the symbol. In contrast, the standard-eval-closure would
1326 ;;; first search the obarray, and if no binding was found there, would
1327 ;;; create a new binding in the obarray, therefore not calling the binder
1328 ;;; procedure or searching the modules in the uses list.
1330 ;;; The explanation of the following members obarray, binder and uses
1331 ;;; assumes that the symbol lookup follows the strategy that is defined in
1332 ;;; the standard-eval-closure and the standard-interface-eval-closure.
1334 ;;; - obarray: a hash table that maps symbols to variable objects. In this
1335 ;;; hash table, the definitions are found that are local to the module (that
1336 ;;; is, not imported from other modules). When looking up bindings in the
1337 ;;; module, this hash table is searched first.
1339 ;;; - binder: either #f or a function taking a module and a symbol argument.
1340 ;;; If it is a function it is called after the obarray has been
1341 ;;; unsuccessfully searched for a binding. It then can provide bindings
1342 ;;; that would otherwise not be found locally in the module.
1344 ;;; - uses: a list of modules from which non-local bindings can be inherited.
1345 ;;; These modules are the third place queried for bindings after the obarray
1346 ;;; has been unsuccessfully searched and the binder function did not deliver
1347 ;;; a result either.
1349 ;;; - transformer: either #f or a function taking a scheme expression as
1350 ;;; delivered by read. If it is a function, it will be called to perform
1351 ;;; syntax transformations (e. g. makro expansion) on the given scheme
1352 ;;; expression. The output of the transformer function will then be passed
1353 ;;; to Guile's internal memoizer. This means that the output must be valid
1354 ;;; scheme code. The only exception is, that the output may make use of the
1355 ;;; syntax extensions provided to identify the modules that a binding
1358 ;;; - name: the name of the module. This is used for all kinds of printing
1359 ;;; outputs. In certain places the module name also serves as a way of
1360 ;;; identification. When adding a module to the uses list of another
1361 ;;; module, it is made sure that the new uses list will not contain two
1362 ;;; modules of the same name.
1364 ;;; - kind: classification of the kind of module. The value is (currently?)
1365 ;;; only used for printing. It has no influence on how a module is treated.
1366 ;;; Currently the following values are used when setting the module kind:
1367 ;;; 'module, 'directory, 'interface, 'custom-interface. If no explicit kind
1368 ;;; is set, it defaults to 'module.
1370 ;;; - duplicates-handlers: a list of procedures that get called to make a
1371 ;;; choice between two duplicate bindings when name clashes occur. See the
1372 ;;; `duplicate-handlers' global variable below.
1374 ;;; - observers: a list of procedures that get called when the module is
1377 ;;; - weak-observers: a weak-key hash table of procedures that get called
1378 ;;; when the module is modified. See `module-observe-weak' for details.
1380 ;;; In addition, the module may (must?) contain a binding for
1381 ;;; `%module-public-interface'. This variable should be bound to a module
1382 ;;; representing the exported interface of a module. See the
1383 ;;; `module-public-interface' and `module-export!' procedures.
1385 ;;; !!! warning: The interface to lazy binder procedures is going
1386 ;;; to be changed in an incompatible way to permit all the basic
1387 ;;; module ops to be virtualized.
1389 ;;; (make-module size use-list lazy-binding-proc) => module
1390 ;;; module-{obarray,uses,binder}[|-set!]
1391 ;;; (module? obj) => [#t|#f]
1392 ;;; (module-locally-bound? module symbol) => [#t|#f]
1393 ;;; (module-bound? module symbol) => [#t|#f]
1394 ;;; (module-symbol-locally-interned? module symbol) => [#t|#f]
1395 ;;; (module-symbol-interned? module symbol) => [#t|#f]
1396 ;;; (module-local-variable module symbol) => [#<variable ...> | #f]
1397 ;;; (module-variable module symbol) => [#<variable ...> | #f]
1398 ;;; (module-symbol-binding module symbol opt-value)
1399 ;;; => [ <obj> | opt-value | an error occurs ]
1400 ;;; (module-make-local-var! module symbol) => #<variable...>
1401 ;;; (module-add! module symbol var) => unspecified
1402 ;;; (module-remove! module symbol) => unspecified
1403 ;;; (module-for-each proc module) => unspecified
1404 ;;; (make-scm-module) => module ; a lazy copy of the symhash module
1405 ;;; (set-current-module module) => unspecified
1406 ;;; (current-module) => #<module...>
1412 ;;; {Printing Modules}
1415 ;; This is how modules are printed. You can re-define it.
1416 ;; (Redefining is actually more complicated than simply redefining
1417 ;; %print-module because that would only change the binding and not
1418 ;; the value stored in the vtable that determines how record are
1421 (define (%print-module mod port) ; unused args: depth length style table)
1423 (display (or (module-kind mod) "module") port)
1425 (display (module-name mod) port)
1427 (display (number->string (object-address mod) 16) port)
1432 ;; A module is characterized by an obarray in which local symbols
1433 ;; are interned, a list of modules, "uses", from which non-local
1434 ;; bindings can be inherited, and an optional lazy-binder which
1435 ;; is a (CLOSURE module symbol) which, as a last resort, can provide
1436 ;; bindings that would otherwise not be found locally in the module.
1438 ;; NOTE: If you change anything here, you also need to change
1439 ;; libguile/modules.h.
1442 (make-record-type 'module
1443 '(obarray uses binder eval-closure transformer name kind
1444 duplicates-handlers import-obarray
1445 observers weak-observers version)
1448 ;; make-module &opt size uses binder
1450 ;; Create a new module, perhaps with a particular size of obarray,
1451 ;; initial uses list, or binding procedure.
1456 (define (parse-arg index default)
1457 (if (> (length args) index)
1458 (list-ref args index)
1461 (define %default-import-size
1462 ;; Typical number of imported bindings actually used by a module.
1465 (if (> (length args) 3)
1466 (error "Too many args to make-module." args))
1468 (let ((size (parse-arg 0 31))
1469 (uses (parse-arg 1 '()))
1470 (binder (parse-arg 2 #f)))
1472 (if (not (integer? size))
1473 (error "Illegal size to make-module." size))
1474 (if (not (and (list? uses)
1475 (and-map module? uses)))
1476 (error "Incorrect use list." uses))
1477 (if (and binder (not (procedure? binder)))
1479 "Lazy-binder expected to be a procedure or #f." binder))
1481 (let ((module (module-constructor (make-hash-table size)
1482 uses binder #f %pre-modules-transformer
1484 (make-hash-table %default-import-size)
1486 (make-weak-key-hash-table 31) #f)))
1488 ;; We can't pass this as an argument to module-constructor,
1489 ;; because we need it to close over a pointer to the module
1491 (set-module-eval-closure! module (standard-eval-closure module))
1495 (define module-constructor (record-constructor module-type))
1496 (define module-obarray (record-accessor module-type 'obarray))
1497 (define set-module-obarray! (record-modifier module-type 'obarray))
1498 (define module-uses (record-accessor module-type 'uses))
1499 (define set-module-uses! (record-modifier module-type 'uses))
1500 (define module-binder (record-accessor module-type 'binder))
1501 (define set-module-binder! (record-modifier module-type 'binder))
1503 ;; NOTE: This binding is used in libguile/modules.c.
1504 (define module-eval-closure (record-accessor module-type 'eval-closure))
1506 ;; (define module-transformer (record-accessor module-type 'transformer))
1507 (define set-module-transformer! (record-modifier module-type 'transformer))
1508 (define module-version (record-accessor module-type 'version))
1509 (define set-module-version! (record-modifier module-type 'version))
1510 ;; (define module-name (record-accessor module-type 'name)) wait until mods are booted
1511 (define set-module-name! (record-modifier module-type 'name))
1512 (define module-kind (record-accessor module-type 'kind))
1513 (define set-module-kind! (record-modifier module-type 'kind))
1514 (define module-duplicates-handlers
1515 (record-accessor module-type 'duplicates-handlers))
1516 (define set-module-duplicates-handlers!
1517 (record-modifier module-type 'duplicates-handlers))
1518 (define module-observers (record-accessor module-type 'observers))
1519 (define set-module-observers! (record-modifier module-type 'observers))
1520 (define module-weak-observers (record-accessor module-type 'weak-observers))
1521 (define module? (record-predicate module-type))
1523 (define module-import-obarray (record-accessor module-type 'import-obarray))
1525 (define set-module-eval-closure!
1526 (let ((setter (record-modifier module-type 'eval-closure)))
1527 (lambda (module closure)
1528 (setter module closure)
1529 ;; Make it possible to lookup the module from the environment.
1530 ;; This implementation is correct since an eval closure can belong
1531 ;; to maximally one module.
1533 ;; XXX: The following line introduces a circular reference that
1534 ;; precludes garbage collection of modules with the current weak hash
1535 ;; table semantics (see
1536 ;; http://lists.gnu.org/archive/html/guile-devel/2009-01/msg00102.html and
1537 ;; http://thread.gmane.org/gmane.comp.programming.garbage-collection.boehmgc/2465
1538 ;; for details). Since it doesn't appear to be used (only in
1539 ;; `scm_lookup_closure_module ()', which has 1 caller), we just comment
1542 ;(set-procedure-property! closure 'module module)
1547 ;;; {Observer protocol}
1550 (define (module-observe module proc)
1551 (set-module-observers! module (cons proc (module-observers module)))
1554 (define (module-observe-weak module observer-id . proc)
1555 ;; Register PROC as an observer of MODULE under name OBSERVER-ID (which can
1556 ;; be any Scheme object). PROC is invoked and passed MODULE any time
1557 ;; MODULE is modified. PROC gets unregistered when OBSERVER-ID gets GC'd
1558 ;; (thus, it is never unregistered if OBSERVER-ID is an immediate value,
1561 ;; The two-argument version is kept for backward compatibility: when called
1562 ;; with two arguments, the observer gets unregistered when closure PROC
1563 ;; gets GC'd (making it impossible to use an anonymous lambda for PROC).
1565 (let ((proc (if (null? proc) observer-id (car proc))))
1566 (hashq-set! (module-weak-observers module) observer-id proc)))
1568 (define (module-unobserve token)
1569 (let ((module (car token))
1572 (hash-remove! (module-weak-observers module) id)
1573 (set-module-observers! module (delq1! id (module-observers module)))))
1576 (define module-defer-observers #f)
1577 (define module-defer-observers-mutex (make-mutex 'recursive))
1578 (define module-defer-observers-table (make-hash-table))
1580 (define (module-modified m)
1581 (if module-defer-observers
1582 (hash-set! module-defer-observers-table m #t)
1583 (module-call-observers m)))
1585 ;;; This function can be used to delay calls to observers so that they
1586 ;;; can be called once only in the face of massive updating of modules.
1588 (define (call-with-deferred-observers thunk)
1591 (lock-mutex module-defer-observers-mutex)
1592 (set! module-defer-observers #t))
1595 (set! module-defer-observers #f)
1596 (hash-for-each (lambda (m dummy)
1597 (module-call-observers m))
1598 module-defer-observers-table)
1599 (hash-clear! module-defer-observers-table)
1600 (unlock-mutex module-defer-observers-mutex))))
1602 (define (module-call-observers m)
1603 (for-each (lambda (proc) (proc m)) (module-observers m))
1605 ;; We assume that weak observers don't (un)register themselves as they are
1606 ;; called since this would preclude proper iteration over the hash table
1608 (hash-for-each (lambda (id proc) (proc m)) (module-weak-observers m)))
1612 ;;; {Module Searching in General}
1614 ;;; We sometimes want to look for properties of a symbol
1615 ;;; just within the obarray of one module. If the property
1616 ;;; holds, then it is said to hold ``locally'' as in, ``The symbol
1617 ;;; DISPLAY is locally rebound in the module `safe-guile'.''
1620 ;;; Other times, we want to test for a symbol property in the obarray
1621 ;;; of M and, if it is not found there, try each of the modules in the
1622 ;;; uses list of M. This is the normal way of testing for some
1623 ;;; property, so we state these properties without qualification as
1624 ;;; in: ``The symbol 'fnord is interned in module M because it is
1625 ;;; interned locally in module M2 which is a member of the uses list
1629 ;; module-search fn m
1631 ;; return the first non-#f result of FN applied to M and then to
1632 ;; the modules in the uses of m, and so on recursively. If all applications
1633 ;; return #f, then so does this function.
1635 (define (module-search fn m v)
1638 (or (module-search fn (car pos) v)
1641 (loop (module-uses m))))
1644 ;;; {Is a symbol bound in a module?}
1646 ;;; Symbol S in Module M is bound if S is interned in M and if the binding
1647 ;;; of S in M has been set to some well-defined value.
1650 ;; module-locally-bound? module symbol
1652 ;; Is a symbol bound (interned and defined) locally in a given module?
1654 (define (module-locally-bound? m v)
1655 (let ((var (module-local-variable m v)))
1657 (variable-bound? var))))
1659 ;; module-bound? module symbol
1661 ;; Is a symbol bound (interned and defined) anywhere in a given module
1664 (define (module-bound? m v)
1665 (let ((var (module-variable m v)))
1667 (variable-bound? var))))
1669 ;;; {Is a symbol interned in a module?}
1671 ;;; Symbol S in Module M is interned if S occurs in
1672 ;;; of S in M has been set to some well-defined value.
1674 ;;; It is possible to intern a symbol in a module without providing
1675 ;;; an initial binding for the corresponding variable. This is done
1677 ;;; (module-add! module symbol (make-undefined-variable))
1679 ;;; In that case, the symbol is interned in the module, but not
1680 ;;; bound there. The unbound symbol shadows any binding for that
1681 ;;; symbol that might otherwise be inherited from a member of the uses list.
1684 (define (module-obarray-get-handle ob key)
1685 ((if (symbol? key) hashq-get-handle hash-get-handle) ob key))
1687 (define (module-obarray-ref ob key)
1688 ((if (symbol? key) hashq-ref hash-ref) ob key))
1690 (define (module-obarray-set! ob key val)
1691 ((if (symbol? key) hashq-set! hash-set!) ob key val))
1693 (define (module-obarray-remove! ob key)
1694 ((if (symbol? key) hashq-remove! hash-remove!) ob key))
1696 ;; module-symbol-locally-interned? module symbol
1698 ;; is a symbol interned (not neccessarily defined) locally in a given module
1699 ;; or its uses? Interned symbols shadow inherited bindings even if
1700 ;; they are not themselves bound to a defined value.
1702 (define (module-symbol-locally-interned? m v)
1703 (not (not (module-obarray-get-handle (module-obarray m) v))))
1705 ;; module-symbol-interned? module symbol
1707 ;; is a symbol interned (not neccessarily defined) anywhere in a given module
1708 ;; or its uses? Interned symbols shadow inherited bindings even if
1709 ;; they are not themselves bound to a defined value.
1711 (define (module-symbol-interned? m v)
1712 (module-search module-symbol-locally-interned? m v))
1715 ;;; {Mapping modules x symbols --> variables}
1718 ;; module-local-variable module symbol
1719 ;; return the local variable associated with a MODULE and SYMBOL.
1721 ;;; This function is very important. It is the only function that can
1722 ;;; return a variable from a module other than the mutators that store
1723 ;;; new variables in modules. Therefore, this function is the location
1724 ;;; of the "lazy binder" hack.
1726 ;;; If symbol is defined in MODULE, and if the definition binds symbol
1727 ;;; to a variable, return that variable object.
1729 ;;; If the symbols is not found at first, but the module has a lazy binder,
1730 ;;; then try the binder.
1732 ;;; If the symbol is not found at all, return #f.
1734 ;;; (This is now written in C, see `modules.c'.)
1737 ;;; {Mapping modules x symbols --> bindings}
1739 ;;; These are similar to the mapping to variables, except that the
1740 ;;; variable is dereferenced.
1743 ;; module-symbol-binding module symbol opt-value
1745 ;; return the binding of a variable specified by name within
1746 ;; a given module, signalling an error if the variable is unbound.
1747 ;; If the OPT-VALUE is passed, then instead of signalling an error,
1748 ;; return OPT-VALUE.
1750 (define (module-symbol-local-binding m v . opt-val)
1751 (let ((var (module-local-variable m v)))
1752 (if (and var (variable-bound? var))
1754 (if (not (null? opt-val))
1756 (error "Locally unbound variable." v)))))
1758 ;; module-symbol-binding module symbol opt-value
1760 ;; return the binding of a variable specified by name within
1761 ;; a given module, signalling an error if the variable is unbound.
1762 ;; If the OPT-VALUE is passed, then instead of signalling an error,
1763 ;; return OPT-VALUE.
1765 (define (module-symbol-binding m v . opt-val)
1766 (let ((var (module-variable m v)))
1767 (if (and var (variable-bound? var))
1769 (if (not (null? opt-val))
1771 (error "Unbound variable." v)))))
1776 ;;; {Adding Variables to Modules}
1779 ;; module-make-local-var! module symbol
1781 ;; ensure a variable for V in the local namespace of M.
1782 ;; If no variable was already there, then create a new and uninitialzied
1785 ;; This function is used in modules.c.
1787 (define (module-make-local-var! m v)
1788 (or (let ((b (module-obarray-ref (module-obarray m) v)))
1791 ;; Mark as modified since this function is called when
1792 ;; the standard eval closure defines a binding
1796 ;; Create a new local variable.
1797 (let ((local-var (make-undefined-variable)))
1798 (module-add! m v local-var)
1801 ;; module-ensure-local-variable! module symbol
1803 ;; Ensure that there is a local variable in MODULE for SYMBOL. If
1804 ;; there is no binding for SYMBOL, create a new uninitialized
1805 ;; variable. Return the local variable.
1807 (define (module-ensure-local-variable! module symbol)
1808 (or (module-local-variable module symbol)
1809 (let ((var (make-undefined-variable)))
1810 (module-add! module symbol var)
1813 ;; module-add! module symbol var
1815 ;; ensure a particular variable for V in the local namespace of M.
1817 (define (module-add! m v var)
1818 (if (not (variable? var))
1819 (error "Bad variable to module-add!" var))
1820 (module-obarray-set! (module-obarray m) v var)
1821 (module-modified m))
1825 ;; make sure that a symbol is undefined in the local namespace of M.
1827 (define (module-remove! m v)
1828 (module-obarray-remove! (module-obarray m) v)
1829 (module-modified m))
1831 (define (module-clear! m)
1832 (hash-clear! (module-obarray m))
1833 (module-modified m))
1835 ;; MODULE-FOR-EACH -- exported
1837 ;; Call PROC on each symbol in MODULE, with arguments of (SYMBOL VARIABLE).
1839 (define (module-for-each proc module)
1840 (hash-for-each proc (module-obarray module)))
1842 (define (module-map proc module)
1843 (hash-map->list proc (module-obarray module)))
1847 ;;; {Low Level Bootstrapping}
1852 ;; A root module uses the pre-modules-obarray as its obarray. This
1853 ;; special obarray accumulates all bindings that have been established
1854 ;; before the module system is fully booted.
1856 ;; (The obarray continues to be used by code that has been closed over
1857 ;; before the module system has been booted.)
1859 (define (make-root-module)
1860 (let ((m (make-module 0)))
1861 (set-module-obarray! m (%get-pre-modules-obarray))
1866 ;; The root interface is a module that uses the same obarray as the
1867 ;; root module. It does not allow new definitions, tho.
1869 (define (make-scm-module)
1870 (let ((m (make-module 0)))
1871 (set-module-obarray! m (%get-pre-modules-obarray))
1872 (set-module-eval-closure! m (standard-interface-eval-closure m))
1878 ;;; {Module-based Loading}
1881 (define (save-module-excursion thunk)
1882 (let ((inner-module (current-module))
1884 (dynamic-wind (lambda ()
1885 (set! outer-module (current-module))
1886 (set-current-module inner-module)
1887 (set! inner-module #f))
1890 (set! inner-module (current-module))
1891 (set-current-module outer-module)
1892 (set! outer-module #f)))))
1894 (define basic-load load)
1896 (define (load-module filename . reader)
1897 (save-module-excursion
1899 (let ((oldname (and (current-load-port)
1900 (port-filename (current-load-port)))))
1903 (> (string-length filename) 0)
1904 (not (char=? (string-ref filename 0) #\/))
1905 (not (string=? (dirname oldname) ".")))
1906 (string-append (dirname oldname) "/" filename)
1913 ;;; {MODULE-REF -- exported}
1916 ;; Returns the value of a variable called NAME in MODULE or any of its
1917 ;; used modules. If there is no such variable, then if the optional third
1918 ;; argument DEFAULT is present, it is returned; otherwise an error is signaled.
1920 (define (module-ref module name . rest)
1921 (let ((variable (module-variable module name)))
1922 (if (and variable (variable-bound? variable))
1923 (variable-ref variable)
1925 (error "No variable named" name 'in module)
1926 (car rest) ; default value
1929 ;; MODULE-SET! -- exported
1931 ;; Sets the variable called NAME in MODULE (or in a module that MODULE uses)
1932 ;; to VALUE; if there is no such variable, an error is signaled.
1934 (define (module-set! module name value)
1935 (let ((variable (module-variable module name)))
1937 (variable-set! variable value)
1938 (error "No variable named" name 'in module))))
1940 ;; MODULE-DEFINE! -- exported
1942 ;; Sets the variable called NAME in MODULE to VALUE; if there is no such
1943 ;; variable, it is added first.
1945 (define (module-define! module name value)
1946 (let ((variable (module-local-variable module name)))
1949 (variable-set! variable value)
1950 (module-modified module))
1951 (let ((variable (make-variable value)))
1952 (module-add! module name variable)))))
1954 ;; MODULE-DEFINED? -- exported
1956 ;; Return #t iff NAME is defined in MODULE (or in a module that MODULE
1959 (define (module-defined? module name)
1960 (let ((variable (module-variable module name)))
1961 (and variable (variable-bound? variable))))
1963 ;; MODULE-USE! module interface
1965 ;; Add INTERFACE to the list of interfaces used by MODULE.
1967 (define (module-use! module interface)
1968 (if (not (or (eq? module interface)
1969 (memq interface (module-uses module))))
1971 ;; Newly used modules must be appended rather than consed, so that
1972 ;; `module-variable' traverses the use list starting from the first
1974 (set-module-uses! module
1975 (append (filter (lambda (m)
1977 (equal? (module-name m)
1978 (module-name interface))))
1979 (module-uses module))
1981 (hash-clear! (module-import-obarray module))
1982 (module-modified module))))
1984 ;; MODULE-USE-INTERFACES! module interfaces
1986 ;; Same as MODULE-USE! but add multiple interfaces and check for duplicates
1988 (define (module-use-interfaces! module interfaces)
1989 (set-module-uses! module
1990 (append (module-uses module) interfaces))
1991 (hash-clear! (module-import-obarray module))
1992 (module-modified module))
1996 ;;; {Recursive Namespaces}
1998 ;;; A hierarchical namespace emerges if we consider some module to be
1999 ;;; root, and variables bound to modules as nested namespaces.
2001 ;;; The routines in this file manage variable names in hierarchical namespace.
2002 ;;; Each variable name is a list of elements, looked up in successively nested
2005 ;;; (nested-ref some-root-module '(foo bar baz))
2006 ;;; => <value of a variable named baz in the module bound to bar in
2007 ;;; the module bound to foo in some-root-module>
2012 ;;; ;; a-root is a module
2013 ;;; ;; name is a list of symbols
2015 ;;; nested-ref a-root name
2016 ;;; nested-set! a-root name val
2017 ;;; nested-define! a-root name val
2018 ;;; nested-remove! a-root name
2021 ;;; (current-module) is a natural choice for a-root so for convenience there are
2024 ;;; local-ref name == nested-ref (current-module) name
2025 ;;; local-set! name val == nested-set! (current-module) name val
2026 ;;; local-define! name val == nested-define! (current-module) name val
2027 ;;; local-remove! name == nested-remove! (current-module) name
2031 (define (nested-ref root names)
2032 (let loop ((cur root)
2036 ((not (module? cur)) #f)
2037 (else (loop (module-ref cur (car elts) #f) (cdr elts))))))
2039 (define (nested-set! root names val)
2040 (let loop ((cur root)
2042 (if (null? (cdr elts))
2043 (module-set! cur (car elts) val)
2044 (loop (module-ref cur (car elts)) (cdr elts)))))
2046 (define (nested-define! root names val)
2047 (let loop ((cur root)
2049 (if (null? (cdr elts))
2050 (module-define! cur (car elts) val)
2051 (loop (module-ref cur (car elts)) (cdr elts)))))
2053 (define (nested-remove! root names)
2054 (let loop ((cur root)
2056 (if (null? (cdr elts))
2057 (module-remove! cur (car elts))
2058 (loop (module-ref cur (car elts)) (cdr elts)))))
2060 (define (local-ref names) (nested-ref (current-module) names))
2061 (define (local-set! names val) (nested-set! (current-module) names val))
2062 (define (local-define names val) (nested-define! (current-module) names val))
2063 (define (local-remove names) (nested-remove! (current-module) names))
2068 ;;; {The (%app) module}
2070 ;;; The root of conventionally named objects not directly in the top level.
2073 ;;; (%app modules guile)
2075 ;;; The directory of all modules and the standard root module.
2078 ;; module-public-interface is defined in C.
2079 (define (set-module-public-interface! m i)
2080 (module-define! m '%module-public-interface i))
2081 (define (set-system-module! m s)
2082 (set-procedure-property! (module-eval-closure m) 'system-module s))
2083 (define the-root-module (make-root-module))
2084 (define the-scm-module (make-scm-module))
2085 (set-module-public-interface! the-root-module the-scm-module)
2086 (set-module-name! the-root-module '(guile))
2087 (set-module-name! the-scm-module '(guile))
2088 (set-module-kind! the-scm-module 'interface)
2089 (set-system-module! the-root-module #t)
2090 (set-system-module! the-scm-module #t)
2092 ;; NOTE: This binding is used in libguile/modules.c.
2094 (define (make-modules-in module name)
2098 (let* ((var (module-local-variable module (car name)))
2099 (val (and var (variable-bound? var) (variable-ref var))))
2102 (let ((m (make-module 31)))
2103 (set-module-kind! m 'directory)
2104 (set-module-name! m (append (module-name module)
2106 (module-define! module (car name) m)
2110 (define (beautify-user-module! module)
2111 (let ((interface (module-public-interface module)))
2112 (if (or (not interface)
2113 (eq? interface module))
2114 (let ((interface (make-module 31)))
2115 (set-module-name! interface (module-name module))
2116 (set-module-version! interface (module-version module))
2117 (set-module-kind! interface 'interface)
2118 (set-module-public-interface! module interface))))
2119 (if (and (not (memq the-scm-module (module-uses module)))
2120 (not (eq? module the-root-module)))
2121 ;; Import the default set of bindings (from the SCM module) in MODULE.
2122 (module-use! module the-scm-module)))
2124 (define (version-matches? version-ref target)
2125 (define (any pred lst)
2126 (and (not (null? lst)) (or (pred (car lst)) (any pred (cdr lst)))))
2127 (define (every pred lst)
2128 (or (null? lst) (and (pred (car lst)) (every pred (cdr lst)))))
2129 (define (sub-versions-match? v-refs t)
2130 (define (sub-version-matches? v-ref t)
2131 (define (curried-sub-version-matches? v)
2132 (sub-version-matches? v t))
2133 (cond ((number? v-ref) (eqv? v-ref t))
2135 (let ((cv (car v-ref)))
2136 (cond ((eq? cv '>=) (>= t (cadr v-ref)))
2137 ((eq? cv '<=) (<= t (cadr v-ref)))
2139 (every curried-sub-version-matches? (cdr v-ref)))
2141 (any curried-sub-version-matches? (cdr v-ref)))
2142 ((eq? cv 'not) (not (sub-version-matches? (cadr v-ref) t)))
2143 (else (error "Incompatible sub-version reference" cv)))))
2144 (else (error "Incompatible sub-version reference" v-ref))))
2146 (and (not (null? t))
2147 (sub-version-matches? (car v-refs) (car t))
2148 (sub-versions-match? (cdr v-refs) (cdr t)))))
2149 (define (curried-version-matches? v)
2150 (version-matches? v target))
2151 (or (null? version-ref)
2152 (let ((cv (car version-ref)))
2153 (cond ((eq? cv 'and) (every curried-version-matches? (cdr version-ref)))
2154 ((eq? cv 'or) (any curried-version-matches? (cdr version-ref)))
2155 ((eq? cv 'not) (not (version-matches? (cadr version-ref) target)))
2156 (else (sub-versions-match? version-ref target))))))
2158 (define (find-versioned-module dir-hint name version-ref roots)
2159 (define (subdir-pair-less pair1 pair2)
2160 (define (numlist-less lst1 lst2)
2162 (and (not (null? lst1))
2163 (cond ((> (car lst1) (car lst2)) #t)
2164 ((< (car lst1) (car lst2)) #f)
2165 (else (numlist-less (cdr lst1) (cdr lst2)))))))
2166 (numlist-less (car pair1) (car pair2)))
2167 (define (match-version-and-file pair)
2168 (and (version-matches? version-ref (car pair))
2170 (filter (lambda (file)
2171 (let ((s (false-if-exception (stat file))))
2172 (and s (eq? (stat:type s) 'regular))))
2174 (string-append (cdr pair) "/" name ext))
2175 %load-extensions))))
2176 (and (not (null? filenames))
2177 (cons (car pair) (car filenames))))))
2179 (define (match-version-recursive root-pairs leaf-pairs)
2180 (define (filter-subdirs root-pairs ret)
2181 (define (filter-subdir root-pair dstrm subdir-pairs)
2182 (let ((entry (readdir dstrm)))
2183 (if (eof-object? entry)
2185 (let* ((subdir (string-append (cdr root-pair) "/" entry))
2186 (num (string->number entry))
2187 (num (and num (append (car root-pair) (list num)))))
2188 (if (and num (eq? (stat:type (stat subdir)) 'directory))
2190 root-pair dstrm (cons (cons num subdir) subdir-pairs))
2191 (filter-subdir root-pair dstrm subdir-pairs))))))
2193 (or (and (null? root-pairs) ret)
2194 (let* ((rp (car root-pairs))
2195 (dstrm (false-if-exception (opendir (cdr rp)))))
2197 (let ((subdir-pairs (filter-subdir rp dstrm '())))
2199 (filter-subdirs (cdr root-pairs)
2200 (or (and (null? subdir-pairs) ret)
2201 (append ret subdir-pairs))))
2202 (filter-subdirs (cdr root-pairs) ret)))))
2204 (or (and (null? root-pairs) leaf-pairs)
2205 (let ((matching-subdir-pairs (filter-subdirs root-pairs '())))
2206 (match-version-recursive
2207 matching-subdir-pairs
2208 (append leaf-pairs (filter pair? (map match-version-and-file
2209 matching-subdir-pairs)))))))
2210 (define (make-root-pair root)
2211 (cons '() (string-append root "/" dir-hint)))
2213 (let* ((root-pairs (map make-root-pair roots))
2214 (matches (if (null? version-ref)
2215 (filter pair? (map match-version-and-file root-pairs))
2217 (matches (append matches (match-version-recursive root-pairs '()))))
2218 (and (null? matches) (error "No matching modules found."))
2219 (cdar (sort matches subdir-pair-less))))
2221 (define (make-fresh-user-module)
2222 (let ((m (make-module)))
2223 (beautify-user-module! m)
2226 ;; NOTE: This binding is used in libguile/modules.c.
2228 (define resolve-module
2229 (let ((the-root-module the-root-module))
2230 (lambda (name . args)
2231 (if (equal? name '(guile))
2233 (let ((full-name (append '(%app modules) name)))
2234 (let* ((already (nested-ref the-root-module full-name))
2235 (numargs (length args))
2236 (autoload (or (= numargs 0) (car args)))
2237 (version (and (> numargs 1) (cadr args))))
2239 ((and already (module? already)
2240 (or (not autoload) (module-public-interface already)))
2241 ;; A hit, a palpable hit.
2243 (not (version-matches? version (module-version already))))
2244 (error "incompatible module version already loaded" name))
2247 ;; Try to autoload the module, and recurse.
2248 (try-load-module name version)
2249 (resolve-module name #f))
2251 ;; A module is not bound (but maybe something else is),
2252 ;; we're not autoloading -- here's the weird semantics,
2253 ;; we create an empty module.
2254 (make-modules-in the-root-module full-name)))))))))
2256 ;; Cheat. These bindings are needed by modules.c, but we don't want
2257 ;; to move their real definition here because that would be unnatural.
2259 (define try-module-autoload #f)
2260 (define process-define-module #f)
2261 (define process-use-modules #f)
2262 (define module-export! #f)
2263 (define default-duplicate-binding-procedures #f)
2265 (define %app (make-module 31))
2266 (set-module-name! %app '(%app))
2267 (define app %app) ;; for backwards compatability
2269 (let ((m (make-module 31)))
2270 (set-module-name! m '())
2271 (local-define '(%app modules) m))
2272 (local-define '(%app modules guile) the-root-module)
2274 ;; This boots the module system. All bindings needed by modules.c
2275 ;; must have been defined by now.
2277 (set-current-module the-root-module)
2278 ;; definition deferred for syncase's benefit.
2280 (let ((accessor (record-accessor module-type 'name)))
2283 (let ((name (list (gensym))))
2284 ;; Name MOD and bind it in THE-ROOT-MODULE so that it's visible
2285 ;; to `resolve-module'. This is important as `psyntax' stores
2286 ;; module names and relies on being able to `resolve-module'
2288 (set-module-name! mod name)
2289 (nested-define! the-root-module `(%app modules ,@name) mod)
2292 ;; (define-special-value '(%app modules new-ws) (lambda () (make-scm-module)))
2294 (define (try-load-module name version)
2295 (try-module-autoload name version))
2297 (define (purify-module! module)
2298 "Removes bindings in MODULE which are inherited from the (guile) module."
2299 (let ((use-list (module-uses module)))
2300 (if (and (pair? use-list)
2301 (eq? (car (last-pair use-list)) the-scm-module))
2302 (set-module-uses! module (reverse (cdr (reverse use-list)))))))
2304 ;; Return a module that is an interface to the module designated by
2307 ;; `resolve-interface' takes four keyword arguments:
2309 ;; #:select SELECTION
2311 ;; SELECTION is a list of binding-specs to be imported; A binding-spec
2312 ;; is either a symbol or a pair of symbols (ORIG . SEEN), where ORIG
2313 ;; is the name in the used module and SEEN is the name in the using
2314 ;; module. Note that SEEN is also passed through RENAMER, below. The
2315 ;; default is to select all bindings. If you specify no selection but
2316 ;; a renamer, only the bindings that already exist in the used module
2317 ;; are made available in the interface. Bindings that are added later
2318 ;; are not picked up.
2322 ;; BINDINGS is a list of bindings which should not be imported.
2326 ;; PREFIX is a symbol that will be appended to each exported name.
2327 ;; The default is to not perform any renaming.
2329 ;; #:renamer RENAMER
2331 ;; RENAMER is a procedure that takes a symbol and returns its new
2332 ;; name. The default is not perform any renaming.
2334 ;; Signal "no code for module" error if module name is not resolvable
2335 ;; or its public interface is not available. Signal "no binding"
2336 ;; error if selected binding does not exist in the used module.
2338 (define (resolve-interface name . args)
2340 (define (get-keyword-arg args kw def)
2341 (cond ((memq kw args)
2343 (if (null? (cdr kw-arg))
2344 (error "keyword without value: " kw))
2349 (let* ((select (get-keyword-arg args #:select #f))
2350 (hide (get-keyword-arg args #:hide '()))
2351 (renamer (or (get-keyword-arg args #:renamer #f)
2352 (let ((prefix (get-keyword-arg args #:prefix #f)))
2353 (and prefix (symbol-prefix-proc prefix)))
2355 (version (get-keyword-arg args #:version #f))
2356 (module (resolve-module name #t version))
2357 (public-i (and module (module-public-interface module))))
2358 (and (or (not module) (not public-i))
2359 (error "no code for module" name))
2360 (if (and (not select) (null? hide) (eq? renamer identity))
2362 (let ((selection (or select (module-map (lambda (sym var) sym)
2364 (custom-i (make-module 31)))
2365 (set-module-kind! custom-i 'custom-interface)
2366 (set-module-name! custom-i name)
2367 ;; XXX - should use a lazy binder so that changes to the
2368 ;; used module are picked up automatically.
2369 (for-each (lambda (bspec)
2370 (let* ((direct? (symbol? bspec))
2371 (orig (if direct? bspec (car bspec)))
2372 (seen (if direct? bspec (cdr bspec)))
2373 (var (or (module-local-variable public-i orig)
2374 (module-local-variable module orig)
2376 ;; fixme: format manually for now
2378 #f "no binding `~A' in module ~A"
2380 (if (memq orig hide)
2381 (set! hide (delq! orig hide))
2382 (module-add! custom-i
2386 ;; Check that we are not hiding bindings which don't exist
2387 (for-each (lambda (binding)
2388 (if (not (module-local-variable public-i binding))
2391 #f "no binding `~A' to hide in module ~A"
2396 (define (symbol-prefix-proc prefix)
2398 (symbol-append prefix symbol)))
2400 ;; This function is called from "modules.c". If you change it, be
2401 ;; sure to update "modules.c" as well.
2403 (define (process-define-module args)
2404 (let* ((module-id (car args))
2405 (module (resolve-module module-id #f))
2407 (unrecognized (lambda (arg)
2408 (error "unrecognized define-module argument" arg))))
2409 (beautify-user-module! module)
2410 (let loop ((kws kws)
2411 (reversed-interfaces '())
2418 (call-with-deferred-observers
2420 (module-use-interfaces! module (reverse reversed-interfaces))
2421 (module-export! module exports)
2422 (module-replace! module replacements)
2423 (module-re-export! module re-exports)
2424 (if (not (null? autoloads))
2425 (apply module-autoload! module autoloads))))
2427 ((#:use-module #:use-syntax)
2428 (or (pair? (cdr kws))
2431 ((equal? (caadr kws) '(ice-9 syncase))
2432 (issue-deprecation-warning
2433 "(ice-9 syncase) is deprecated. Support for syntax-case is now in Guile core.")
2441 (let* ((interface-args (cadr kws))
2442 (interface (apply resolve-interface interface-args)))
2443 (and (eq? (car kws) #:use-syntax)
2444 (or (symbol? (caar interface-args))
2445 (error "invalid module name for use-syntax"
2446 (car interface-args)))
2447 (set-module-transformer!
2449 (module-ref interface
2450 (car (last-pair (car interface-args)))
2453 (cons interface reversed-interfaces)
2459 (or (and (pair? (cdr kws)) (pair? (cddr kws)))
2466 (let ((name (cadr kws))
2467 (bindings (caddr kws)))
2468 (cons* name bindings autoloads))))
2470 (set-system-module! module #t)
2471 (loop (cdr kws) reversed-interfaces exports re-exports
2472 replacements autoloads))
2474 (purify-module! module)
2475 (loop (cdr kws) reversed-interfaces exports re-exports
2476 replacements autoloads))
2478 (or (pair? (cdr kws))
2480 (let ((version (cadr kws)))
2481 (set-module-version! module version)
2482 (set-module-version! (module-public-interface module) version))
2483 (loop (cddr kws) reversed-interfaces exports re-exports
2484 replacements autoloads))
2486 (if (not (pair? (cdr kws)))
2488 (set-module-duplicates-handlers!
2490 (lookup-duplicates-handlers (cadr kws)))
2491 (loop (cddr kws) reversed-interfaces exports re-exports
2492 replacements autoloads))
2493 ((#:export #:export-syntax)
2494 (or (pair? (cdr kws))
2498 (append (cadr kws) exports)
2502 ((#:re-export #:re-export-syntax)
2503 (or (pair? (cdr kws))
2508 (append (cadr kws) re-exports)
2511 ((#:replace #:replace-syntax)
2512 (or (pair? (cdr kws))
2518 (append (cadr kws) replacements)
2521 (unrecognized kws)))))
2522 (run-hook module-defined-hook module)
2525 ;; `module-defined-hook' is a hook that is run whenever a new module
2526 ;; is defined. Its members are called with one argument, the new
2528 (define module-defined-hook (make-hook 1))
2535 (define (make-autoload-interface module name bindings)
2536 (let ((b (lambda (a sym definep)
2537 (and (memq sym bindings)
2538 (let ((i (module-public-interface (resolve-module name))))
2540 (error "missing interface for module" name))
2541 (let ((autoload (memq a (module-uses module))))
2542 ;; Replace autoload-interface with actual interface if
2543 ;; that has not happened yet.
2544 (if (pair? autoload)
2545 (set-car! autoload i)))
2546 (module-local-variable i sym))))))
2547 (module-constructor (make-hash-table 0) '() b #f #f name 'autoload #f
2548 (make-hash-table 0) '() (make-weak-value-hash-table 31) #f)))
2550 (define (module-autoload! module . args)
2551 "Have @var{module} automatically load the module named @var{name} when one
2552 of the symbols listed in @var{bindings} is looked up. @var{args} should be a
2553 list of module-name/binding-list pairs, e.g., as in @code{(module-autoload!
2554 module '(ice-9 q) '(make-q q-length))}."
2555 (let loop ((args args))
2559 (error "invalid name+binding autoload list" args))
2561 (let ((name (car args))
2562 (bindings (cadr args)))
2563 (module-use! module (make-autoload-interface module
2565 (loop (cddr args)))))))
2570 ;;; {Autoloading modules}
2573 (define autoloads-in-progress '())
2575 ;; This function is called from "modules.c". If you change it, be
2576 ;; sure to update "modules.c" as well.
2578 (define (try-module-autoload module-name . args)
2579 (let* ((reverse-name (reverse module-name))
2580 (name (symbol->string (car reverse-name)))
2581 (version (and (not (null? args)) (car args)))
2582 (dir-hint-module-name (reverse (cdr reverse-name)))
2583 (dir-hint (apply string-append
2585 (string-append (symbol->string elt) "/"))
2586 dir-hint-module-name))))
2587 (resolve-module dir-hint-module-name #f)
2588 (and (not (autoload-done-or-in-progress? dir-hint name))
2591 (lambda () (autoload-in-progress! dir-hint name))
2593 (with-fluids ((current-reader #f))
2594 (save-module-excursion
2597 (load (find-versioned-module
2598 dir-hint name version %load-path))
2599 (primitive-load-path (in-vicinity dir-hint name) #f))
2601 (lambda () (set-autoloaded! dir-hint name didit)))
2606 ;;; {Dynamic linking of modules}
2609 (define autoloads-done '((guile . guile)))
2611 (define (autoload-done-or-in-progress? p m)
2612 (let ((n (cons p m)))
2613 (->bool (or (member n autoloads-done)
2614 (member n autoloads-in-progress)))))
2616 (define (autoload-done! p m)
2617 (let ((n (cons p m)))
2618 (set! autoloads-in-progress
2619 (delete! n autoloads-in-progress))
2620 (or (member n autoloads-done)
2621 (set! autoloads-done (cons n autoloads-done)))))
2623 (define (autoload-in-progress! p m)
2624 (let ((n (cons p m)))
2625 (set! autoloads-done
2626 (delete! n autoloads-done))
2627 (set! autoloads-in-progress (cons n autoloads-in-progress))))
2629 (define (set-autoloaded! p m done?)
2631 (autoload-done! p m)
2632 (let ((n (cons p m)))
2633 (set! autoloads-done (delete! n autoloads-done))
2634 (set! autoloads-in-progress (delete! n autoloads-in-progress)))))
2638 ;;; {Run-time options}
2641 (defmacro define-option-interface (option-group)
2642 (let* ((option-name 'car)
2643 (option-value 'cadr)
2644 (option-documentation 'caddr)
2646 ;; Below follow the macros defining the run-time option interfaces.
2648 (make-options (lambda (interface)
2650 (cond ((null? args) (,interface))
2652 (,interface (car args)) (,interface))
2655 (display (,option-name option))
2656 (if (< (string-length
2657 (symbol->string (,option-name option)))
2661 (display (,option-value option))
2663 (display (,option-documentation option))
2665 (,interface #t)))))))
2667 (make-enable (lambda (interface)
2669 (,interface (append flags (,interface)))
2672 (make-disable (lambda (interface)
2674 (let ((options (,interface)))
2675 (for-each (lambda (flag)
2676 (set! options (delq! flag options)))
2678 (,interface options)
2680 (let* ((interface (car option-group))
2681 (options/enable/disable (cadr option-group)))
2683 (define ,(car options/enable/disable)
2684 ,(make-options interface))
2685 (define ,(cadr options/enable/disable)
2686 ,(make-enable interface))
2687 (define ,(caddr options/enable/disable)
2688 ,(make-disable interface))
2689 (defmacro ,(caaddr option-group) (opt val)
2690 `(,',(car options/enable/disable)
2691 (append (,',(car options/enable/disable))
2692 (list ',opt ,val))))))))
2694 (define-option-interface
2695 (eval-options-interface
2696 (eval-options eval-enable eval-disable)
2699 (define-option-interface
2700 (debug-options-interface
2701 (debug-options debug-enable debug-disable)
2704 (define-option-interface
2705 (evaluator-traps-interface
2706 (traps trap-enable trap-disable)
2709 (define-option-interface
2710 (read-options-interface
2711 (read-options read-enable read-disable)
2714 (define-option-interface
2715 (print-options-interface
2716 (print-options print-enable print-disable)
2724 (define (repl read evaler print)
2725 (let loop ((source (read (current-input-port))))
2726 (print (evaler source))
2727 (loop (read (current-input-port)))))
2729 ;; A provisional repl that acts like the SCM repl:
2731 (define scm-repl-silent #f)
2732 (define (assert-repl-silence v) (set! scm-repl-silent v))
2734 (define *unspecified* (if #f #f))
2735 (define (unspecified? v) (eq? v *unspecified*))
2737 (define scm-repl-print-unspecified #f)
2738 (define (assert-repl-print-unspecified v) (set! scm-repl-print-unspecified v))
2740 (define scm-repl-verbose #f)
2741 (define (assert-repl-verbosity v) (set! scm-repl-verbose v))
2743 (define scm-repl-prompt "guile> ")
2745 (define (set-repl-prompt! v) (set! scm-repl-prompt v))
2747 (define (default-pre-unwind-handler key . args)
2748 ;; Narrow by two more frames: this one, and the throw handler.
2750 (apply throw key args))
2753 (define (pre-unwind-handler-dispatch key . args)
2754 (apply default-pre-unwind-handler key args)))
2756 (define abort-hook (make-hook))
2758 ;; these definitions are used if running a script.
2759 ;; otherwise redefined in error-catching-loop.
2760 (define (set-batch-mode?! arg) #t)
2761 (define (batch-mode?) #t)
2763 (define (error-catching-loop thunk)
2766 (define (loop first)
2771 (call-with-unblocked-asyncs
2777 ;; This line is needed because mark
2778 ;; doesn't do closures quite right.
2779 ;; Unreferenced locals should be
2782 (let loop ((v (thunk)))
2786 (lambda (key . args)
2793 (apply throw 'switch-repl args))
2796 ;; This is one of the closures that require
2797 ;; (set! first #f) above
2800 (run-hook abort-hook)
2801 (force-output (current-output-port))
2802 (display "ABORT: " (current-error-port))
2803 (write args (current-error-port))
2804 (newline (current-error-port))
2808 (not has-shown-debugger-hint?)
2809 (not (memq 'backtrace
2810 (debug-options-interface)))
2811 (stack? (fluid-ref the-last-stack)))
2813 (newline (current-error-port))
2815 "Type \"(backtrace)\" to get more information or \"(debug)\" to enter the debugger.\n"
2816 (current-error-port))
2817 (set! has-shown-debugger-hint? #t)))
2818 (force-output (current-error-port)))
2820 (primitive-exit 1)))
2821 (set! stack-saved? #f)))
2824 ;; This is the other cons-leak closure...
2826 (cond ((= (length args) 4)
2827 (apply handle-system-error key args))
2829 (apply bad-throw key args)))))))
2831 default-pre-unwind-handler)))
2833 (if next (loop next) status)))
2834 (set! set-batch-mode?! (lambda (arg)
2836 (set! interactive #f)
2839 (error "sorry, not implemented")))))
2840 (set! batch-mode? (lambda () (not interactive)))
2841 (call-with-blocked-asyncs
2842 (lambda () (loop (lambda () #t))))))
2844 ;;(define the-last-stack (make-fluid)) Defined by scm_init_backtrace ()
2845 (define before-signal-stack (make-fluid))
2846 ;; FIXME: stack-saved? is broken in the presence of threads.
2847 (define stack-saved? #f)
2849 (define (save-stack . narrowing)
2850 (if (not stack-saved?)
2852 (let ((stacks (fluid-ref %stacks)))
2853 (fluid-set! the-last-stack
2854 ;; (make-stack obj inner outer inner outer ...)
2856 ;; In this case, cut away the make-stack frame, the
2857 ;; save-stack frame, and then narrow as specified by the
2858 ;; user, delimited by the nearest start-stack invocation,
2860 (apply make-stack #t
2862 (if (pair? stacks) (cdar stacks) 0)
2864 (set! stack-saved? #t))))
2866 (define before-error-hook (make-hook))
2867 (define after-error-hook (make-hook))
2868 (define before-backtrace-hook (make-hook))
2869 (define after-backtrace-hook (make-hook))
2871 (define has-shown-debugger-hint? #f)
2873 (define (handle-system-error key . args)
2874 (let ((cep (current-error-port)))
2875 (cond ((not (stack? (fluid-ref the-last-stack))))
2876 ((memq 'backtrace (debug-options-interface))
2877 (let ((highlights (if (or (eq? key 'wrong-type-arg)
2878 (eq? key 'out-of-range))
2881 (run-hook before-backtrace-hook)
2883 (display "Backtrace:\n")
2884 (display-backtrace (fluid-ref the-last-stack) cep
2887 (run-hook after-backtrace-hook))))
2888 (run-hook before-error-hook)
2889 (apply display-error (fluid-ref the-last-stack) cep args)
2890 (run-hook after-error-hook)
2892 (throw 'abort key)))
2894 (define (quit . args)
2895 (apply throw 'quit args))
2899 ;;(define has-shown-backtrace-hint? #f) Defined by scm_init_backtrace ()
2901 ;; Replaced by C code:
2902 ;;(define (backtrace)
2903 ;; (if (fluid-ref the-last-stack)
2906 ;; (display-backtrace (fluid-ref the-last-stack) (current-output-port))
2908 ;; (if (and (not has-shown-backtrace-hint?)
2909 ;; (not (memq 'backtrace (debug-options-interface))))
2912 ;;"Type \"(debug-enable 'backtrace)\" if you would like a backtrace
2913 ;;automatically if an error occurs in the future.\n")
2914 ;; (set! has-shown-backtrace-hint? #t))))
2915 ;; (display "No backtrace available.\n")))
2917 (define (error-catching-repl r e p)
2918 (error-catching-loop
2920 (call-with-values (lambda () (e (r)))
2921 (lambda the-values (for-each p the-values))))))
2923 (define (gc-run-time)
2924 (cdr (assq 'gc-time-taken (gc-stats))))
2926 (define before-read-hook (make-hook))
2927 (define after-read-hook (make-hook))
2928 (define before-eval-hook (make-hook 1))
2929 (define after-eval-hook (make-hook 1))
2930 (define before-print-hook (make-hook 1))
2931 (define after-print-hook (make-hook 1))
2933 ;;; The default repl-reader function. We may override this if we've
2934 ;;; the readline library.
2936 (lambda (prompt . reader)
2937 (if (not (char-ready?))
2938 (display (if (string? prompt) prompt (prompt))))
2940 (run-hook before-read-hook)
2941 ((or (and (pair? reader) (car reader))
2942 (fluid-ref current-reader)
2944 (current-input-port))))
2946 (define (scm-style-repl)
2951 (repl-report-start-timing (lambda ()
2952 (set! start-gc-rt (gc-run-time))
2953 (set! start-rt (get-internal-run-time))))
2954 (repl-report (lambda ()
2956 (display (inexact->exact
2957 (* 1000 (/ (- (get-internal-run-time) start-rt)
2958 internal-time-units-per-second))))
2960 (display (inexact->exact
2961 (* 1000 (/ (- (gc-run-time) start-gc-rt)
2962 internal-time-units-per-second))))
2963 (display " msec in gc)\n")))
2965 (consume-trailing-whitespace
2967 (let ((ch (peek-char)))
2970 ((or (char=? ch #\space) (char=? ch #\tab))
2972 (consume-trailing-whitespace))
2973 ((char=? ch #\newline)
2977 (let ((prompt (cond ((string? scm-repl-prompt)
2979 ((thunk? scm-repl-prompt)
2981 (scm-repl-prompt "> ")
2983 (repl-reader prompt))))
2985 ;; As described in R4RS, the READ procedure updates the
2986 ;; port to point to the first character past the end of
2987 ;; the external representation of the object. This
2988 ;; means that it doesn't consume the newline typically
2989 ;; found after an expression. This means that, when
2990 ;; debugging Guile with GDB, GDB gets the newline, which
2991 ;; it often interprets as a "continue" command, making
2992 ;; breakpoints kind of useless. So, consume any
2993 ;; trailing newline here, as well as any whitespace
2995 ;; But not if EOF, for control-D.
2996 (if (not (eof-object? val))
2997 (consume-trailing-whitespace))
2998 (run-hook after-read-hook)
2999 (if (eof-object? val)
3001 (repl-report-start-timing)
3002 (if scm-repl-verbose
3005 (display ";;; EOF -- quitting")
3010 (-eval (lambda (sourc)
3011 (repl-report-start-timing)
3012 (run-hook before-eval-hook sourc)
3013 (let ((val (start-stack 'repl-stack
3014 ;; If you change this procedure
3015 ;; (primitive-eval), please also
3016 ;; modify the repl-stack case in
3017 ;; save-stack so that stack cutting
3018 ;; continues to work.
3019 (primitive-eval sourc))))
3020 (run-hook after-eval-hook sourc)
3024 (-print (let ((maybe-print (lambda (result)
3025 (if (or scm-repl-print-unspecified
3026 (not (unspecified? result)))
3031 (if (not scm-repl-silent)
3033 (run-hook before-print-hook result)
3034 (maybe-print result)
3035 (run-hook after-print-hook result)
3036 (if scm-repl-verbose
3040 (-quit (lambda (args)
3041 (if scm-repl-verbose
3043 (display ";;; QUIT executed, repl exitting")
3048 (let ((status (error-catching-repl -read
3056 ;;; {IOTA functions: generating lists of numbers}
3060 (let loop ((count (1- n)) (result '()))
3061 (if (< count 0) result
3062 (loop (1- count) (cons count result)))))
3068 ;;; Similar to `begin' but returns a list of the results of all constituent
3069 ;;; forms instead of the result of the last form.
3070 ;;; (The definition relies on the current left-to-right
3071 ;;; order of evaluation of operands in applications.)
3074 (defmacro collect forms
3081 ;;; with `continue' and `break'.
3084 ;; The inner `do' loop avoids re-establishing a catch every iteration,
3085 ;; that's only necessary if continue is actually used. A new key is
3086 ;; generated every time, so break and continue apply to their originating
3087 ;; `while' even when recursing.
3089 ;; FIXME: This macro is unintentionally unhygienic with respect to let,
3090 ;; make-symbol, do, throw, catch, lambda, and not.
3092 (define-macro (while cond . body)
3093 (let ((keyvar (make-symbol "while-keyvar")))
3094 `(let ((,keyvar (make-symbol "while-key")))
3098 (let ((break (lambda () (throw ,keyvar #t)))
3099 (continue (lambda () (throw ,keyvar #f))))
3110 ;;; {Module System Macros}
3113 ;; Return a list of expressions that evaluate to the appropriate
3114 ;; arguments for resolve-interface according to SPEC.
3118 (if (memq 'prefix (read-options))
3119 (error "boot-9 must be compiled with #:kw, not :kw")))
3121 (define (compile-interface-spec spec)
3122 (define (make-keyarg sym key quote?)
3123 (cond ((or (memq sym spec)
3127 (list key (list 'quote (cadr rest)))
3128 (list key (cadr rest)))))
3131 (define (map-apply func list)
3132 (map (lambda (args) (apply func args)) list))
3135 '((:select #:select #t)
3137 (:prefix #:prefix #t)
3138 (:renamer #:renamer #f)
3139 (:version #:version #t)))
3140 (if (not (pair? (car spec)))
3143 ,@(apply append (map-apply make-keyarg keys)))))
3145 (define (keyword-like-symbol->keyword sym)
3146 (symbol->keyword (string->symbol (substring (symbol->string sym) 1))))
3148 (define (compile-define-module-args args)
3149 ;; Just quote everything except #:use-module and #:use-syntax. We
3150 ;; need to know about all arguments regardless since we want to turn
3151 ;; symbols that look like keywords into real keywords, and the
3152 ;; keyword args in a define-module form are not regular
3153 ;; (i.e. no-backtrace doesn't take a value).
3154 (let loop ((compiled-args `((quote ,(car args))))
3157 (reverse! compiled-args))
3158 ;; symbol in keyword position
3159 ((symbol? (car args))
3161 (cons (keyword-like-symbol->keyword (car args)) (cdr args))))
3162 ((memq (car args) '(#:no-backtrace #:pure))
3163 (loop (cons (car args) compiled-args)
3166 (error "keyword without value:" (car args)))
3167 ((memq (car args) '(#:use-module #:use-syntax))
3168 (loop (cons* `(list ,@(compile-interface-spec (cadr args)))
3172 ((eq? (car args) #:autoload)
3173 (loop (cons* `(quote ,(caddr args))
3174 `(quote ,(cadr args))
3179 (loop (cons* `(quote ,(cadr args))
3184 (defmacro define-module args
3187 (let ((m (process-define-module
3188 (list ,@(compile-define-module-args args)))))
3189 (set-current-module m)
3192 ;; The guts of the use-modules macro. Add the interfaces of the named
3193 ;; modules to the use-list of the current module, in order.
3195 ;; This function is called by "modules.c". If you change it, be sure
3196 ;; to change scm_c_use_module as well.
3198 (define (process-use-modules module-interface-args)
3199 (let ((interfaces (map (lambda (mif-args)
3200 (or (apply resolve-interface mif-args)
3201 (error "no such module" mif-args)))
3202 module-interface-args)))
3203 (call-with-deferred-observers
3205 (module-use-interfaces! (current-module) interfaces)))))
3207 (defmacro use-modules modules
3210 (process-use-modules
3211 (list ,@(map (lambda (m)
3212 `(list ,@(compile-interface-spec m)))
3216 (defmacro use-syntax (spec)
3219 (issue-deprecation-warning
3220 "`use-syntax' is deprecated. Please contact guile-devel for more info.")
3221 (process-use-modules (list (list ,@(compile-interface-spec spec))))
3224 (define-syntax define-private
3229 (define-syntax define-public
3231 ((_ (name . args) . body)
3232 (define-public name (lambda args . body)))
3238 (define-syntax defmacro-public
3240 ((_ name args . body)
3242 (defmacro name args . body)
3243 (export-syntax name)))))
3245 ;; And now for the most important macro.
3248 ((_ formals body ...)
3249 (lambda formals body ...))))
3252 ;; Export a local variable
3254 ;; This function is called from "modules.c". If you change it, be
3255 ;; sure to update "modules.c" as well.
3257 (define (module-export! m names)
3258 (let ((public-i (module-public-interface m)))
3259 (for-each (lambda (name)
3260 (let* ((internal-name (if (pair? name) (car name) name))
3261 (external-name (if (pair? name) (cdr name) name))
3262 (var (module-ensure-local-variable! m internal-name)))
3263 (module-add! public-i external-name var)))
3266 (define (module-replace! m names)
3267 (let ((public-i (module-public-interface m)))
3268 (for-each (lambda (name)
3269 (let* ((internal-name (if (pair? name) (car name) name))
3270 (external-name (if (pair? name) (cdr name) name))
3271 (var (module-ensure-local-variable! m internal-name)))
3272 (set-object-property! var 'replace #t)
3273 (module-add! public-i external-name var)))
3276 ;; Re-export a imported variable
3278 (define (module-re-export! m names)
3279 (let ((public-i (module-public-interface m)))
3280 (for-each (lambda (name)
3281 (let* ((internal-name (if (pair? name) (car name) name))
3282 (external-name (if (pair? name) (cdr name) name))
3283 (var (module-variable m internal-name)))
3285 (error "Undefined variable:" internal-name))
3286 ((eq? var (module-local-variable m internal-name))
3287 (error "re-exporting local variable:" internal-name))
3289 (module-add! public-i external-name var)))))
3292 (defmacro export names
3293 `(eval-when (eval load compile)
3294 (call-with-deferred-observers
3296 (module-export! (current-module) ',names)))))
3298 (defmacro re-export names
3299 `(eval-when (eval load compile)
3300 (call-with-deferred-observers
3302 (module-re-export! (current-module) ',names)))))
3304 (defmacro export-syntax names
3307 (defmacro re-export-syntax names
3308 `(re-export ,@names))
3310 (define load load-module)
3317 (define make-mutable-parameter
3318 (let ((make (lambda (fluid converter)
3322 (fluid-set! fluid (converter (car args))))))))
3323 (lambda (init . converter)
3324 (let ((fluid (make-fluid))
3325 (converter (if (null? converter)
3328 (fluid-set! fluid (converter init))
3329 (make fluid converter)))))
3333 ;;; {Handling of duplicate imported bindings}
3336 ;; Duplicate handlers take the following arguments:
3338 ;; module importing module
3339 ;; name conflicting name
3340 ;; int1 old interface where name occurs
3341 ;; val1 value of binding in old interface
3342 ;; int2 new interface where name occurs
3343 ;; val2 value of binding in new interface
3344 ;; var previous resolution or #f
3345 ;; val value of previous resolution
3347 ;; A duplicate handler can take three alternative actions:
3349 ;; 1. return #f => leave responsibility to next handler
3350 ;; 2. exit with an error
3351 ;; 3. return a variable resolving the conflict
3354 (define duplicate-handlers
3355 (let ((m (make-module 7)))
3357 (define (check module name int1 val1 int2 val2 var val)
3358 (scm-error 'misc-error
3360 "~A: `~A' imported from both ~A and ~A"
3361 (list (module-name module)
3367 (define (warn module name int1 val1 int2 val2 var val)
3368 (format (current-error-port)
3369 "WARNING: ~A: `~A' imported from both ~A and ~A\n"
3370 (module-name module)
3376 (define (replace module name int1 val1 int2 val2 var val)
3377 (let ((old (or (and var (object-property var 'replace) var)
3378 (module-variable int1 name)))
3379 (new (module-variable int2 name)))
3380 (if (object-property old 'replace)
3381 (and (or (eq? old new)
3382 (not (object-property new 'replace)))
3384 (and (object-property new 'replace)
3387 (define (warn-override-core module name int1 val1 int2 val2 var val)
3388 (and (eq? int1 the-scm-module)
3390 (format (current-error-port)
3391 "WARNING: ~A: imported module ~A overrides core binding `~A'\n"
3392 (module-name module)
3395 (module-local-variable int2 name))))
3397 (define (first module name int1 val1 int2 val2 var val)
3398 (or var (module-local-variable int1 name)))
3400 (define (last module name int1 val1 int2 val2 var val)
3401 (module-local-variable int2 name))
3403 (define (noop module name int1 val1 int2 val2 var val)
3406 (set-module-name! m 'duplicate-handlers)
3407 (set-module-kind! m 'interface)
3408 (module-define! m 'check check)
3409 (module-define! m 'warn warn)
3410 (module-define! m 'replace replace)
3411 (module-define! m 'warn-override-core warn-override-core)
3412 (module-define! m 'first first)
3413 (module-define! m 'last last)
3414 (module-define! m 'merge-generics noop)
3415 (module-define! m 'merge-accessors noop)
3418 (define (lookup-duplicates-handlers handler-names)
3420 (map (lambda (handler-name)
3421 (or (module-symbol-local-binding
3422 duplicate-handlers handler-name #f)
3423 (error "invalid duplicate handler name:"
3425 (if (list? handler-names)
3427 (list handler-names)))))
3429 (define default-duplicate-binding-procedures
3430 (make-mutable-parameter #f))
3432 (define default-duplicate-binding-handler
3433 (make-mutable-parameter '(replace warn-override-core warn last)
3434 (lambda (handler-names)
3435 (default-duplicate-binding-procedures
3436 (lookup-duplicates-handlers handler-names))
3441 ;;; {`cond-expand' for SRFI-0 support.}
3443 ;;; This syntactic form expands into different commands or
3444 ;;; definitions, depending on the features provided by the Scheme
3450 ;;; --> (cond-expand <cond-expand-clause>+)
3451 ;;; | (cond-expand <cond-expand-clause>* (else <command-or-definition>))
3452 ;;; <cond-expand-clause>
3453 ;;; --> (<feature-requirement> <command-or-definition>*)
3454 ;;; <feature-requirement>
3455 ;;; --> <feature-identifier>
3456 ;;; | (and <feature-requirement>*)
3457 ;;; | (or <feature-requirement>*)
3458 ;;; | (not <feature-requirement>)
3459 ;;; <feature-identifier>
3460 ;;; --> <a symbol which is the name or alias of a SRFI>
3462 ;;; Additionally, this implementation provides the
3463 ;;; <feature-identifier>s `guile' and `r5rs', so that programs can
3464 ;;; determine the implementation type and the supported standard.
3466 ;;; Currently, the following feature identifiers are supported:
3468 ;;; guile r5rs srfi-0 srfi-4 srfi-6 srfi-13 srfi-14 srfi-55 srfi-61
3470 ;;; Remember to update the features list when adding more SRFIs.
3473 (define %cond-expand-features
3474 ;; Adjust the above comment when changing this.
3478 srfi-0 ;; cond-expand itself
3479 srfi-4 ;; homogenous numeric vectors
3480 srfi-6 ;; open-input-string etc, in the guile core
3481 srfi-13 ;; string library
3482 srfi-14 ;; character sets
3483 srfi-55 ;; require-extension
3484 srfi-61 ;; general cond clause
3487 ;; This table maps module public interfaces to the list of features.
3489 (define %cond-expand-table (make-hash-table 31))
3491 ;; Add one or more features to the `cond-expand' feature list of the
3494 (define (cond-expand-provide module features)
3495 (let ((mod (module-public-interface module)))
3497 (hashq-set! %cond-expand-table mod
3498 (append (hashq-ref %cond-expand-table mod '())
3501 (define-macro (cond-expand . clauses)
3502 (let ((syntax-error (lambda (cl)
3503 (error "invalid clause in `cond-expand'" cl))))
3509 (or (memq clause %cond-expand-features)
3510 (let lp ((uses (module-uses (current-module))))
3513 (hashq-ref %cond-expand-table
3519 ((eq? 'and (car clause))
3520 (let lp ((l (cdr clause)))
3524 (and (test-clause (car l)) (lp (cdr l))))
3526 (syntax-error clause)))))
3527 ((eq? 'or (car clause))
3528 (let lp ((l (cdr clause)))
3532 (or (test-clause (car l)) (lp (cdr l))))
3534 (syntax-error clause)))))
3535 ((eq? 'not (car clause))
3536 (cond ((not (pair? (cdr clause)))
3537 (syntax-error clause))
3538 ((pair? (cddr clause))
3539 ((syntax-error clause))))
3540 (not (test-clause (cadr clause))))
3542 (syntax-error clause))))
3544 (syntax-error clause))))))
3545 (let lp ((c clauses))
3548 (error "Unfulfilled `cond-expand'"))
3551 ((not (pair? (car c)))
3552 (syntax-error (car c)))
3553 ((test-clause (caar c))
3554 `(begin ,@(cdar c)))
3555 ((eq? (caar c) 'else)
3558 `(begin ,@(cdar c)))
3562 ;; This procedure gets called from the startup code with a list of
3563 ;; numbers, which are the numbers of the SRFIs to be loaded on startup.
3565 (define (use-srfis srfis)
3566 (process-use-modules
3568 (list (list 'srfi (string->symbol
3569 (string-append "srfi-" (number->string num))))))
3574 ;;; srfi-55: require-extension
3577 (define-macro (require-extension extension-spec)
3578 ;; This macro only handles the srfi extension, which, at present, is
3579 ;; the only one defined by the standard.
3580 (if (not (pair? extension-spec))
3581 (scm-error 'wrong-type-arg "require-extension"
3582 "Not an extension: ~S" (list extension-spec) #f))
3583 (let ((extension (car extension-spec))
3584 (extension-args (cdr extension-spec)))
3587 (let ((use-list '()))
3590 (if (not (integer? i))
3591 (scm-error 'wrong-type-arg "require-extension"
3592 "Invalid srfi name: ~S" (list i) #f))
3593 (let ((srfi-sym (string->symbol
3594 (string-append "srfi-" (number->string i)))))
3595 (if (not (memq srfi-sym %cond-expand-features))
3596 (set! use-list (cons `(use-modules (srfi ,srfi-sym))
3599 (if (pair? use-list)
3600 ;; i.e. (begin (use-modules x) (use-modules y) (use-modules z))
3601 `(begin ,@(reverse! use-list)))))
3604 'wrong-type-arg "require-extension"
3605 "Not a recognized extension type: ~S" (list extension) #f)))))
3609 ;;; {Load emacs interface support if emacs option is given.}
3612 (define (named-module-use! user usee)
3613 (module-use! (resolve-module user) (resolve-interface usee)))
3615 (define (load-emacs-interface)
3616 (and (provided? 'debug-extensions)
3617 (debug-enable 'backtrace))
3618 (named-module-use! '(guile-user) '(ice-9 emacs)))
3622 (define using-readline?
3623 (let ((using-readline? (make-fluid)))
3624 (make-procedure-with-setter
3625 (lambda () (fluid-ref using-readline?))
3626 (lambda (v) (fluid-set! using-readline? v)))))
3629 (let ((guile-user-module (resolve-module '(guile-user))))
3631 ;; Load emacs interface support if emacs option is given.
3632 (if (and (module-defined? guile-user-module 'use-emacs-interface)
3633 (module-ref guile-user-module 'use-emacs-interface))
3634 (load-emacs-interface))
3636 ;; Use some convenient modules (in reverse order)
3638 (set-current-module guile-user-module)
3639 (process-use-modules
3644 (if (provided? 'regex)
3647 (if (provided? 'threads)
3648 '(((ice-9 threads)))
3650 ;; load debugger on demand
3651 (module-autoload! guile-user-module '(system vm debug) '(debug))
3653 ;; Note: SIGFPE, SIGSEGV and SIGBUS are actually "query-only" (see
3654 ;; scmsigs.c scm_sigaction_for_thread), so the handlers setup here have
3656 (let ((old-handlers #f)
3657 (start-repl (module-ref (resolve-interface '(system repl repl))
3659 (signals (if (provided? 'posix)
3660 `((,SIGINT . "User interrupt")
3661 (,SIGFPE . "Arithmetic error")
3663 . "Bad memory access (Segmentation violation)"))
3665 ;; no SIGBUS on mingw
3666 (if (defined? 'SIGBUS)
3667 (set! signals (acons SIGBUS "Bad memory access (bus error)"
3674 (let ((make-handler (lambda (msg)
3676 ;; Make a backup copy of the stack
3677 (fluid-set! before-signal-stack
3678 (fluid-ref the-last-stack))
3686 (map (lambda (sig-msg)
3687 (sigaction (car sig-msg)
3688 (make-handler (cdr sig-msg))))
3691 ;; the protected thunk.
3693 (let ((status (start-repl 'scheme)))
3694 (run-hook exit-hook)
3699 (map (lambda (sig-msg old-handler)
3700 (if (not (car old-handler))
3701 ;; restore original C handler.
3702 (sigaction (car sig-msg) #f)
3703 ;; restore Scheme handler, SIG_IGN or SIG_DFL.
3704 (sigaction (car sig-msg)
3706 (cdr old-handler))))
3707 signals old-handlers))))))
3709 ;;; This hook is run at the very end of an interactive session.
3711 (define exit-hook (make-hook))
3715 ;;; {Deprecated stuff}
3719 (module-use! the-scm-module (resolve-interface '(ice-9 deprecated))))
3723 ;;; Place the user in the guile-user module.
3726 ;;; FIXME: annotate ?
3727 ;; (define (syncase exp)
3728 ;; (with-fluids ((expansion-eval-closure
3729 ;; (module-eval-closure (current-module))))
3730 ;; (deannotate/source-properties (macroexpand (annotate exp)))))
3733 (module-use! the-scm-module (resolve-interface '(srfi srfi-4)))
3735 (define-module (guile-user)
3736 #:autoload (system base compile) (compile))
3738 ;; Remain in the `(guile)' module at compilation-time so that the
3739 ;; `-Wunused-toplevel' warning works as expected.
3740 (eval-when (compile) (set-current-module the-root-module))
3742 ;;; boot-9.scm ends here