3 ;;;; Copyright (C) 1995,1996,1997,1998,1999,2000,2001,2002,2003,2004,2005,2006,2007,2009
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 2.1 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))))
46 (primitive-load-path "ice-9/r4rs")
50 ;;; {Simple Debugging Tools}
53 ;; peek takes any number of arguments, writes them to the
54 ;; current ouput port, and returns the last argument.
55 ;; It is handy to wrap around an expression to look at
56 ;; a value each time is evaluated, e.g.:
58 ;; (+ 10 (troublesome-fn))
59 ;; => (+ 10 (pk 'troublesome-fn-returned (troublesome-fn)))
62 (define (peek . stuff)
67 (car (last-pair stuff)))
71 (define (warn . stuff)
72 (with-output-to-port (current-error-port)
75 (display ";;; WARNING ")
78 (car (last-pair stuff)))))
86 (if (not (memq sym *features*))
87 (set! *features* (cons sym *features*))))
89 ;; Return #t iff FEATURE is available to this Guile interpreter. In SLIB,
90 ;; provided? also checks to see if the module is available. We should do that
93 (define (provided? feature)
94 (and (memq feature *features*) #t))
98 ;;; {and-map and or-map}
100 ;;; (and-map fn lst) is like (and (fn (car lst)) (fn (cadr lst)) (fn...) ...)
101 ;;; (or-map fn lst) is like (or (fn (car lst)) (fn (cadr lst)) (fn...) ...)
106 ;; Apply f to successive elements of l until exhaustion or f returns #f.
107 ;; If returning early, return #f. Otherwise, return the last value returned
108 ;; by f. If f has never been called because l is empty, return #t.
110 (define (and-map f lst)
111 (let loop ((result #t)
116 (loop (f (car l)) (cdr l))))))
120 ;; Apply f to successive elements of l until exhaustion or while f returns #f.
121 ;; If returning early, return the return value of f.
123 (define (or-map f lst)
124 (let loop ((result #f)
128 (loop (f (car l)) (cdr l))))))
132 ;; let format alias simple-format until the more complete version is loaded
134 (define format simple-format)
136 ;; this is scheme wrapping the C code so the final pred call is a tail call,
138 (define (string-any char_pred s . rest)
139 (let ((start (if (null? rest)
141 (end (if (or (null? rest) (null? (cdr rest)))
142 (string-length s) (cadr rest))))
143 (if (and (procedure? char_pred)
145 (<= end (string-length s))) ;; let c-code handle range error
146 (or (string-any-c-code char_pred s start (1- end))
147 (char_pred (string-ref s (1- end))))
148 (string-any-c-code char_pred s start end))))
150 ;; this is scheme wrapping the C code so the final pred call is a tail call,
152 (define (string-every char_pred s . rest)
153 (let ((start (if (null? rest)
155 (end (if (or (null? rest) (null? (cdr rest)))
156 (string-length s) (cadr rest))))
157 (if (and (procedure? char_pred)
159 (<= end (string-length s))) ;; let c-code handle range error
160 (and (string-every-c-code char_pred s start (1- end))
161 (char_pred (string-ref s (1- end))))
162 (string-every-c-code char_pred s start end))))
164 ;; A variant of string-fill! that we keep for compatability
166 (define (substring-fill! str start end fill)
167 (string-fill! str fill start end))
171 ;; Define a minimal stub of the module API for psyntax, before modules
173 (define (module-name x)
175 (define (module-define! module sym val)
176 (let ((v (hashq-ref (%get-pre-modules-obarray) sym)))
178 (variable-set! v val)
179 (hashq-set! (%get-pre-modules-obarray) sym
180 (make-variable val)))))
181 (define (module-ref module sym)
182 (let ((v (module-variable module sym)))
183 (if v (variable-ref v) (error "badness!" (pk module) (pk sym)))))
184 (define (resolve-module . args)
187 ;; Input hook to syncase -- so that we might be able to pass annotated
188 ;; expressions in. Currently disabled. Maybe we should just use
189 ;; source-properties directly.
190 (define (annotation? x) #f)
192 ;; API provided by psyntax
193 (define syntax-violation #f)
194 (define datum->syntax #f)
195 (define syntax->datum #f)
196 (define identifier? #f)
197 (define generate-temporaries #f)
198 (define bound-identifier=? #f)
199 (define free-identifier=? #f)
200 (define sc-expand #f)
202 ;; $sc-expand is an implementation detail of psyntax. It is used by
203 ;; expanded macros, to dispatch an input against a set of patterns.
204 (define $sc-dispatch #f)
207 (primitive-load-path "ice-9/psyntax-pp")
209 ;; %pre-modules-transformer is the Scheme expander from now until the
210 ;; module system has booted up.
211 (define %pre-modules-transformer sc-expand)
217 ((_ x y ...) (if x (and y ...) #f))))
223 ((_ x y ...) (let ((t x)) (if t t (or y ...))))))
225 ;; The "maybe-more" bits are something of a hack, so that we can support
226 ;; SRFI-61. Rewrites into a standalone syntax-case macro would be
229 (syntax-rules (=> else)
230 ((_ "maybe-more" test consequent)
231 (if test consequent))
233 ((_ "maybe-more" test consequent clause ...)
234 (if test consequent (cond clause ...)))
236 ((_ (else else1 else2 ...))
237 (begin else1 else2 ...))
239 ((_ (test => receiver) more-clause ...)
241 (cond "maybe-more" t (receiver t) more-clause ...)))
243 ((_ (generator guard => receiver) more-clause ...)
244 (call-with-values (lambda () generator)
247 (apply guard t) (apply receiver t) more-clause ...))))
249 ((_ (test => receiver ...) more-clause ...)
250 (syntax-violation 'cond "wrong number of receiver expressions"
251 '(test => receiver ...)))
252 ((_ (generator guard => receiver ...) more-clause ...)
253 (syntax-violation 'cond "wrong number of receiver expressions"
254 '(generator guard => receiver ...)))
256 ((_ (test) more-clause ...)
258 (cond "maybe-more" t t more-clause ...)))
260 ((_ (test body1 body2 ...) more-clause ...)
262 test (begin body1 body2 ...) more-clause ...))))
268 (let ((atom-key (key ...)))
269 (case atom-key clauses ...)))
271 (else result1 result2 ...))
272 (begin result1 result2 ...))
274 ((atoms ...) result1 result2 ...))
275 (if (memv key '(atoms ...))
276 (begin result1 result2 ...)))
278 ((atoms ...) result1 result2 ...)
280 (if (memv key '(atoms ...))
281 (begin result1 result2 ...)
282 (case key clause clauses ...)))))
286 ((do ((var init step ...) ...)
299 (loop (do "step" var step ...)
309 ((_ exp) (make-promise (lambda () exp)))))
316 (define-syntax define-macro
320 ((_ (macro . args) doc body1 body ...)
321 (string? (syntax->datum (syntax doc)))
322 (syntax (define-macro macro doc (lambda args body1 body ...))))
323 ((_ (macro . args) body ...)
324 (syntax (define-macro macro #f (lambda args body ...))))
325 ((_ macro doc transformer)
326 (or (string? (syntax->datum (syntax doc)))
327 (not (syntax->datum (syntax doc))))
334 (let ((v (syntax->datum (syntax args))))
335 (datum->syntax y (apply transformer v))))))))))))
337 (define-syntax defmacro
339 "Define a defmacro, with the old lispy defun syntax."
341 ((_ macro args doc body1 body ...)
342 (string? (syntax->datum (syntax doc)))
343 (syntax (define-macro macro doc (lambda args body1 body ...))))
344 ((_ macro args body ...)
345 (syntax (define-macro macro #f (lambda args body ...)))))))
353 ;;; Depends on: defmacro
356 (defmacro begin-deprecated forms
357 (if (include-deprecated-features)
363 ;;; {Trivial Functions}
366 (define (identity x) x)
367 (define (and=> value procedure) (and value (procedure value)))
368 (define call/cc call-with-current-continuation)
370 ;;; apply-to-args is functionally redundant with apply and, worse,
371 ;;; is less general than apply since it only takes two arguments.
373 ;;; On the other hand, apply-to-args is a syntacticly convenient way to
374 ;;; perform binding in many circumstances when the "let" family of
375 ;;; of forms don't cut it. E.g.:
377 ;;; (apply-to-args (return-3d-mouse-coords)
382 (define (apply-to-args args fn) (apply fn args))
384 (defmacro false-if-exception (expr)
385 `(catch #t (lambda () ,expr)
390 ;;; {General Properties}
393 ;; This is a more modern interface to properties. It will replace all
394 ;; other property-like things eventually.
396 (define (make-object-property)
397 (let ((prop (primitive-make-property #f)))
398 (make-procedure-with-setter
399 (lambda (obj) (primitive-property-ref prop obj))
400 (lambda (obj val) (primitive-property-set! prop obj val)))))
404 ;;; {Symbol Properties}
407 (define (symbol-property sym prop)
408 (let ((pair (assoc prop (symbol-pref sym))))
409 (and pair (cdr pair))))
411 (define (set-symbol-property! sym prop val)
412 (let ((pair (assoc prop (symbol-pref sym))))
415 (symbol-pset! sym (acons prop val (symbol-pref sym))))))
417 (define (symbol-property-remove! sym prop)
418 (let ((pair (assoc prop (symbol-pref sym))))
420 (symbol-pset! sym (delq! pair (symbol-pref sym))))))
427 (define (array-shape a)
428 (map (lambda (ind) (if (number? ind) (list 0 (+ -1 ind)) ind))
429 (array-dimensions a)))
436 (define (kw-arg-ref args kw)
437 (let ((rem (member kw args)))
438 (and rem (pair? (cdr rem)) (cadr rem))))
445 (define (struct-layout s)
446 (struct-ref (struct-vtable s) vtable-index-layout))
453 ;; Printing records: by default, records are printed as
455 ;; #<type-name field1: val1 field2: val2 ...>
457 ;; You can change that by giving a custom printing function to
458 ;; MAKE-RECORD-TYPE (after the list of field symbols). This function
459 ;; will be called like
461 ;; (<printer> object port)
463 ;; It should print OBJECT to PORT.
465 (define (inherit-print-state old-port new-port)
466 (if (get-print-state old-port)
467 (port-with-print-state new-port (get-print-state old-port))
470 ;; 0: type-name, 1: fields
471 (define record-type-vtable
472 (make-vtable-vtable "prpr" 0
474 (cond ((eq? s record-type-vtable)
475 (display "#<record-type-vtable>" p))
477 (display "#<record-type " p)
478 (display (record-type-name s) p)
481 (define (record-type? obj)
482 (and (struct? obj) (eq? record-type-vtable (struct-vtable obj))))
484 (define (make-record-type type-name fields . opt)
485 (let ((printer-fn (and (pair? opt) (car opt))))
486 (let ((struct (make-struct record-type-vtable 0
489 (map (lambda (f) "pw") fields)))
493 (display type-name p)
494 (let loop ((fields fields)
497 ((not (null? fields))
499 (display (car fields) p)
501 (display (struct-ref s off) p)
502 (loop (cdr fields) (+ 1 off)))))
505 (copy-tree fields))))
506 ;; Temporary solution: Associate a name to the record type descriptor
507 ;; so that the object system can create a wrapper class for it.
508 (set-struct-vtable-name! struct (if (symbol? type-name)
510 (string->symbol type-name)))
513 (define (record-type-name obj)
514 (if (record-type? obj)
515 (struct-ref obj vtable-offset-user)
516 (error 'not-a-record-type obj)))
518 (define (record-type-fields obj)
519 (if (record-type? obj)
520 (struct-ref obj (+ 1 vtable-offset-user))
521 (error 'not-a-record-type obj)))
523 (define (record-constructor rtd . opt)
524 (let ((field-names (if (pair? opt) (car opt) (record-type-fields rtd))))
526 `(lambda ,field-names
527 (make-struct ',rtd 0 ,@(map (lambda (f)
528 (if (memq f field-names)
531 (record-type-fields rtd)))))))
533 (define (record-predicate rtd)
534 (lambda (obj) (and (struct? obj) (eq? rtd (struct-vtable obj)))))
536 (define (%record-type-error rtd obj) ;; private helper
537 (or (eq? rtd (record-type-descriptor obj))
538 (scm-error 'wrong-type-arg "%record-type-check"
539 "Wrong type record (want `~S'): ~S"
540 (list (record-type-name rtd) obj)
543 (define (record-accessor rtd field-name)
544 (let ((pos (list-index (record-type-fields rtd) field-name)))
546 (error 'no-such-field field-name))
548 (if (eq? (struct-vtable obj) rtd)
550 (%record-type-error rtd obj)))))
552 (define (record-modifier rtd field-name)
553 (let ((pos (list-index (record-type-fields rtd) field-name)))
555 (error 'no-such-field field-name))
557 (if (eq? (struct-vtable obj) rtd)
558 (struct-set! obj pos val)
559 (%record-type-error rtd obj)))))
561 (define (record? obj)
562 (and (struct? obj) (record-type? (struct-vtable obj))))
564 (define (record-type-descriptor obj)
567 (error 'not-a-record obj)))
576 (define (->bool x) (not (not x)))
583 (define (symbol-append . args)
584 (string->symbol (apply string-append (map symbol->string args))))
586 (define (list->symbol . args)
587 (string->symbol (apply list->string args)))
589 (define (symbol . args)
590 (string->symbol (apply string args)))
597 (define (list-index l k)
603 (loop (+ n 1) (cdr l))))))
607 (if (provided? 'posix)
608 (primitive-load-path "ice-9/posix"))
610 (if (provided? 'socket)
611 (primitive-load-path "ice-9/networking"))
613 ;; For reference, Emacs file-exists-p uses stat in this same way.
615 (if (provided? 'posix)
617 (->bool (stat str #f)))
619 (let ((port (catch 'system-error (lambda () (open-file str OPEN_READ))
621 (if port (begin (close-port port) #t)
624 (define file-is-directory?
625 (if (provided? 'posix)
627 (eq? (stat:type (stat str)) 'directory))
629 (let ((port (catch 'system-error
630 (lambda () (open-file (string-append str "/.")
633 (if port (begin (close-port port) #t)
636 (define (has-suffix? str suffix)
637 (string-suffix? suffix str))
639 (define (system-error-errno args)
640 (if (eq? (car args) 'system-error)
641 (car (list-ref args 4))
649 (define (error . args)
652 (scm-error 'misc-error #f "?" #f #f)
653 (let loop ((msg "~A")
655 (if (not (null? rest))
656 (loop (string-append msg " ~S")
658 (scm-error 'misc-error #f msg args #f)))))
660 ;; bad-throw is the hook that is called upon a throw to a an unhandled
661 ;; key (unless the throw has four arguments, in which case
662 ;; it's usually interpreted as an error throw.)
663 ;; If the key has a default handler (a throw-handler-default property),
664 ;; it is applied to the throw.
666 (define (bad-throw key . args)
667 (let ((default (symbol-property key 'throw-handler-default)))
668 (or (and default (apply default key args))
669 (apply error "unhandled-exception:" key args))))
673 (define (tm:sec obj) (vector-ref obj 0))
674 (define (tm:min obj) (vector-ref obj 1))
675 (define (tm:hour obj) (vector-ref obj 2))
676 (define (tm:mday obj) (vector-ref obj 3))
677 (define (tm:mon obj) (vector-ref obj 4))
678 (define (tm:year obj) (vector-ref obj 5))
679 (define (tm:wday obj) (vector-ref obj 6))
680 (define (tm:yday obj) (vector-ref obj 7))
681 (define (tm:isdst obj) (vector-ref obj 8))
682 (define (tm:gmtoff obj) (vector-ref obj 9))
683 (define (tm:zone obj) (vector-ref obj 10))
685 (define (set-tm:sec obj val) (vector-set! obj 0 val))
686 (define (set-tm:min obj val) (vector-set! obj 1 val))
687 (define (set-tm:hour obj val) (vector-set! obj 2 val))
688 (define (set-tm:mday obj val) (vector-set! obj 3 val))
689 (define (set-tm:mon obj val) (vector-set! obj 4 val))
690 (define (set-tm:year obj val) (vector-set! obj 5 val))
691 (define (set-tm:wday obj val) (vector-set! obj 6 val))
692 (define (set-tm:yday obj val) (vector-set! obj 7 val))
693 (define (set-tm:isdst obj val) (vector-set! obj 8 val))
694 (define (set-tm:gmtoff obj val) (vector-set! obj 9 val))
695 (define (set-tm:zone obj val) (vector-set! obj 10 val))
697 (define (tms:clock obj) (vector-ref obj 0))
698 (define (tms:utime obj) (vector-ref obj 1))
699 (define (tms:stime obj) (vector-ref obj 2))
700 (define (tms:cutime obj) (vector-ref obj 3))
701 (define (tms:cstime obj) (vector-ref obj 4))
703 (define file-position ftell)
704 (define (file-set-position port offset . whence)
705 (let ((whence (if (eq? whence '()) SEEK_SET (car whence))))
706 (seek port offset whence)))
708 (define (move->fdes fd/port fd)
709 (cond ((integer? fd/port)
710 (dup->fdes fd/port fd)
714 (primitive-move->fdes fd/port fd)
715 (set-port-revealed! fd/port 1)
718 (define (release-port-handle port)
719 (let ((revealed (port-revealed port)))
721 (set-port-revealed! port (- revealed 1)))))
723 (define (dup->port port/fd mode . maybe-fd)
724 (let ((port (fdopen (apply dup->fdes port/fd maybe-fd)
727 (set-port-revealed! port 1))
730 (define (dup->inport port/fd . maybe-fd)
731 (apply dup->port port/fd "r" maybe-fd))
733 (define (dup->outport port/fd . maybe-fd)
734 (apply dup->port port/fd "w" maybe-fd))
736 (define (dup port/fd . maybe-fd)
737 (if (integer? port/fd)
738 (apply dup->fdes port/fd maybe-fd)
739 (apply dup->port port/fd (port-mode port/fd) maybe-fd)))
741 (define (duplicate-port port modes)
742 (dup->port port modes))
744 (define (fdes->inport fdes)
745 (let loop ((rest-ports (fdes->ports fdes)))
746 (cond ((null? rest-ports)
747 (let ((result (fdopen fdes "r")))
748 (set-port-revealed! result 1)
750 ((input-port? (car rest-ports))
751 (set-port-revealed! (car rest-ports)
752 (+ (port-revealed (car rest-ports)) 1))
755 (loop (cdr rest-ports))))))
757 (define (fdes->outport fdes)
758 (let loop ((rest-ports (fdes->ports fdes)))
759 (cond ((null? rest-ports)
760 (let ((result (fdopen fdes "w")))
761 (set-port-revealed! result 1)
763 ((output-port? (car rest-ports))
764 (set-port-revealed! (car rest-ports)
765 (+ (port-revealed (car rest-ports)) 1))
768 (loop (cdr rest-ports))))))
770 (define (port->fdes port)
771 (set-port-revealed! port (+ (port-revealed port) 1))
774 (define (setenv name value)
776 (putenv (string-append name "=" value))
779 (define (unsetenv name)
780 "Remove the entry for NAME from the environment."
788 ;;; Here for backward compatability
790 (define scheme-file-suffix (lambda () ".scm"))
792 (define (in-vicinity vicinity file)
793 (let ((tail (let ((len (string-length vicinity)))
796 (string-ref vicinity (- len 1))))))
797 (string-append vicinity
806 ;;; {Help for scm_shell}
808 ;;; The argument-processing code used by Guile-based shells generates
809 ;;; Scheme code based on the argument list. This page contains help
810 ;;; functions for the code it generates.
813 (define (command-line) (program-arguments))
815 ;; This is mostly for the internal use of the code generated by
816 ;; scm_compile_shell_switches.
818 (define (turn-on-debugging)
819 (debug-enable 'debug)
820 (debug-enable 'backtrace)
821 (read-enable 'positions))
823 (define (load-user-init)
824 (let* ((home (or (getenv "HOME")
825 (false-if-exception (passwd:dir (getpwuid (getuid))))
826 "/")) ;; fallback for cygwin etc.
827 (init-file (in-vicinity home ".guile")))
828 (if (file-exists? init-file)
829 (primitive-load init-file))))
833 ;;; {The interpreter stack}
836 (defmacro start-stack (tag exp)
837 `(%start-stack ,tag (lambda () ,exp)))
841 ;;; {Loading by paths}
844 ;;; Load a Scheme source file named NAME, searching for it in the
845 ;;; directories listed in %load-path, and applying each of the file
846 ;;; name extensions listed in %load-extensions.
847 (define (load-from-path name)
848 (start-stack 'load-stack
849 (primitive-load-path name)))
851 (define %load-verbosely #f)
852 (define (assert-load-verbosity v) (set! %load-verbosely v))
854 (define (%load-announce file)
856 (with-output-to-port (current-error-port)
864 (set! %load-hook %load-announce)
866 (define (load name . reader)
867 (with-fluid* current-reader (and (pair? reader) (car reader))
869 (start-stack 'load-stack
870 (primitive-load name)))))
874 ;;; {Transcendental Functions}
876 ;;; Derived from "Transcen.scm", Complex trancendental functions for SCM.
877 ;;; Written by Jerry D. Hedden, (C) FSF.
878 ;;; See the file `COPYING' for terms applying to this program.
882 (let ((integer-expt integer-expt))
884 (cond ((and (exact? z2) (integer? z2))
885 (integer-expt z1 z2))
886 ((and (real? z2) (real? z1) (>= z1 0))
889 (exp (* z2 (log z1))))))))
892 (if (real? z) ($sinh z)
893 (let ((x (real-part z)) (y (imag-part z)))
894 (make-rectangular (* ($sinh x) ($cos y))
895 (* ($cosh x) ($sin y))))))
897 (if (real? z) ($cosh z)
898 (let ((x (real-part z)) (y (imag-part z)))
899 (make-rectangular (* ($cosh x) ($cos y))
900 (* ($sinh x) ($sin y))))))
902 (if (real? z) ($tanh z)
903 (let* ((x (* 2 (real-part z)))
904 (y (* 2 (imag-part z)))
905 (w (+ ($cosh x) ($cos y))))
906 (make-rectangular (/ ($sinh x) w) (/ ($sin y) w)))))
909 (if (real? z) ($asinh z)
910 (log (+ z (sqrt (+ (* z z) 1))))))
913 (if (and (real? z) (>= z 1))
915 (log (+ z (sqrt (- (* z z) 1))))))
918 (if (and (real? z) (> z -1) (< z 1))
920 (/ (log (/ (+ 1 z) (- 1 z))) 2)))
923 (if (real? z) ($sin z)
924 (let ((x (real-part z)) (y (imag-part z)))
925 (make-rectangular (* ($sin x) ($cosh y))
926 (* ($cos x) ($sinh y))))))
928 (if (real? z) ($cos z)
929 (let ((x (real-part z)) (y (imag-part z)))
930 (make-rectangular (* ($cos x) ($cosh y))
931 (- (* ($sin x) ($sinh y)))))))
933 (if (real? z) ($tan z)
934 (let* ((x (* 2 (real-part z)))
935 (y (* 2 (imag-part z)))
936 (w (+ ($cos x) ($cosh y))))
937 (make-rectangular (/ ($sin x) w) (/ ($sinh y) w)))))
940 (if (and (real? z) (>= z -1) (<= z 1))
942 (* -i (asinh (* +i z)))))
945 (if (and (real? z) (>= z -1) (<= z 1))
947 (+ (/ (angle -1) 2) (* +i (asinh (* +i z))))))
951 (if (real? z) ($atan z)
952 (/ (log (/ (- +i z) (+ +i z))) +2i))
957 ;;; {Reader Extensions}
959 ;;; Reader code for various "#c" forms.
962 (define read-eval? (make-fluid))
963 (fluid-set! read-eval? #f)
964 (read-hash-extend #\.
966 (if (fluid-ref read-eval?)
967 (eval (read port) (interaction-environment))
969 "#. read expansion found and read-eval? is #f."))))
973 ;;; {Command Line Options}
976 (define (get-option argv kw-opts kw-args return)
981 ((or (not (eq? #\- (string-ref (car argv) 0)))
982 (eq? (string-length (car argv)) 1))
983 (return 'normal-arg (car argv) (cdr argv)))
985 ((eq? #\- (string-ref (car argv) 1))
986 (let* ((kw-arg-pos (or (string-index (car argv) #\=)
987 (string-length (car argv))))
988 (kw (symbol->keyword (substring (car argv) 2 kw-arg-pos)))
989 (kw-opt? (member kw kw-opts))
990 (kw-arg? (member kw kw-args))
991 (arg (or (and (not (eq? kw-arg-pos (string-length (car argv))))
992 (substring (car argv)
994 (string-length (car argv))))
996 (begin (set! argv (cdr argv)) (car argv))))))
997 (if (or kw-opt? kw-arg?)
998 (return kw arg (cdr argv))
999 (return 'usage-error kw (cdr argv)))))
1002 (let* ((char (substring (car argv) 1 2))
1003 (kw (symbol->keyword char)))
1006 ((member kw kw-opts)
1007 (let* ((rest-car (substring (car argv) 2 (string-length (car argv))))
1008 (new-argv (if (= 0 (string-length rest-car))
1010 (cons (string-append "-" rest-car) (cdr argv)))))
1011 (return kw #f new-argv)))
1013 ((member kw kw-args)
1014 (let* ((rest-car (substring (car argv) 2 (string-length (car argv))))
1015 (arg (if (= 0 (string-length rest-car))
1018 (new-argv (if (= 0 (string-length rest-car))
1021 (return kw arg new-argv)))
1023 (else (return 'usage-error kw argv)))))))
1025 (define (for-next-option proc argv kw-opts kw-args)
1026 (let loop ((argv argv))
1027 (get-option argv kw-opts kw-args
1028 (lambda (opt opt-arg argv)
1029 (and opt (proc opt opt-arg argv loop))))))
1031 (define (display-usage-report kw-desc)
1034 (or (eq? (car kw) #t)
1035 (eq? (car kw) 'else)
1036 (let* ((opt-desc kw)
1037 (help (cadr opt-desc))
1038 (opts (car opt-desc))
1039 (opts-proper (if (string? (car opts)) (cdr opts) opts))
1040 (arg-name (if (string? (car opts))
1041 (string-append "<" (car opts) ">")
1043 (left-part (string-append
1044 (with-output-to-string
1046 (map (lambda (x) (display (keyword->symbol x)) (display " "))
1049 (middle-part (if (and (< (string-length left-part) 30)
1050 (< (string-length help) 40))
1051 (make-string (- 30 (string-length left-part)) #\ )
1054 (display middle-part)
1061 (define (transform-usage-lambda cases)
1062 (let* ((raw-usage (delq! 'else (map car cases)))
1063 (usage-sans-specials (map (lambda (x)
1064 (or (and (not (list? x)) x)
1065 (and (symbol? (car x)) #t)
1066 (and (boolean? (car x)) #t)
1069 (usage-desc (delq! #t usage-sans-specials))
1070 (kw-desc (map car usage-desc))
1071 (kw-opts (apply append (map (lambda (x) (and (not (string? (car x))) x)) kw-desc)))
1072 (kw-args (apply append (map (lambda (x) (and (string? (car x)) (cdr x))) kw-desc)))
1073 (transmogrified-cases (map (lambda (case)
1074 (cons (let ((opts (car case)))
1075 (if (or (boolean? opts) (eq? 'else opts))
1078 ((symbol? (car opts)) opts)
1079 ((boolean? (car opts)) opts)
1080 ((string? (caar opts)) (cdar opts))
1081 (else (car opts)))))
1084 `(let ((%display-usage (lambda () (display-usage-report ',usage-desc))))
1086 (let %next-arg ((%argv %argv))
1090 (lambda (%opt %arg %new-argv)
1092 ,@ transmogrified-cases))))))))
1097 ;;; {Low Level Modules}
1099 ;;; These are the low level data structures for modules.
1101 ;;; Every module object is of the type 'module-type', which is a record
1102 ;;; consisting of the following members:
1104 ;;; - eval-closure: the function that defines for its module the strategy that
1105 ;;; shall be followed when looking up symbols in the module.
1107 ;;; An eval-closure is a function taking two arguments: the symbol to be
1108 ;;; looked up and a boolean value telling whether a binding for the symbol
1109 ;;; should be created if it does not exist yet. If the symbol lookup
1110 ;;; succeeded (either because an existing binding was found or because a new
1111 ;;; binding was created), a variable object representing the binding is
1112 ;;; returned. Otherwise, the value #f is returned. Note that the eval
1113 ;;; closure does not take the module to be searched as an argument: During
1114 ;;; construction of the eval-closure, the eval-closure has to store the
1115 ;;; module it belongs to in its environment. This means, that any
1116 ;;; eval-closure can belong to only one module.
1118 ;;; The eval-closure of a module can be defined arbitrarily. However, three
1119 ;;; special cases of eval-closures are to be distinguished: During startup
1120 ;;; the module system is not yet activated. In this phase, no modules are
1121 ;;; defined and all bindings are automatically stored by the system in the
1122 ;;; pre-modules-obarray. Since no eval-closures exist at this time, the
1123 ;;; functions which require an eval-closure as their argument need to be
1124 ;;; passed the value #f.
1126 ;;; The other two special cases of eval-closures are the
1127 ;;; standard-eval-closure and the standard-interface-eval-closure. Both
1128 ;;; behave equally for the case that no new binding is to be created. The
1129 ;;; difference between the two comes in, when the boolean argument to the
1130 ;;; eval-closure indicates that a new binding shall be created if it is not
1133 ;;; Given that no new binding shall be created, both standard eval-closures
1134 ;;; define the following standard strategy of searching bindings in the
1135 ;;; module: First, the module's obarray is searched for the symbol. Second,
1136 ;;; if no binding for the symbol was found in the module's obarray, the
1137 ;;; module's binder procedure is exececuted. If this procedure did not
1138 ;;; return a binding for the symbol, the modules referenced in the module's
1139 ;;; uses list are recursively searched for a binding of the symbol. If the
1140 ;;; binding can not be found in these modules also, the symbol lookup has
1143 ;;; If a new binding shall be created, the standard-interface-eval-closure
1144 ;;; immediately returns indicating failure. That is, it does not even try
1145 ;;; to look up the symbol. In contrast, the standard-eval-closure would
1146 ;;; first search the obarray, and if no binding was found there, would
1147 ;;; create a new binding in the obarray, therefore not calling the binder
1148 ;;; procedure or searching the modules in the uses list.
1150 ;;; The explanation of the following members obarray, binder and uses
1151 ;;; assumes that the symbol lookup follows the strategy that is defined in
1152 ;;; the standard-eval-closure and the standard-interface-eval-closure.
1154 ;;; - obarray: a hash table that maps symbols to variable objects. In this
1155 ;;; hash table, the definitions are found that are local to the module (that
1156 ;;; is, not imported from other modules). When looking up bindings in the
1157 ;;; module, this hash table is searched first.
1159 ;;; - binder: either #f or a function taking a module and a symbol argument.
1160 ;;; If it is a function it is called after the obarray has been
1161 ;;; unsuccessfully searched for a binding. It then can provide bindings
1162 ;;; that would otherwise not be found locally in the module.
1164 ;;; - uses: a list of modules from which non-local bindings can be inherited.
1165 ;;; These modules are the third place queried for bindings after the obarray
1166 ;;; has been unsuccessfully searched and the binder function did not deliver
1167 ;;; a result either.
1169 ;;; - transformer: either #f or a function taking a scheme expression as
1170 ;;; delivered by read. If it is a function, it will be called to perform
1171 ;;; syntax transformations (e. g. makro expansion) on the given scheme
1172 ;;; expression. The output of the transformer function will then be passed
1173 ;;; to Guile's internal memoizer. This means that the output must be valid
1174 ;;; scheme code. The only exception is, that the output may make use of the
1175 ;;; syntax extensions provided to identify the modules that a binding
1178 ;;; - name: the name of the module. This is used for all kinds of printing
1179 ;;; outputs. In certain places the module name also serves as a way of
1180 ;;; identification. When adding a module to the uses list of another
1181 ;;; module, it is made sure that the new uses list will not contain two
1182 ;;; modules of the same name.
1184 ;;; - kind: classification of the kind of module. The value is (currently?)
1185 ;;; only used for printing. It has no influence on how a module is treated.
1186 ;;; Currently the following values are used when setting the module kind:
1187 ;;; 'module, 'directory, 'interface, 'custom-interface. If no explicit kind
1188 ;;; is set, it defaults to 'module.
1190 ;;; - duplicates-handlers: a list of procedures that get called to make a
1191 ;;; choice between two duplicate bindings when name clashes occur. See the
1192 ;;; `duplicate-handlers' global variable below.
1194 ;;; - observers: a list of procedures that get called when the module is
1197 ;;; - weak-observers: a weak-key hash table of procedures that get called
1198 ;;; when the module is modified. See `module-observe-weak' for details.
1200 ;;; In addition, the module may (must?) contain a binding for
1201 ;;; `%module-public-interface'. This variable should be bound to a module
1202 ;;; representing the exported interface of a module. See the
1203 ;;; `module-public-interface' and `module-export!' procedures.
1205 ;;; !!! warning: The interface to lazy binder procedures is going
1206 ;;; to be changed in an incompatible way to permit all the basic
1207 ;;; module ops to be virtualized.
1209 ;;; (make-module size use-list lazy-binding-proc) => module
1210 ;;; module-{obarray,uses,binder}[|-set!]
1211 ;;; (module? obj) => [#t|#f]
1212 ;;; (module-locally-bound? module symbol) => [#t|#f]
1213 ;;; (module-bound? module symbol) => [#t|#f]
1214 ;;; (module-symbol-locally-interned? module symbol) => [#t|#f]
1215 ;;; (module-symbol-interned? module symbol) => [#t|#f]
1216 ;;; (module-local-variable module symbol) => [#<variable ...> | #f]
1217 ;;; (module-variable module symbol) => [#<variable ...> | #f]
1218 ;;; (module-symbol-binding module symbol opt-value)
1219 ;;; => [ <obj> | opt-value | an error occurs ]
1220 ;;; (module-make-local-var! module symbol) => #<variable...>
1221 ;;; (module-add! module symbol var) => unspecified
1222 ;;; (module-remove! module symbol) => unspecified
1223 ;;; (module-for-each proc module) => unspecified
1224 ;;; (make-scm-module) => module ; a lazy copy of the symhash module
1225 ;;; (set-current-module module) => unspecified
1226 ;;; (current-module) => #<module...>
1232 ;;; {Printing Modules}
1235 ;; This is how modules are printed. You can re-define it.
1236 ;; (Redefining is actually more complicated than simply redefining
1237 ;; %print-module because that would only change the binding and not
1238 ;; the value stored in the vtable that determines how record are
1241 (define (%print-module mod port) ; unused args: depth length style table)
1243 (display (or (module-kind mod) "module") port)
1245 (display (module-name mod) port)
1247 (display (number->string (object-address mod) 16) port)
1252 ;; A module is characterized by an obarray in which local symbols
1253 ;; are interned, a list of modules, "uses", from which non-local
1254 ;; bindings can be inherited, and an optional lazy-binder which
1255 ;; is a (CLOSURE module symbol) which, as a last resort, can provide
1256 ;; bindings that would otherwise not be found locally in the module.
1258 ;; NOTE: If you change anything here, you also need to change
1259 ;; libguile/modules.h.
1262 (make-record-type 'module
1263 '(obarray uses binder eval-closure transformer name kind
1264 duplicates-handlers import-obarray
1265 observers weak-observers)
1268 ;; make-module &opt size uses binder
1270 ;; Create a new module, perhaps with a particular size of obarray,
1271 ;; initial uses list, or binding procedure.
1276 (define (parse-arg index default)
1277 (if (> (length args) index)
1278 (list-ref args index)
1281 (define %default-import-size
1282 ;; Typical number of imported bindings actually used by a module.
1285 (if (> (length args) 3)
1286 (error "Too many args to make-module." args))
1288 (let ((size (parse-arg 0 31))
1289 (uses (parse-arg 1 '()))
1290 (binder (parse-arg 2 #f)))
1292 (if (not (integer? size))
1293 (error "Illegal size to make-module." size))
1294 (if (not (and (list? uses)
1295 (and-map module? uses)))
1296 (error "Incorrect use list." uses))
1297 (if (and binder (not (procedure? binder)))
1299 "Lazy-binder expected to be a procedure or #f." binder))
1301 (let ((module (module-constructor (make-hash-table size)
1302 uses binder #f %pre-modules-transformer
1304 (make-hash-table %default-import-size)
1306 (make-weak-key-hash-table 31))))
1308 ;; We can't pass this as an argument to module-constructor,
1309 ;; because we need it to close over a pointer to the module
1311 (set-module-eval-closure! module (standard-eval-closure module))
1315 (define module-constructor (record-constructor module-type))
1316 (define module-obarray (record-accessor module-type 'obarray))
1317 (define set-module-obarray! (record-modifier module-type 'obarray))
1318 (define module-uses (record-accessor module-type 'uses))
1319 (define set-module-uses! (record-modifier module-type 'uses))
1320 (define module-binder (record-accessor module-type 'binder))
1321 (define set-module-binder! (record-modifier module-type 'binder))
1323 ;; NOTE: This binding is used in libguile/modules.c.
1324 (define module-eval-closure (record-accessor module-type 'eval-closure))
1326 (define module-transformer (record-accessor module-type 'transformer))
1327 (define set-module-transformer! (record-modifier module-type 'transformer))
1328 ;; (define module-name (record-accessor module-type 'name)) wait until mods are booted
1329 (define set-module-name! (record-modifier module-type 'name))
1330 (define module-kind (record-accessor module-type 'kind))
1331 (define set-module-kind! (record-modifier module-type 'kind))
1332 (define module-duplicates-handlers
1333 (record-accessor module-type 'duplicates-handlers))
1334 (define set-module-duplicates-handlers!
1335 (record-modifier module-type 'duplicates-handlers))
1336 (define module-observers (record-accessor module-type 'observers))
1337 (define set-module-observers! (record-modifier module-type 'observers))
1338 (define module-weak-observers (record-accessor module-type 'weak-observers))
1339 (define module? (record-predicate module-type))
1341 (define module-import-obarray (record-accessor module-type 'import-obarray))
1343 (define set-module-eval-closure!
1344 (let ((setter (record-modifier module-type 'eval-closure)))
1345 (lambda (module closure)
1346 (setter module closure)
1347 ;; Make it possible to lookup the module from the environment.
1348 ;; This implementation is correct since an eval closure can belong
1349 ;; to maximally one module.
1350 (set-procedure-property! closure 'module module))))
1354 ;;; {Observer protocol}
1357 (define (module-observe module proc)
1358 (set-module-observers! module (cons proc (module-observers module)))
1361 (define (module-observe-weak module observer-id . proc)
1362 ;; Register PROC as an observer of MODULE under name OBSERVER-ID (which can
1363 ;; be any Scheme object). PROC is invoked and passed MODULE any time
1364 ;; MODULE is modified. PROC gets unregistered when OBSERVER-ID gets GC'd
1365 ;; (thus, it is never unregistered if OBSERVER-ID is an immediate value,
1368 ;; The two-argument version is kept for backward compatibility: when called
1369 ;; with two arguments, the observer gets unregistered when closure PROC
1370 ;; gets GC'd (making it impossible to use an anonymous lambda for PROC).
1372 (let ((proc (if (null? proc) observer-id (car proc))))
1373 (hashq-set! (module-weak-observers module) observer-id proc)))
1375 (define (module-unobserve token)
1376 (let ((module (car token))
1379 (hash-remove! (module-weak-observers module) id)
1380 (set-module-observers! module (delq1! id (module-observers module)))))
1383 (define module-defer-observers #f)
1384 (define module-defer-observers-mutex (make-mutex 'recursive))
1385 (define module-defer-observers-table (make-hash-table))
1387 (define (module-modified m)
1388 (if module-defer-observers
1389 (hash-set! module-defer-observers-table m #t)
1390 (module-call-observers m)))
1392 ;;; This function can be used to delay calls to observers so that they
1393 ;;; can be called once only in the face of massive updating of modules.
1395 (define (call-with-deferred-observers thunk)
1398 (lock-mutex module-defer-observers-mutex)
1399 (set! module-defer-observers #t))
1402 (set! module-defer-observers #f)
1403 (hash-for-each (lambda (m dummy)
1404 (module-call-observers m))
1405 module-defer-observers-table)
1406 (hash-clear! module-defer-observers-table)
1407 (unlock-mutex module-defer-observers-mutex))))
1409 (define (module-call-observers m)
1410 (for-each (lambda (proc) (proc m)) (module-observers m))
1412 ;; We assume that weak observers don't (un)register themselves as they are
1413 ;; called since this would preclude proper iteration over the hash table
1415 (hash-for-each (lambda (id proc) (proc m)) (module-weak-observers m)))
1419 ;;; {Module Searching in General}
1421 ;;; We sometimes want to look for properties of a symbol
1422 ;;; just within the obarray of one module. If the property
1423 ;;; holds, then it is said to hold ``locally'' as in, ``The symbol
1424 ;;; DISPLAY is locally rebound in the module `safe-guile'.''
1427 ;;; Other times, we want to test for a symbol property in the obarray
1428 ;;; of M and, if it is not found there, try each of the modules in the
1429 ;;; uses list of M. This is the normal way of testing for some
1430 ;;; property, so we state these properties without qualification as
1431 ;;; in: ``The symbol 'fnord is interned in module M because it is
1432 ;;; interned locally in module M2 which is a member of the uses list
1436 ;; module-search fn m
1438 ;; return the first non-#f result of FN applied to M and then to
1439 ;; the modules in the uses of m, and so on recursively. If all applications
1440 ;; return #f, then so does this function.
1442 (define (module-search fn m v)
1445 (or (module-search fn (car pos) v)
1448 (loop (module-uses m))))
1451 ;;; {Is a symbol bound in a module?}
1453 ;;; Symbol S in Module M is bound if S is interned in M and if the binding
1454 ;;; of S in M has been set to some well-defined value.
1457 ;; module-locally-bound? module symbol
1459 ;; Is a symbol bound (interned and defined) locally in a given module?
1461 (define (module-locally-bound? m v)
1462 (let ((var (module-local-variable m v)))
1464 (variable-bound? var))))
1466 ;; module-bound? module symbol
1468 ;; Is a symbol bound (interned and defined) anywhere in a given module
1471 (define (module-bound? m v)
1472 (let ((var (module-variable m v)))
1474 (variable-bound? var))))
1476 ;;; {Is a symbol interned in a module?}
1478 ;;; Symbol S in Module M is interned if S occurs in
1479 ;;; of S in M has been set to some well-defined value.
1481 ;;; It is possible to intern a symbol in a module without providing
1482 ;;; an initial binding for the corresponding variable. This is done
1484 ;;; (module-add! module symbol (make-undefined-variable))
1486 ;;; In that case, the symbol is interned in the module, but not
1487 ;;; bound there. The unbound symbol shadows any binding for that
1488 ;;; symbol that might otherwise be inherited from a member of the uses list.
1491 (define (module-obarray-get-handle ob key)
1492 ((if (symbol? key) hashq-get-handle hash-get-handle) ob key))
1494 (define (module-obarray-ref ob key)
1495 ((if (symbol? key) hashq-ref hash-ref) ob key))
1497 (define (module-obarray-set! ob key val)
1498 ((if (symbol? key) hashq-set! hash-set!) ob key val))
1500 (define (module-obarray-remove! ob key)
1501 ((if (symbol? key) hashq-remove! hash-remove!) ob key))
1503 ;; module-symbol-locally-interned? module symbol
1505 ;; is a symbol interned (not neccessarily defined) locally in a given module
1506 ;; or its uses? Interned symbols shadow inherited bindings even if
1507 ;; they are not themselves bound to a defined value.
1509 (define (module-symbol-locally-interned? m v)
1510 (not (not (module-obarray-get-handle (module-obarray m) v))))
1512 ;; module-symbol-interned? module symbol
1514 ;; is a symbol interned (not neccessarily defined) anywhere in a given module
1515 ;; or its uses? Interned symbols shadow inherited bindings even if
1516 ;; they are not themselves bound to a defined value.
1518 (define (module-symbol-interned? m v)
1519 (module-search module-symbol-locally-interned? m v))
1522 ;;; {Mapping modules x symbols --> variables}
1525 ;; module-local-variable module symbol
1526 ;; return the local variable associated with a MODULE and SYMBOL.
1528 ;;; This function is very important. It is the only function that can
1529 ;;; return a variable from a module other than the mutators that store
1530 ;;; new variables in modules. Therefore, this function is the location
1531 ;;; of the "lazy binder" hack.
1533 ;;; If symbol is defined in MODULE, and if the definition binds symbol
1534 ;;; to a variable, return that variable object.
1536 ;;; If the symbols is not found at first, but the module has a lazy binder,
1537 ;;; then try the binder.
1539 ;;; If the symbol is not found at all, return #f.
1541 ;;; (This is now written in C, see `modules.c'.)
1544 ;;; {Mapping modules x symbols --> bindings}
1546 ;;; These are similar to the mapping to variables, except that the
1547 ;;; variable is dereferenced.
1550 ;; module-symbol-binding module symbol opt-value
1552 ;; return the binding of a variable specified by name within
1553 ;; a given module, signalling an error if the variable is unbound.
1554 ;; If the OPT-VALUE is passed, then instead of signalling an error,
1555 ;; return OPT-VALUE.
1557 (define (module-symbol-local-binding m v . opt-val)
1558 (let ((var (module-local-variable m v)))
1559 (if (and var (variable-bound? var))
1561 (if (not (null? opt-val))
1563 (error "Locally unbound variable." v)))))
1565 ;; module-symbol-binding module symbol opt-value
1567 ;; return the binding of a variable specified by name within
1568 ;; a given module, signalling an error if the variable is unbound.
1569 ;; If the OPT-VALUE is passed, then instead of signalling an error,
1570 ;; return OPT-VALUE.
1572 (define (module-symbol-binding m v . opt-val)
1573 (let ((var (module-variable m v)))
1574 (if (and var (variable-bound? var))
1576 (if (not (null? opt-val))
1578 (error "Unbound variable." v)))))
1583 ;;; {Adding Variables to Modules}
1586 ;; module-make-local-var! module symbol
1588 ;; ensure a variable for V in the local namespace of M.
1589 ;; If no variable was already there, then create a new and uninitialzied
1592 ;; This function is used in modules.c.
1594 (define (module-make-local-var! m v)
1595 (or (let ((b (module-obarray-ref (module-obarray m) v)))
1598 ;; Mark as modified since this function is called when
1599 ;; the standard eval closure defines a binding
1603 ;; Create a new local variable.
1604 (let ((local-var (make-undefined-variable)))
1605 (module-add! m v local-var)
1608 ;; module-ensure-local-variable! module symbol
1610 ;; Ensure that there is a local variable in MODULE for SYMBOL. If
1611 ;; there is no binding for SYMBOL, create a new uninitialized
1612 ;; variable. Return the local variable.
1614 (define (module-ensure-local-variable! module symbol)
1615 (or (module-local-variable module symbol)
1616 (let ((var (make-undefined-variable)))
1617 (module-add! module symbol var)
1620 ;; module-add! module symbol var
1622 ;; ensure a particular variable for V in the local namespace of M.
1624 (define (module-add! m v var)
1625 (if (not (variable? var))
1626 (error "Bad variable to module-add!" var))
1627 (module-obarray-set! (module-obarray m) v var)
1628 (module-modified m))
1632 ;; make sure that a symbol is undefined in the local namespace of M.
1634 (define (module-remove! m v)
1635 (module-obarray-remove! (module-obarray m) v)
1636 (module-modified m))
1638 (define (module-clear! m)
1639 (hash-clear! (module-obarray m))
1640 (module-modified m))
1642 ;; MODULE-FOR-EACH -- exported
1644 ;; Call PROC on each symbol in MODULE, with arguments of (SYMBOL VARIABLE).
1646 (define (module-for-each proc module)
1647 (hash-for-each proc (module-obarray module)))
1649 (define (module-map proc module)
1650 (hash-map->list proc (module-obarray module)))
1654 ;;; {Low Level Bootstrapping}
1659 ;; A root module uses the pre-modules-obarray as its obarray. This
1660 ;; special obarray accumulates all bindings that have been established
1661 ;; before the module system is fully booted.
1663 ;; (The obarray continues to be used by code that has been closed over
1664 ;; before the module system has been booted.)
1666 (define (make-root-module)
1667 (let ((m (make-module 0)))
1668 (set-module-obarray! m (%get-pre-modules-obarray))
1673 ;; The root interface is a module that uses the same obarray as the
1674 ;; root module. It does not allow new definitions, tho.
1676 (define (make-scm-module)
1677 (let ((m (make-module 0)))
1678 (set-module-obarray! m (%get-pre-modules-obarray))
1679 (set-module-eval-closure! m (standard-interface-eval-closure m))
1685 ;;; {Module-based Loading}
1688 (define (save-module-excursion thunk)
1689 (let ((inner-module (current-module))
1691 (dynamic-wind (lambda ()
1692 (set! outer-module (current-module))
1693 (set-current-module inner-module)
1694 (set! inner-module #f))
1697 (set! inner-module (current-module))
1698 (set-current-module outer-module)
1699 (set! outer-module #f)))))
1701 (define basic-load load)
1703 (define (load-module filename . reader)
1704 (save-module-excursion
1706 (let ((oldname (and (current-load-port)
1707 (port-filename (current-load-port)))))
1710 (> (string-length filename) 0)
1711 (not (char=? (string-ref filename 0) #\/))
1712 (not (string=? (dirname oldname) ".")))
1713 (string-append (dirname oldname) "/" filename)
1720 ;;; {MODULE-REF -- exported}
1723 ;; Returns the value of a variable called NAME in MODULE or any of its
1724 ;; used modules. If there is no such variable, then if the optional third
1725 ;; argument DEFAULT is present, it is returned; otherwise an error is signaled.
1727 (define (module-ref module name . rest)
1728 (let ((variable (module-variable module name)))
1729 (if (and variable (variable-bound? variable))
1730 (variable-ref variable)
1732 (error "No variable named" name 'in module)
1733 (car rest) ; default value
1736 ;; MODULE-SET! -- exported
1738 ;; Sets the variable called NAME in MODULE (or in a module that MODULE uses)
1739 ;; to VALUE; if there is no such variable, an error is signaled.
1741 (define (module-set! module name value)
1742 (let ((variable (module-variable module name)))
1744 (variable-set! variable value)
1745 (error "No variable named" name 'in module))))
1747 ;; MODULE-DEFINE! -- exported
1749 ;; Sets the variable called NAME in MODULE to VALUE; if there is no such
1750 ;; variable, it is added first.
1752 (define (module-define! module name value)
1753 (let ((variable (module-local-variable module name)))
1756 (variable-set! variable value)
1757 (module-modified module))
1758 (let ((variable (make-variable value)))
1759 (module-add! module name variable)))))
1761 ;; MODULE-DEFINED? -- exported
1763 ;; Return #t iff NAME is defined in MODULE (or in a module that MODULE
1766 (define (module-defined? module name)
1767 (let ((variable (module-variable module name)))
1768 (and variable (variable-bound? variable))))
1770 ;; MODULE-USE! module interface
1772 ;; Add INTERFACE to the list of interfaces used by MODULE.
1774 (define (module-use! module interface)
1775 (if (not (or (eq? module interface)
1776 (memq interface (module-uses module))))
1778 ;; Newly used modules must be appended rather than consed, so that
1779 ;; `module-variable' traverses the use list starting from the first
1781 (set-module-uses! module
1782 (append (filter (lambda (m)
1784 (equal? (module-name m)
1785 (module-name interface))))
1786 (module-uses module))
1789 (module-modified module))))
1791 ;; MODULE-USE-INTERFACES! module interfaces
1793 ;; Same as MODULE-USE! but add multiple interfaces and check for duplicates
1795 (define (module-use-interfaces! module interfaces)
1796 (set-module-uses! module
1797 (append (module-uses module) interfaces))
1798 (module-modified module))
1802 ;;; {Recursive Namespaces}
1804 ;;; A hierarchical namespace emerges if we consider some module to be
1805 ;;; root, and variables bound to modules as nested namespaces.
1807 ;;; The routines in this file manage variable names in hierarchical namespace.
1808 ;;; Each variable name is a list of elements, looked up in successively nested
1811 ;;; (nested-ref some-root-module '(foo bar baz))
1812 ;;; => <value of a variable named baz in the module bound to bar in
1813 ;;; the module bound to foo in some-root-module>
1818 ;;; ;; a-root is a module
1819 ;;; ;; name is a list of symbols
1821 ;;; nested-ref a-root name
1822 ;;; nested-set! a-root name val
1823 ;;; nested-define! a-root name val
1824 ;;; nested-remove! a-root name
1827 ;;; (current-module) is a natural choice for a-root so for convenience there are
1830 ;;; local-ref name == nested-ref (current-module) name
1831 ;;; local-set! name val == nested-set! (current-module) name val
1832 ;;; local-define! name val == nested-define! (current-module) name val
1833 ;;; local-remove! name == nested-remove! (current-module) name
1837 (define (nested-ref root names)
1838 (let loop ((cur root)
1842 ((not (module? cur)) #f)
1843 (else (loop (module-ref cur (car elts) #f) (cdr elts))))))
1845 (define (nested-set! root names val)
1846 (let loop ((cur root)
1848 (if (null? (cdr elts))
1849 (module-set! cur (car elts) val)
1850 (loop (module-ref cur (car elts)) (cdr elts)))))
1852 (define (nested-define! root names val)
1853 (let loop ((cur root)
1855 (if (null? (cdr elts))
1856 (module-define! cur (car elts) val)
1857 (loop (module-ref cur (car elts)) (cdr elts)))))
1859 (define (nested-remove! root names)
1860 (let loop ((cur root)
1862 (if (null? (cdr elts))
1863 (module-remove! cur (car elts))
1864 (loop (module-ref cur (car elts)) (cdr elts)))))
1866 (define (local-ref names) (nested-ref (current-module) names))
1867 (define (local-set! names val) (nested-set! (current-module) names val))
1868 (define (local-define names val) (nested-define! (current-module) names val))
1869 (define (local-remove names) (nested-remove! (current-module) names))
1874 ;;; {The (%app) module}
1876 ;;; The root of conventionally named objects not directly in the top level.
1879 ;;; (%app modules guile)
1881 ;;; The directory of all modules and the standard root module.
1884 ;; module-public-interface is defined in C.
1885 (define (set-module-public-interface! m i)
1886 (module-define! m '%module-public-interface i))
1887 (define (set-system-module! m s)
1888 (set-procedure-property! (module-eval-closure m) 'system-module s))
1889 (define the-root-module (make-root-module))
1890 (define the-scm-module (make-scm-module))
1891 (set-module-public-interface! the-root-module the-scm-module)
1892 (set-module-name! the-root-module '(guile))
1893 (set-module-name! the-scm-module '(guile))
1894 (set-module-kind! the-scm-module 'interface)
1895 (set-system-module! the-root-module #t)
1896 (set-system-module! the-scm-module #t)
1898 ;; NOTE: This binding is used in libguile/modules.c.
1900 (define (make-modules-in module name)
1904 (let* ((var (module-local-variable module (car name)))
1905 (val (and var (variable-bound? var) (variable-ref var))))
1908 (let ((m (make-module 31)))
1909 (set-module-kind! m 'directory)
1910 (set-module-name! m (append (module-name module)
1912 (module-define! module (car name) m)
1916 (define (beautify-user-module! module)
1917 (let ((interface (module-public-interface module)))
1918 (if (or (not interface)
1919 (eq? interface module))
1920 (let ((interface (make-module 31)))
1921 (set-module-name! interface (module-name module))
1922 (set-module-kind! interface 'interface)
1923 (set-module-public-interface! module interface))))
1924 (if (and (not (memq the-scm-module (module-uses module)))
1925 (not (eq? module the-root-module)))
1926 ;; Import the default set of bindings (from the SCM module) in MODULE.
1927 (module-use! module the-scm-module)))
1929 ;; NOTE: This binding is used in libguile/modules.c.
1931 (define resolve-module
1932 (let ((the-root-module the-root-module))
1933 (lambda (name . maybe-autoload)
1934 (if (equal? name '(guile))
1936 (let ((full-name (append '(%app modules) name)))
1937 (let ((already (nested-ref the-root-module full-name))
1938 (autoload (or (null? maybe-autoload) (car maybe-autoload))))
1940 ((and already (module? already)
1941 (or (not autoload) (module-public-interface already)))
1942 ;; A hit, a palpable hit.
1945 ;; Try to autoload the module, and recurse.
1946 (try-load-module name)
1947 (resolve-module name #f))
1949 ;; A module is not bound (but maybe something else is),
1950 ;; we're not autoloading -- here's the weird semantics,
1951 ;; we create an empty module.
1952 (make-modules-in the-root-module full-name)))))))))
1954 ;; Cheat. These bindings are needed by modules.c, but we don't want
1955 ;; to move their real definition here because that would be unnatural.
1957 (define try-module-autoload #f)
1958 (define process-define-module #f)
1959 (define process-use-modules #f)
1960 (define module-export! #f)
1961 (define default-duplicate-binding-procedures #f)
1963 (define %app (make-module 31))
1964 (set-module-name! %app '(%app))
1965 (define app %app) ;; for backwards compatability
1967 (let ((m (make-module 31)))
1968 (set-module-name! m '())
1969 (local-define '(%app modules) m))
1970 (local-define '(%app modules guile) the-root-module)
1972 ;; This boots the module system. All bindings needed by modules.c
1973 ;; must have been defined by now.
1975 (set-current-module the-root-module)
1976 ;; definition deferred for syncase's benefit.
1978 (let ((accessor (record-accessor module-type 'name)))
1982 (set-module-name! mod (list (gensym)))
1985 ;; (define-special-value '(%app modules new-ws) (lambda () (make-scm-module)))
1987 (define (try-load-module name)
1988 (try-module-autoload name))
1990 (define (purify-module! module)
1991 "Removes bindings in MODULE which are inherited from the (guile) module."
1992 (let ((use-list (module-uses module)))
1993 (if (and (pair? use-list)
1994 (eq? (car (last-pair use-list)) the-scm-module))
1995 (set-module-uses! module (reverse (cdr (reverse use-list)))))))
1997 ;; Return a module that is an interface to the module designated by
2000 ;; `resolve-interface' takes four keyword arguments:
2002 ;; #:select SELECTION
2004 ;; SELECTION is a list of binding-specs to be imported; A binding-spec
2005 ;; is either a symbol or a pair of symbols (ORIG . SEEN), where ORIG
2006 ;; is the name in the used module and SEEN is the name in the using
2007 ;; module. Note that SEEN is also passed through RENAMER, below. The
2008 ;; default is to select all bindings. If you specify no selection but
2009 ;; a renamer, only the bindings that already exist in the used module
2010 ;; are made available in the interface. Bindings that are added later
2011 ;; are not picked up.
2015 ;; BINDINGS is a list of bindings which should not be imported.
2019 ;; PREFIX is a symbol that will be appended to each exported name.
2020 ;; The default is to not perform any renaming.
2022 ;; #:renamer RENAMER
2024 ;; RENAMER is a procedure that takes a symbol and returns its new
2025 ;; name. The default is not perform any renaming.
2027 ;; Signal "no code for module" error if module name is not resolvable
2028 ;; or its public interface is not available. Signal "no binding"
2029 ;; error if selected binding does not exist in the used module.
2031 (define (resolve-interface name . args)
2033 (define (get-keyword-arg args kw def)
2034 (cond ((memq kw args)
2036 (if (null? (cdr kw-arg))
2037 (error "keyword without value: " kw))
2042 (let* ((select (get-keyword-arg args #:select #f))
2043 (hide (get-keyword-arg args #:hide '()))
2044 (renamer (or (get-keyword-arg args #:renamer #f)
2045 (let ((prefix (get-keyword-arg args #:prefix #f)))
2046 (and prefix (symbol-prefix-proc prefix)))
2048 (module (resolve-module name))
2049 (public-i (and module (module-public-interface module))))
2050 (and (or (not module) (not public-i))
2051 (error "no code for module" name))
2052 (if (and (not select) (null? hide) (eq? renamer identity))
2054 (let ((selection (or select (module-map (lambda (sym var) sym)
2056 (custom-i (make-module 31)))
2057 (set-module-kind! custom-i 'custom-interface)
2058 (set-module-name! custom-i name)
2059 ;; XXX - should use a lazy binder so that changes to the
2060 ;; used module are picked up automatically.
2061 (for-each (lambda (bspec)
2062 (let* ((direct? (symbol? bspec))
2063 (orig (if direct? bspec (car bspec)))
2064 (seen (if direct? bspec (cdr bspec)))
2065 (var (or (module-local-variable public-i orig)
2066 (module-local-variable module orig)
2068 ;; fixme: format manually for now
2070 #f "no binding `~A' in module ~A"
2072 (if (memq orig hide)
2073 (set! hide (delq! orig hide))
2074 (module-add! custom-i
2078 ;; Check that we are not hiding bindings which don't exist
2079 (for-each (lambda (binding)
2080 (if (not (module-local-variable public-i binding))
2083 #f "no binding `~A' to hide in module ~A"
2088 (define (symbol-prefix-proc prefix)
2090 (symbol-append prefix symbol)))
2092 ;; This function is called from "modules.c". If you change it, be
2093 ;; sure to update "modules.c" as well.
2095 (define (process-define-module args)
2096 (let* ((module-id (car args))
2097 (module (resolve-module module-id #f))
2099 (unrecognized (lambda (arg)
2100 (error "unrecognized define-module argument" arg))))
2101 (beautify-user-module! module)
2102 (let loop ((kws kws)
2103 (reversed-interfaces '())
2110 (call-with-deferred-observers
2112 (module-use-interfaces! module (reverse reversed-interfaces))
2113 (module-export! module exports)
2114 (module-replace! module replacements)
2115 (module-re-export! module re-exports)
2116 (if (not (null? autoloads))
2117 (apply module-autoload! module autoloads))))
2119 ((#:use-module #:use-syntax)
2120 (or (pair? (cdr kws))
2123 ((equal? (caadr kws) '(ice-9 syncase))
2124 (issue-deprecation-warning
2125 "(ice-9 syncase) is deprecated. Support for syntax-case is now in Guile core.")
2133 (let* ((interface-args (cadr kws))
2134 (interface (apply resolve-interface interface-args)))
2135 (and (eq? (car kws) #:use-syntax)
2136 (or (symbol? (caar interface-args))
2137 (error "invalid module name for use-syntax"
2138 (car interface-args)))
2139 (set-module-transformer!
2141 (module-ref interface
2142 (car (last-pair (car interface-args)))
2145 (cons interface reversed-interfaces)
2151 (or (and (pair? (cdr kws)) (pair? (cddr kws)))
2158 (let ((name (cadr kws))
2159 (bindings (caddr kws)))
2160 (cons* name bindings autoloads))))
2162 (set-system-module! module #t)
2163 (loop (cdr kws) reversed-interfaces exports re-exports
2164 replacements autoloads))
2166 (purify-module! module)
2167 (loop (cdr kws) reversed-interfaces exports re-exports
2168 replacements autoloads))
2170 (if (not (pair? (cdr kws)))
2172 (set-module-duplicates-handlers!
2174 (lookup-duplicates-handlers (cadr kws)))
2175 (loop (cddr kws) reversed-interfaces exports re-exports
2176 replacements autoloads))
2177 ((#:export #:export-syntax)
2178 (or (pair? (cdr kws))
2182 (append (cadr kws) exports)
2186 ((#:re-export #:re-export-syntax)
2187 (or (pair? (cdr kws))
2192 (append (cadr kws) re-exports)
2195 ((#:replace #:replace-syntax)
2196 (or (pair? (cdr kws))
2202 (append (cadr kws) replacements)
2205 (unrecognized kws)))))
2206 (run-hook module-defined-hook module)
2209 ;; `module-defined-hook' is a hook that is run whenever a new module
2210 ;; is defined. Its members are called with one argument, the new
2212 (define module-defined-hook (make-hook 1))
2219 (define (make-autoload-interface module name bindings)
2220 (let ((b (lambda (a sym definep)
2221 (and (memq sym bindings)
2222 (let ((i (module-public-interface (resolve-module name))))
2224 (error "missing interface for module" name))
2225 (let ((autoload (memq a (module-uses module))))
2226 ;; Replace autoload-interface with actual interface if
2227 ;; that has not happened yet.
2228 (if (pair? autoload)
2229 (set-car! autoload i)))
2230 (module-local-variable i sym))))))
2231 (module-constructor (make-hash-table 0) '() b #f #f name 'autoload #f
2232 (make-hash-table 0) '() (make-weak-value-hash-table 31))))
2234 (define (module-autoload! module . args)
2235 "Have @var{module} automatically load the module named @var{name} when one
2236 of the symbols listed in @var{bindings} is looked up. @var{args} should be a
2237 list of module-name/binding-list pairs, e.g., as in @code{(module-autoload!
2238 module '(ice-9 q) '(make-q q-length))}."
2239 (let loop ((args args))
2243 (error "invalid name+binding autoload list" args))
2245 (let ((name (car args))
2246 (bindings (cadr args)))
2247 (module-use! module (make-autoload-interface module
2249 (loop (cddr args)))))))
2254 ;;; {Autoloading modules}
2257 (define autoloads-in-progress '())
2259 ;; This function is called from "modules.c". If you change it, be
2260 ;; sure to update "modules.c" as well.
2262 (define (try-module-autoload module-name)
2263 (let* ((reverse-name (reverse module-name))
2264 (name (symbol->string (car reverse-name)))
2265 (dir-hint-module-name (reverse (cdr reverse-name)))
2266 (dir-hint (apply string-append
2268 (string-append (symbol->string elt) "/"))
2269 dir-hint-module-name))))
2270 (resolve-module dir-hint-module-name #f)
2271 (and (not (autoload-done-or-in-progress? dir-hint name))
2274 (lambda () (autoload-in-progress! dir-hint name))
2276 (with-fluid* current-reader #f
2278 (save-module-excursion
2280 (primitive-load-path (in-vicinity dir-hint name) #f)
2281 (set! didit #t))))))
2282 (lambda () (set-autoloaded! dir-hint name didit)))
2287 ;;; {Dynamic linking of modules}
2290 (define autoloads-done '((guile . guile)))
2292 (define (autoload-done-or-in-progress? p m)
2293 (let ((n (cons p m)))
2294 (->bool (or (member n autoloads-done)
2295 (member n autoloads-in-progress)))))
2297 (define (autoload-done! p m)
2298 (let ((n (cons p m)))
2299 (set! autoloads-in-progress
2300 (delete! n autoloads-in-progress))
2301 (or (member n autoloads-done)
2302 (set! autoloads-done (cons n autoloads-done)))))
2304 (define (autoload-in-progress! p m)
2305 (let ((n (cons p m)))
2306 (set! autoloads-done
2307 (delete! n autoloads-done))
2308 (set! autoloads-in-progress (cons n autoloads-in-progress))))
2310 (define (set-autoloaded! p m done?)
2312 (autoload-done! p m)
2313 (let ((n (cons p m)))
2314 (set! autoloads-done (delete! n autoloads-done))
2315 (set! autoloads-in-progress (delete! n autoloads-in-progress)))))
2319 ;;; {Run-time options}
2322 (defmacro define-option-interface (option-group)
2323 (let* ((option-name car)
2325 (option-documentation caddr)
2327 ;; Below follow the macros defining the run-time option interfaces.
2329 (make-options (lambda (interface)
2331 (cond ((null? args) (,interface))
2333 (,interface (car args)) (,interface))
2336 (display (option-name option))
2337 (if (< (string-length
2338 (symbol->string (option-name option)))
2342 (display (option-value option))
2344 (display (option-documentation option))
2346 (,interface #t)))))))
2348 (make-enable (lambda (interface)
2350 (,interface (append flags (,interface)))
2353 (make-disable (lambda (interface)
2355 (let ((options (,interface)))
2356 (for-each (lambda (flag)
2357 (set! options (delq! flag options)))
2359 (,interface options)
2361 (let* ((interface (car option-group))
2362 (options/enable/disable (cadr option-group)))
2364 (define ,(car options/enable/disable)
2365 ,(make-options interface))
2366 (define ,(cadr options/enable/disable)
2367 ,(make-enable interface))
2368 (define ,(caddr options/enable/disable)
2369 ,(make-disable interface))
2370 (defmacro ,(caaddr option-group) (opt val)
2371 `(,',(car options/enable/disable)
2372 (append (,',(car options/enable/disable))
2373 (list ',opt ,val))))))))
2375 (define-option-interface
2376 (eval-options-interface
2377 (eval-options eval-enable eval-disable)
2380 (define-option-interface
2381 (debug-options-interface
2382 (debug-options debug-enable debug-disable)
2385 (define-option-interface
2386 (evaluator-traps-interface
2387 (traps trap-enable trap-disable)
2390 (define-option-interface
2391 (read-options-interface
2392 (read-options read-enable read-disable)
2395 (define-option-interface
2396 (print-options-interface
2397 (print-options print-enable print-disable)
2405 (define (repl read evaler print)
2406 (let loop ((source (read (current-input-port))))
2407 (print (evaler source))
2408 (loop (read (current-input-port)))))
2410 ;; A provisional repl that acts like the SCM repl:
2412 (define scm-repl-silent #f)
2413 (define (assert-repl-silence v) (set! scm-repl-silent v))
2415 (define *unspecified* (if #f #f))
2416 (define (unspecified? v) (eq? v *unspecified*))
2418 (define scm-repl-print-unspecified #f)
2419 (define (assert-repl-print-unspecified v) (set! scm-repl-print-unspecified v))
2421 (define scm-repl-verbose #f)
2422 (define (assert-repl-verbosity v) (set! scm-repl-verbose v))
2424 (define scm-repl-prompt "guile> ")
2426 (define (set-repl-prompt! v) (set! scm-repl-prompt v))
2428 (define (default-pre-unwind-handler key . args)
2430 (apply throw key args))
2433 (define (pre-unwind-handler-dispatch key . args)
2434 (apply default-pre-unwind-handler key args)))
2436 (define abort-hook (make-hook))
2438 ;; these definitions are used if running a script.
2439 ;; otherwise redefined in error-catching-loop.
2440 (define (set-batch-mode?! arg) #t)
2441 (define (batch-mode?) #t)
2443 (define (error-catching-loop thunk)
2446 (define (loop first)
2451 (call-with-unblocked-asyncs
2457 ;; This line is needed because mark
2458 ;; doesn't do closures quite right.
2459 ;; Unreferenced locals should be
2462 (let loop ((v (thunk)))
2466 (lambda (key . args)
2473 (apply throw 'switch-repl args))
2476 ;; This is one of the closures that require
2477 ;; (set! first #f) above
2480 (run-hook abort-hook)
2481 (force-output (current-output-port))
2482 (display "ABORT: " (current-error-port))
2483 (write args (current-error-port))
2484 (newline (current-error-port))
2488 (not has-shown-debugger-hint?)
2489 (not (memq 'backtrace
2490 (debug-options-interface)))
2491 (stack? (fluid-ref the-last-stack)))
2493 (newline (current-error-port))
2495 "Type \"(backtrace)\" to get more information or \"(debug)\" to enter the debugger.\n"
2496 (current-error-port))
2497 (set! has-shown-debugger-hint? #t)))
2498 (force-output (current-error-port)))
2500 (primitive-exit 1)))
2501 (set! stack-saved? #f)))
2504 ;; This is the other cons-leak closure...
2506 (cond ((= (length args) 4)
2507 (apply handle-system-error key args))
2509 (apply bad-throw key args)))))))
2511 default-pre-unwind-handler)))
2513 (if next (loop next) status)))
2514 (set! set-batch-mode?! (lambda (arg)
2516 (set! interactive #f)
2519 (error "sorry, not implemented")))))
2520 (set! batch-mode? (lambda () (not interactive)))
2521 (call-with-blocked-asyncs
2522 (lambda () (loop (lambda () #t))))))
2524 ;;(define the-last-stack (make-fluid)) Defined by scm_init_backtrace ()
2525 (define before-signal-stack (make-fluid))
2526 (define stack-saved? #f)
2528 (define (save-stack . narrowing)
2530 (cond ((not (memq 'debug (debug-options-interface)))
2531 (fluid-set! the-last-stack #f)
2532 (set! stack-saved? #t))
2538 (apply make-stack #t save-stack primitive-eval #t 0 narrowing))
2540 (apply make-stack #t save-stack 0 #t 0 narrowing))
2542 (apply make-stack #t save-stack tk-stack-mark #t 0 narrowing))
2544 (apply make-stack #t save-stack 0 1 narrowing))
2546 (let ((id (stack-id #t)))
2547 (and (procedure? id)
2548 (apply make-stack #t save-stack id #t 0 narrowing))))))
2549 (set! stack-saved? #t)))))
2551 (define before-error-hook (make-hook))
2552 (define after-error-hook (make-hook))
2553 (define before-backtrace-hook (make-hook))
2554 (define after-backtrace-hook (make-hook))
2556 (define has-shown-debugger-hint? #f)
2558 (define (handle-system-error key . args)
2559 (let ((cep (current-error-port)))
2560 (cond ((not (stack? (fluid-ref the-last-stack))))
2561 ((memq 'backtrace (debug-options-interface))
2562 (let ((highlights (if (or (eq? key 'wrong-type-arg)
2563 (eq? key 'out-of-range))
2566 (run-hook before-backtrace-hook)
2568 (display "Backtrace:\n")
2569 (display-backtrace (fluid-ref the-last-stack) cep
2572 (run-hook after-backtrace-hook))))
2573 (run-hook before-error-hook)
2574 (apply display-error (fluid-ref the-last-stack) cep args)
2575 (run-hook after-error-hook)
2577 (throw 'abort key)))
2579 (define (quit . args)
2580 (apply throw 'quit args))
2584 ;;(define has-shown-backtrace-hint? #f) Defined by scm_init_backtrace ()
2586 ;; Replaced by C code:
2587 ;;(define (backtrace)
2588 ;; (if (fluid-ref the-last-stack)
2591 ;; (display-backtrace (fluid-ref the-last-stack) (current-output-port))
2593 ;; (if (and (not has-shown-backtrace-hint?)
2594 ;; (not (memq 'backtrace (debug-options-interface))))
2597 ;;"Type \"(debug-enable 'backtrace)\" if you would like a backtrace
2598 ;;automatically if an error occurs in the future.\n")
2599 ;; (set! has-shown-backtrace-hint? #t))))
2600 ;; (display "No backtrace available.\n")))
2602 (define (error-catching-repl r e p)
2603 (error-catching-loop
2605 (call-with-values (lambda () (e (r)))
2606 (lambda the-values (for-each p the-values))))))
2608 (define (gc-run-time)
2609 (cdr (assq 'gc-time-taken (gc-stats))))
2611 (define before-read-hook (make-hook))
2612 (define after-read-hook (make-hook))
2613 (define before-eval-hook (make-hook 1))
2614 (define after-eval-hook (make-hook 1))
2615 (define before-print-hook (make-hook 1))
2616 (define after-print-hook (make-hook 1))
2618 ;;; The default repl-reader function. We may override this if we've
2619 ;;; the readline library.
2622 (display (if (string? prompt) prompt (prompt)))
2624 (run-hook before-read-hook)
2625 ((or (fluid-ref current-reader) read) (current-input-port))))
2627 (define (scm-style-repl)
2632 (repl-report-start-timing (lambda ()
2633 (set! start-gc-rt (gc-run-time))
2634 (set! start-rt (get-internal-run-time))))
2635 (repl-report (lambda ()
2637 (display (inexact->exact
2638 (* 1000 (/ (- (get-internal-run-time) start-rt)
2639 internal-time-units-per-second))))
2641 (display (inexact->exact
2642 (* 1000 (/ (- (gc-run-time) start-gc-rt)
2643 internal-time-units-per-second))))
2644 (display " msec in gc)\n")))
2646 (consume-trailing-whitespace
2648 (let ((ch (peek-char)))
2651 ((or (char=? ch #\space) (char=? ch #\tab))
2653 (consume-trailing-whitespace))
2654 ((char=? ch #\newline)
2658 (let ((prompt (cond ((string? scm-repl-prompt)
2660 ((thunk? scm-repl-prompt)
2662 (scm-repl-prompt "> ")
2664 (repl-reader prompt))))
2666 ;; As described in R4RS, the READ procedure updates the
2667 ;; port to point to the first character past the end of
2668 ;; the external representation of the object. This
2669 ;; means that it doesn't consume the newline typically
2670 ;; found after an expression. This means that, when
2671 ;; debugging Guile with GDB, GDB gets the newline, which
2672 ;; it often interprets as a "continue" command, making
2673 ;; breakpoints kind of useless. So, consume any
2674 ;; trailing newline here, as well as any whitespace
2676 ;; But not if EOF, for control-D.
2677 (if (not (eof-object? val))
2678 (consume-trailing-whitespace))
2679 (run-hook after-read-hook)
2680 (if (eof-object? val)
2682 (repl-report-start-timing)
2683 (if scm-repl-verbose
2686 (display ";;; EOF -- quitting")
2691 (-eval (lambda (sourc)
2692 (repl-report-start-timing)
2693 (run-hook before-eval-hook sourc)
2694 (let ((val (start-stack 'repl-stack
2695 ;; If you change this procedure
2696 ;; (primitive-eval), please also
2697 ;; modify the repl-stack case in
2698 ;; save-stack so that stack cutting
2699 ;; continues to work.
2700 (primitive-eval sourc))))
2701 (run-hook after-eval-hook sourc)
2705 (-print (let ((maybe-print (lambda (result)
2706 (if (or scm-repl-print-unspecified
2707 (not (unspecified? result)))
2712 (if (not scm-repl-silent)
2714 (run-hook before-print-hook result)
2715 (maybe-print result)
2716 (run-hook after-print-hook result)
2717 (if scm-repl-verbose
2721 (-quit (lambda (args)
2722 (if scm-repl-verbose
2724 (display ";;; QUIT executed, repl exitting")
2730 (if scm-repl-verbose
2732 (display ";;; ABORT executed.")
2735 (repl -read -eval -print))))
2737 (let ((status (error-catching-repl -read
2745 ;;; {IOTA functions: generating lists of numbers}
2749 (let loop ((count (1- n)) (result '()))
2750 (if (< count 0) result
2751 (loop (1- count) (cons count result)))))
2757 ;;; Similar to `begin' but returns a list of the results of all constituent
2758 ;;; forms instead of the result of the last form.
2759 ;;; (The definition relies on the current left-to-right
2760 ;;; order of evaluation of operands in applications.)
2763 (defmacro collect forms
2771 ;; with-fluids is a convenience wrapper for the builtin procedure
2772 ;; `with-fluids*'. The syntax is just like `let':
2774 ;; (with-fluids ((fluid val)
2778 (defmacro with-fluids (bindings . body)
2779 (let ((fluids (map car bindings))
2780 (values (map cadr bindings)))
2781 (if (and (= (length fluids) 1) (= (length values) 1))
2782 `(with-fluid* ,(car fluids) ,(car values) (lambda () ,@body))
2783 `(with-fluids* (list ,@fluids) (list ,@values)
2784 (lambda () ,@body)))))
2788 ;;; with `continue' and `break'.
2791 ;; The inner `do' loop avoids re-establishing a catch every iteration,
2792 ;; that's only necessary if continue is actually used. A new key is
2793 ;; generated every time, so break and continue apply to their originating
2794 ;; `while' even when recursing.
2796 ;; FIXME: This macro is unintentionally unhygienic with respect to let,
2797 ;; make-symbol, do, throw, catch, lambda, and not.
2799 (define-macro (while cond . body)
2800 (let ((keyvar (make-symbol "while-keyvar")))
2801 `(let ((,keyvar (make-symbol "while-key")))
2805 (let ((break (lambda () (throw ,keyvar #t)))
2806 (continue (lambda () (throw ,keyvar #f))))
2817 ;;; {Module System Macros}
2820 ;; Return a list of expressions that evaluate to the appropriate
2821 ;; arguments for resolve-interface according to SPEC.
2825 (if (memq 'prefix (read-options))
2826 (error "boot-9 must be compiled with #:kw, not :kw")))
2828 (define (compile-interface-spec spec)
2829 (define (make-keyarg sym key quote?)
2830 (cond ((or (memq sym spec)
2834 (list key (list 'quote (cadr rest)))
2835 (list key (cadr rest)))))
2838 (define (map-apply func list)
2839 (map (lambda (args) (apply func args)) list))
2842 '((:select #:select #t)
2844 (:prefix #:prefix #t)
2845 (:renamer #:renamer #f)))
2846 (if (not (pair? (car spec)))
2849 ,@(apply append (map-apply make-keyarg keys)))))
2851 (define (keyword-like-symbol->keyword sym)
2852 (symbol->keyword (string->symbol (substring (symbol->string sym) 1))))
2854 (define (compile-define-module-args args)
2855 ;; Just quote everything except #:use-module and #:use-syntax. We
2856 ;; need to know about all arguments regardless since we want to turn
2857 ;; symbols that look like keywords into real keywords, and the
2858 ;; keyword args in a define-module form are not regular
2859 ;; (i.e. no-backtrace doesn't take a value).
2860 (let loop ((compiled-args `((quote ,(car args))))
2863 (reverse! compiled-args))
2864 ;; symbol in keyword position
2865 ((symbol? (car args))
2867 (cons (keyword-like-symbol->keyword (car args)) (cdr args))))
2868 ((memq (car args) '(#:no-backtrace #:pure))
2869 (loop (cons (car args) compiled-args)
2872 (error "keyword without value:" (car args)))
2873 ((memq (car args) '(#:use-module #:use-syntax))
2874 (loop (cons* `(list ,@(compile-interface-spec (cadr args)))
2878 ((eq? (car args) #:autoload)
2879 (loop (cons* `(quote ,(caddr args))
2880 `(quote ,(cadr args))
2885 (loop (cons* `(quote ,(cadr args))
2890 (defmacro define-module args
2893 (let ((m (process-define-module
2894 (list ,@(compile-define-module-args args)))))
2895 (set-current-module m)
2898 ;; The guts of the use-modules macro. Add the interfaces of the named
2899 ;; modules to the use-list of the current module, in order.
2901 ;; This function is called by "modules.c". If you change it, be sure
2902 ;; to change scm_c_use_module as well.
2904 (define (process-use-modules module-interface-args)
2905 (let ((interfaces (map (lambda (mif-args)
2906 (or (apply resolve-interface mif-args)
2907 (error "no such module" mif-args)))
2908 module-interface-args)))
2909 (call-with-deferred-observers
2911 (module-use-interfaces! (current-module) interfaces)))))
2913 (defmacro use-modules modules
2916 (process-use-modules
2917 (list ,@(map (lambda (m)
2918 `(list ,@(compile-interface-spec m)))
2922 (defmacro use-syntax (spec)
2925 (issue-deprecation-warning
2926 "`use-syntax' is deprecated. Please contact guile-devel for more info.")
2927 (process-use-modules (list (list ,@(compile-interface-spec spec))))
2930 ;; Dirk:FIXME:: This incorrect (according to R5RS) syntax needs to be changed
2931 ;; as soon as guile supports hygienic macros.
2932 (define-syntax define-private
2937 (define-syntax define-public
2939 ((_ (name . args) . body)
2940 (define-public name (lambda args . body)))
2946 (define-syntax defmacro-public
2948 ((_ name args . body)
2950 (defmacro name args . body)
2951 (export-syntax name)))))
2953 ;; Export a local variable
2955 ;; This function is called from "modules.c". If you change it, be
2956 ;; sure to update "modules.c" as well.
2958 (define (module-export! m names)
2959 (let ((public-i (module-public-interface m)))
2960 (for-each (lambda (name)
2961 (let ((var (module-ensure-local-variable! m name)))
2962 (module-add! public-i name var)))
2965 (define (module-replace! m names)
2966 (let ((public-i (module-public-interface m)))
2967 (for-each (lambda (name)
2968 (let ((var (module-ensure-local-variable! m name)))
2969 (set-object-property! var 'replace #t)
2970 (module-add! public-i name var)))
2973 ;; Re-export a imported variable
2975 (define (module-re-export! m names)
2976 (let ((public-i (module-public-interface m)))
2977 (for-each (lambda (name)
2978 (let ((var (module-variable m name)))
2980 (error "Undefined variable:" name))
2981 ((eq? var (module-local-variable m name))
2982 (error "re-exporting local variable:" name))
2984 (module-add! public-i name var)))))
2987 (defmacro export names
2988 `(call-with-deferred-observers
2990 (module-export! (current-module) ',names))))
2992 (defmacro re-export names
2993 `(call-with-deferred-observers
2995 (module-re-export! (current-module) ',names))))
2997 (defmacro export-syntax names
3000 (defmacro re-export-syntax names
3001 `(re-export ,@names))
3003 (define load load-module)
3010 (define make-mutable-parameter
3011 (let ((make (lambda (fluid converter)
3015 (fluid-set! fluid (converter (car args))))))))
3016 (lambda (init . converter)
3017 (let ((fluid (make-fluid))
3018 (converter (if (null? converter)
3021 (fluid-set! fluid (converter init))
3022 (make fluid converter)))))
3026 ;;; {Handling of duplicate imported bindings}
3029 ;; Duplicate handlers take the following arguments:
3031 ;; module importing module
3032 ;; name conflicting name
3033 ;; int1 old interface where name occurs
3034 ;; val1 value of binding in old interface
3035 ;; int2 new interface where name occurs
3036 ;; val2 value of binding in new interface
3037 ;; var previous resolution or #f
3038 ;; val value of previous resolution
3040 ;; A duplicate handler can take three alternative actions:
3042 ;; 1. return #f => leave responsibility to next handler
3043 ;; 2. exit with an error
3044 ;; 3. return a variable resolving the conflict
3047 (define duplicate-handlers
3048 (let ((m (make-module 7)))
3050 (define (check module name int1 val1 int2 val2 var val)
3051 (scm-error 'misc-error
3053 "~A: `~A' imported from both ~A and ~A"
3054 (list (module-name module)
3060 (define (warn module name int1 val1 int2 val2 var val)
3061 (format (current-error-port)
3062 "WARNING: ~A: `~A' imported from both ~A and ~A\n"
3063 (module-name module)
3069 (define (replace module name int1 val1 int2 val2 var val)
3070 (let ((old (or (and var (object-property var 'replace) var)
3071 (module-variable int1 name)))
3072 (new (module-variable int2 name)))
3073 (if (object-property old 'replace)
3074 (and (or (eq? old new)
3075 (not (object-property new 'replace)))
3077 (and (object-property new 'replace)
3080 (define (warn-override-core module name int1 val1 int2 val2 var val)
3081 (and (eq? int1 the-scm-module)
3083 (format (current-error-port)
3084 "WARNING: ~A: imported module ~A overrides core binding `~A'\n"
3085 (module-name module)
3088 (module-local-variable int2 name))))
3090 (define (first module name int1 val1 int2 val2 var val)
3091 (or var (module-local-variable int1 name)))
3093 (define (last module name int1 val1 int2 val2 var val)
3094 (module-local-variable int2 name))
3096 (define (noop module name int1 val1 int2 val2 var val)
3099 (set-module-name! m 'duplicate-handlers)
3100 (set-module-kind! m 'interface)
3101 (module-define! m 'check check)
3102 (module-define! m 'warn warn)
3103 (module-define! m 'replace replace)
3104 (module-define! m 'warn-override-core warn-override-core)
3105 (module-define! m 'first first)
3106 (module-define! m 'last last)
3107 (module-define! m 'merge-generics noop)
3108 (module-define! m 'merge-accessors noop)
3111 (define (lookup-duplicates-handlers handler-names)
3113 (map (lambda (handler-name)
3114 (or (module-symbol-local-binding
3115 duplicate-handlers handler-name #f)
3116 (error "invalid duplicate handler name:"
3118 (if (list? handler-names)
3120 (list handler-names)))))
3122 (define default-duplicate-binding-procedures
3123 (make-mutable-parameter #f))
3125 (define default-duplicate-binding-handler
3126 (make-mutable-parameter '(replace warn-override-core warn last)
3127 (lambda (handler-names)
3128 (default-duplicate-binding-procedures
3129 (lookup-duplicates-handlers handler-names))
3134 ;;; {`cond-expand' for SRFI-0 support.}
3136 ;;; This syntactic form expands into different commands or
3137 ;;; definitions, depending on the features provided by the Scheme
3143 ;;; --> (cond-expand <cond-expand-clause>+)
3144 ;;; | (cond-expand <cond-expand-clause>* (else <command-or-definition>))
3145 ;;; <cond-expand-clause>
3146 ;;; --> (<feature-requirement> <command-or-definition>*)
3147 ;;; <feature-requirement>
3148 ;;; --> <feature-identifier>
3149 ;;; | (and <feature-requirement>*)
3150 ;;; | (or <feature-requirement>*)
3151 ;;; | (not <feature-requirement>)
3152 ;;; <feature-identifier>
3153 ;;; --> <a symbol which is the name or alias of a SRFI>
3155 ;;; Additionally, this implementation provides the
3156 ;;; <feature-identifier>s `guile' and `r5rs', so that programs can
3157 ;;; determine the implementation type and the supported standard.
3159 ;;; Currently, the following feature identifiers are supported:
3161 ;;; guile r5rs srfi-0 srfi-4 srfi-6 srfi-13 srfi-14 srfi-55 srfi-61
3163 ;;; Remember to update the features list when adding more SRFIs.
3166 (define %cond-expand-features
3167 ;; Adjust the above comment when changing this.
3170 srfi-0 ;; cond-expand itself
3171 srfi-4 ;; homogenous numeric vectors
3172 srfi-6 ;; open-input-string etc, in the guile core
3173 srfi-13 ;; string library
3174 srfi-14 ;; character sets
3175 srfi-55 ;; require-extension
3176 srfi-61 ;; general cond clause
3179 ;; This table maps module public interfaces to the list of features.
3181 (define %cond-expand-table (make-hash-table 31))
3183 ;; Add one or more features to the `cond-expand' feature list of the
3186 (define (cond-expand-provide module features)
3187 (let ((mod (module-public-interface module)))
3189 (hashq-set! %cond-expand-table mod
3190 (append (hashq-ref %cond-expand-table mod '())
3194 (procedure->memoizing-macro
3196 (let ((clauses (cdr exp))
3197 (syntax-error (lambda (cl)
3198 (error "invalid clause in `cond-expand'" cl))))
3204 (or (memq clause %cond-expand-features)
3205 (let lp ((uses (module-uses (env-module env))))
3208 (hashq-ref %cond-expand-table
3214 ((eq? 'and (car clause))
3215 (let lp ((l (cdr clause)))
3219 (and (test-clause (car l)) (lp (cdr l))))
3221 (syntax-error clause)))))
3222 ((eq? 'or (car clause))
3223 (let lp ((l (cdr clause)))
3227 (or (test-clause (car l)) (lp (cdr l))))
3229 (syntax-error clause)))))
3230 ((eq? 'not (car clause))
3231 (cond ((not (pair? (cdr clause)))
3232 (syntax-error clause))
3233 ((pair? (cddr clause))
3234 ((syntax-error clause))))
3235 (not (test-clause (cadr clause))))
3237 (syntax-error clause))))
3239 (syntax-error clause))))))
3240 (let lp ((c clauses))
3243 (error "Unfulfilled `cond-expand'"))
3246 ((not (pair? (car c)))
3247 (syntax-error (car c)))
3248 ((test-clause (caar c))
3249 `(begin ,@(cdar c)))
3250 ((eq? (caar c) 'else)
3253 `(begin ,@(cdar c)))
3255 (lp (cdr c))))))))))
3257 ;; This procedure gets called from the startup code with a list of
3258 ;; numbers, which are the numbers of the SRFIs to be loaded on startup.
3260 (define (use-srfis srfis)
3261 (process-use-modules
3263 (list (list 'srfi (string->symbol
3264 (string-append "srfi-" (number->string num))))))
3269 ;;; srfi-55: require-extension
3272 (define-macro (require-extension extension-spec)
3273 ;; This macro only handles the srfi extension, which, at present, is
3274 ;; the only one defined by the standard.
3275 (if (not (pair? extension-spec))
3276 (scm-error 'wrong-type-arg "require-extension"
3277 "Not an extension: ~S" (list extension-spec) #f))
3278 (let ((extension (car extension-spec))
3279 (extension-args (cdr extension-spec)))
3282 (let ((use-list '()))
3285 (if (not (integer? i))
3286 (scm-error 'wrong-type-arg "require-extension"
3287 "Invalid srfi name: ~S" (list i) #f))
3288 (let ((srfi-sym (string->symbol
3289 (string-append "srfi-" (number->string i)))))
3290 (if (not (memq srfi-sym %cond-expand-features))
3291 (set! use-list (cons `(use-modules (srfi ,srfi-sym))
3294 (if (pair? use-list)
3295 ;; i.e. (begin (use-modules x) (use-modules y) (use-modules z))
3296 `(begin ,@(reverse! use-list)))))
3299 'wrong-type-arg "require-extension"
3300 "Not a recognized extension type: ~S" (list extension) #f)))))
3304 ;;; {Load emacs interface support if emacs option is given.}
3307 (define (named-module-use! user usee)
3308 (module-use! (resolve-module user) (resolve-interface usee)))
3310 (define (load-emacs-interface)
3311 (and (provided? 'debug-extensions)
3312 (debug-enable 'backtrace))
3313 (named-module-use! '(guile-user) '(ice-9 emacs)))
3317 (define using-readline?
3318 (let ((using-readline? (make-fluid)))
3319 (make-procedure-with-setter
3320 (lambda () (fluid-ref using-readline?))
3321 (lambda (v) (fluid-set! using-readline? v)))))
3324 (let ((guile-user-module (resolve-module '(guile-user))))
3326 ;; Load emacs interface support if emacs option is given.
3327 (if (and (module-defined? guile-user-module 'use-emacs-interface)
3328 (module-ref guile-user-module 'use-emacs-interface))
3329 (load-emacs-interface))
3331 ;; Use some convenient modules (in reverse order)
3333 (set-current-module guile-user-module)
3334 (process-use-modules
3339 (if (provided? 'regex)
3342 (if (provided? 'threads)
3343 '(((ice-9 threads)))
3345 ;; load debugger on demand
3346 (module-autoload! guile-user-module '(ice-9 debugger) '(debug))
3348 ;; Note: SIGFPE, SIGSEGV and SIGBUS are actually "query-only" (see
3349 ;; scmsigs.c scm_sigaction_for_thread), so the handlers setup here have
3351 (let ((old-handlers #f)
3352 (start-repl (module-ref (resolve-interface '(system repl repl))
3354 (signals (if (provided? 'posix)
3355 `((,SIGINT . "User interrupt")
3356 (,SIGFPE . "Arithmetic error")
3358 . "Bad memory access (Segmentation violation)"))
3360 ;; no SIGBUS on mingw
3361 (if (defined? 'SIGBUS)
3362 (set! signals (acons SIGBUS "Bad memory access (bus error)"
3369 (let ((make-handler (lambda (msg)
3371 ;; Make a backup copy of the stack
3372 (fluid-set! before-signal-stack
3373 (fluid-ref the-last-stack))
3381 (map (lambda (sig-msg)
3382 (sigaction (car sig-msg)
3383 (make-handler (cdr sig-msg))))
3386 ;; the protected thunk.
3388 (let ((status (start-repl 'scheme)))
3389 (run-hook exit-hook)
3394 (map (lambda (sig-msg old-handler)
3395 (if (not (car old-handler))
3396 ;; restore original C handler.
3397 (sigaction (car sig-msg) #f)
3398 ;; restore Scheme handler, SIG_IGN or SIG_DFL.
3399 (sigaction (car sig-msg)
3401 (cdr old-handler))))
3402 signals old-handlers))))))
3404 ;;; This hook is run at the very end of an interactive session.
3406 (define exit-hook (make-hook))
3410 ;;; {Deprecated stuff}
3414 (define (feature? sym)
3415 (issue-deprecation-warning
3416 "`feature?' is deprecated. Use `provided?' instead.")
3420 (primitive-load-path "ice-9/deprecated"))
3424 ;;; Place the user in the guile-user module.
3427 ;;; FIXME: annotate ?
3428 ;; (define (syncase exp)
3429 ;; (with-fluids ((expansion-eval-closure
3430 ;; (module-eval-closure (current-module))))
3431 ;; (deannotate/source-properties (sc-expand (annotate exp)))))
3433 (define-module (guile-user)
3434 #:autoload (system base compile) (compile))
3436 ;;; boot-9.scm ends here