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 (define (void) (if #f #f))
38 ;; Before compiling, make sure any symbols are resolved in the (guile)
39 ;; module, the primary location of those symbols, rather than in
40 ;; (guile-user), the default module that we compile in.
43 (set-current-module (resolve-module '(guile))))
48 (primitive-load-path "ice-9/r4rs")
52 ;;; {Simple Debugging Tools}
55 ;; peek takes any number of arguments, writes them to the
56 ;; current ouput port, and returns the last argument.
57 ;; It is handy to wrap around an expression to look at
58 ;; a value each time is evaluated, e.g.:
60 ;; (+ 10 (troublesome-fn))
61 ;; => (+ 10 (pk 'troublesome-fn-returned (troublesome-fn)))
64 (define (peek . stuff)
69 (car (last-pair stuff)))
73 (define (warn . stuff)
74 (with-output-to-port (current-error-port)
77 (display ";;; WARNING ")
80 (car (last-pair stuff)))))
88 (if (not (memq sym *features*))
89 (set! *features* (cons sym *features*))))
91 ;; Return #t iff FEATURE is available to this Guile interpreter. In SLIB,
92 ;; provided? also checks to see if the module is available. We should do that
95 (define (provided? feature)
96 (and (memq feature *features*) #t))
98 ;; let format alias simple-format until the more complete version is loaded
100 (define format simple-format)
102 ;; this is scheme wrapping the C code so the final pred call is a tail call,
104 (define (string-any char_pred s . rest)
105 (let ((start (if (null? rest)
107 (end (if (or (null? rest) (null? (cdr rest)))
108 (string-length s) (cadr rest))))
109 (if (and (procedure? char_pred)
111 (<= end (string-length s))) ;; let c-code handle range error
112 (or (string-any-c-code char_pred s start (1- end))
113 (char_pred (string-ref s (1- end))))
114 (string-any-c-code char_pred s start end))))
116 ;; this is scheme wrapping the C code so the final pred call is a tail call,
118 (define (string-every char_pred s . rest)
119 (let ((start (if (null? rest)
121 (end (if (or (null? rest) (null? (cdr rest)))
122 (string-length s) (cadr rest))))
123 (if (and (procedure? char_pred)
125 (<= end (string-length s))) ;; let c-code handle range error
126 (and (string-every-c-code char_pred s start (1- end))
127 (char_pred (string-ref s (1- end))))
128 (string-every-c-code char_pred s start end))))
130 ;; A variant of string-fill! that we keep for compatability
132 (define (substring-fill! str start end fill)
133 (string-fill! str fill start end))
137 ;; Before the module system boots, there are no module names. But
138 ;; psyntax does want a module-name definition, so give it one.
139 (define (module-name x)
141 (define (module-add! module sym var)
142 (hashq-set! (%get-pre-modules-obarray) sym var))
143 (define sc-macro 'sc-macro)
144 (define (make-module-ref mod var kind)
146 ((public) (if mod `(@ ,mod ,var) var))
147 ((private) (if (and mod (not (equal? mod (module-name (current-module)))))
151 ((hygiene) (if (and mod
152 (not (equal? mod (module-name (current-module))))
153 (module-variable (resolve-module mod) var))
156 (else (error "foo" mod var kind))))
157 (define (resolve-module . args)
160 (define sc-expand #f)
161 (define sc-expand3 #f)
163 (define install-global-transformer #f)
164 (define syntax-dispatch #f)
165 (define syntax-error #f)
166 (define (annotation? x) #f)
168 (define bound-identifier=? #f)
169 (define datum->syntax-object #f)
170 (define free-identifier=? #f)
171 (define generate-temporaries #f)
172 (define identifier? #f)
173 (define syntax-object->datum #f)
176 (lambda (f first . rest)
179 (let andmap ((first first))
180 (let ((x (car first)) (first (cdr first)))
183 (and (f x) (andmap first)))))
184 (let andmap ((first first) (rest rest))
185 (let ((x (car first))
188 (rest (map cdr rest)))
190 (apply f (cons x xr))
191 (and (apply f (cons x xr)) (andmap first rest)))))))))
193 (define (syncase-error who format-string why what)
194 (%start-stack 'syncase-stack
196 (scm-error 'misc-error who "~A ~S" (list why what) '()))))
198 ;; Until the module system is booted, this will be the current expander.
199 (primitive-load-path "ice-9/psyntax-pp")
201 (define %pre-modules-transformer sc-expand)
207 ;;; Depends on: features, eval-case
210 (define-syntax define-macro
213 ((_ (macro . args) . body)
214 (syntax (define-macro macro (lambda args . body))))
215 ((_ macro transformer)
221 (let ((v (syntax-object->datum (syntax args))))
222 (datum->syntax-object y (apply transformer v))))))))))))
224 (define-syntax defmacro
227 ((_ macro args . body)
228 (syntax (define-macro macro (lambda args . body)))))))
236 ;;; Depends on: defmacro
239 (defmacro begin-deprecated forms
240 (if (include-deprecated-features)
246 ;;; {Trivial Functions}
249 (define (identity x) x)
250 (define (and=> value procedure) (and value (procedure value)))
251 (define call/cc call-with-current-continuation)
253 ;;; apply-to-args is functionally redundant with apply and, worse,
254 ;;; is less general than apply since it only takes two arguments.
256 ;;; On the other hand, apply-to-args is a syntacticly convenient way to
257 ;;; perform binding in many circumstances when the "let" family of
258 ;;; of forms don't cut it. E.g.:
260 ;;; (apply-to-args (return-3d-mouse-coords)
265 (define (apply-to-args args fn) (apply fn args))
267 (defmacro false-if-exception (expr)
268 `(catch #t (lambda () ,expr)
273 ;;; {General Properties}
276 ;; This is a more modern interface to properties. It will replace all
277 ;; other property-like things eventually.
279 (define (make-object-property)
280 (let ((prop (primitive-make-property #f)))
281 (make-procedure-with-setter
282 (lambda (obj) (primitive-property-ref prop obj))
283 (lambda (obj val) (primitive-property-set! prop obj val)))))
287 ;;; {Symbol Properties}
290 (define (symbol-property sym prop)
291 (let ((pair (assoc prop (symbol-pref sym))))
292 (and pair (cdr pair))))
294 (define (set-symbol-property! sym prop val)
295 (let ((pair (assoc prop (symbol-pref sym))))
298 (symbol-pset! sym (acons prop val (symbol-pref sym))))))
300 (define (symbol-property-remove! sym prop)
301 (let ((pair (assoc prop (symbol-pref sym))))
303 (symbol-pset! sym (delq! pair (symbol-pref sym))))))
310 (define (array-shape a)
311 (map (lambda (ind) (if (number? ind) (list 0 (+ -1 ind)) ind))
312 (array-dimensions a)))
319 (define (kw-arg-ref args kw)
320 (let ((rem (member kw args)))
321 (and rem (pair? (cdr rem)) (cadr rem))))
328 (define (struct-layout s)
329 (struct-ref (struct-vtable s) vtable-index-layout))
336 ;; Printing records: by default, records are printed as
338 ;; #<type-name field1: val1 field2: val2 ...>
340 ;; You can change that by giving a custom printing function to
341 ;; MAKE-RECORD-TYPE (after the list of field symbols). This function
342 ;; will be called like
344 ;; (<printer> object port)
346 ;; It should print OBJECT to PORT.
348 (define (inherit-print-state old-port new-port)
349 (if (get-print-state old-port)
350 (port-with-print-state new-port (get-print-state old-port))
353 ;; 0: type-name, 1: fields
354 (define record-type-vtable
355 (make-vtable-vtable "prpr" 0
357 (cond ((eq? s record-type-vtable)
358 (display "#<record-type-vtable>" p))
360 (display "#<record-type " p)
361 (display (record-type-name s) p)
364 (define (record-type? obj)
365 (and (struct? obj) (eq? record-type-vtable (struct-vtable obj))))
367 (define (make-record-type type-name fields . opt)
368 (let ((printer-fn (and (pair? opt) (car opt))))
369 (let ((struct (make-struct record-type-vtable 0
372 (map (lambda (f) "pw") fields)))
376 (display type-name p)
377 (let loop ((fields fields)
380 ((not (null? fields))
382 (display (car fields) p)
384 (display (struct-ref s off) p)
385 (loop (cdr fields) (+ 1 off)))))
388 (copy-tree fields))))
389 ;; Temporary solution: Associate a name to the record type descriptor
390 ;; so that the object system can create a wrapper class for it.
391 (set-struct-vtable-name! struct (if (symbol? type-name)
393 (string->symbol type-name)))
396 (define (record-type-name obj)
397 (if (record-type? obj)
398 (struct-ref obj vtable-offset-user)
399 (error 'not-a-record-type obj)))
401 (define (record-type-fields obj)
402 (if (record-type? obj)
403 (struct-ref obj (+ 1 vtable-offset-user))
404 (error 'not-a-record-type obj)))
406 (define (record-constructor rtd . opt)
407 (let ((field-names (if (pair? opt) (car opt) (record-type-fields rtd))))
409 `(lambda ,field-names
410 (make-struct ',rtd 0 ,@(map (lambda (f)
411 (if (memq f field-names)
414 (record-type-fields rtd)))))))
416 (define (record-predicate rtd)
417 (lambda (obj) (and (struct? obj) (eq? rtd (struct-vtable obj)))))
419 (define (%record-type-error rtd obj) ;; private helper
420 (or (eq? rtd (record-type-descriptor obj))
421 (scm-error 'wrong-type-arg "%record-type-check"
422 "Wrong type record (want `~S'): ~S"
423 (list (record-type-name rtd) obj)
426 (define (record-accessor rtd field-name)
427 (let ((pos (list-index (record-type-fields rtd) field-name)))
429 (error 'no-such-field field-name))
431 (if (eq? (struct-vtable obj) rtd)
433 (%record-type-error rtd obj)))))
435 (define (record-modifier rtd field-name)
436 (let ((pos (list-index (record-type-fields rtd) field-name)))
438 (error 'no-such-field field-name))
440 (if (eq? (struct-vtable obj) rtd)
441 (struct-set! obj pos val)
442 (%record-type-error rtd obj)))))
444 (define (record? obj)
445 (and (struct? obj) (record-type? (struct-vtable obj))))
447 (define (record-type-descriptor obj)
450 (error 'not-a-record obj)))
459 (define (->bool x) (not (not x)))
466 (define (symbol-append . args)
467 (string->symbol (apply string-append (map symbol->string args))))
469 (define (list->symbol . args)
470 (string->symbol (apply list->string args)))
472 (define (symbol . args)
473 (string->symbol (apply string args)))
480 (define (list-index l k)
486 (loop (+ n 1) (cdr l))))))
490 ;;; {and-map and or-map}
492 ;;; (and-map fn lst) is like (and (fn (car lst)) (fn (cadr lst)) (fn...) ...)
493 ;;; (or-map fn lst) is like (or (fn (car lst)) (fn (cadr lst)) (fn...) ...)
498 ;; Apply f to successive elements of l until exhaustion or f returns #f.
499 ;; If returning early, return #f. Otherwise, return the last value returned
500 ;; by f. If f has never been called because l is empty, return #t.
502 (define (and-map f lst)
503 (let loop ((result #t)
508 (loop (f (car l)) (cdr l))))))
512 ;; Apply f to successive elements of l until exhaustion or while f returns #f.
513 ;; If returning early, return the return value of f.
515 (define (or-map f lst)
516 (let loop ((result #f)
520 (loop (f (car l)) (cdr l))))))
524 (if (provided? 'posix)
525 (primitive-load-path "ice-9/posix"))
527 (if (provided? 'socket)
528 (primitive-load-path "ice-9/networking"))
530 ;; For reference, Emacs file-exists-p uses stat in this same way.
531 ;; ENHANCE-ME: Catching an exception from stat is a bit wasteful, do this in
532 ;; C where all that's needed is to inspect the return from stat().
534 (if (provided? 'posix)
536 (->bool (false-if-exception (stat str))))
538 (let ((port (catch 'system-error (lambda () (open-file str OPEN_READ))
540 (if port (begin (close-port port) #t)
543 (define file-is-directory?
544 (if (provided? 'posix)
546 (eq? (stat:type (stat str)) 'directory))
548 (let ((port (catch 'system-error
549 (lambda () (open-file (string-append str "/.")
552 (if port (begin (close-port port) #t)
555 (define (has-suffix? str suffix)
556 (string-suffix? suffix str))
558 (define (system-error-errno args)
559 (if (eq? (car args) 'system-error)
560 (car (list-ref args 4))
568 (define (error . args)
571 (scm-error 'misc-error #f "?" #f #f)
572 (let loop ((msg "~A")
574 (if (not (null? rest))
575 (loop (string-append msg " ~S")
577 (scm-error 'misc-error #f msg args #f)))))
579 ;; bad-throw is the hook that is called upon a throw to a an unhandled
580 ;; key (unless the throw has four arguments, in which case
581 ;; it's usually interpreted as an error throw.)
582 ;; If the key has a default handler (a throw-handler-default property),
583 ;; it is applied to the throw.
585 (define (bad-throw key . args)
586 (let ((default (symbol-property key 'throw-handler-default)))
587 (or (and default (apply default key args))
588 (apply error "unhandled-exception:" key args))))
592 (define (tm:sec obj) (vector-ref obj 0))
593 (define (tm:min obj) (vector-ref obj 1))
594 (define (tm:hour obj) (vector-ref obj 2))
595 (define (tm:mday obj) (vector-ref obj 3))
596 (define (tm:mon obj) (vector-ref obj 4))
597 (define (tm:year obj) (vector-ref obj 5))
598 (define (tm:wday obj) (vector-ref obj 6))
599 (define (tm:yday obj) (vector-ref obj 7))
600 (define (tm:isdst obj) (vector-ref obj 8))
601 (define (tm:gmtoff obj) (vector-ref obj 9))
602 (define (tm:zone obj) (vector-ref obj 10))
604 (define (set-tm:sec obj val) (vector-set! obj 0 val))
605 (define (set-tm:min obj val) (vector-set! obj 1 val))
606 (define (set-tm:hour obj val) (vector-set! obj 2 val))
607 (define (set-tm:mday obj val) (vector-set! obj 3 val))
608 (define (set-tm:mon obj val) (vector-set! obj 4 val))
609 (define (set-tm:year obj val) (vector-set! obj 5 val))
610 (define (set-tm:wday obj val) (vector-set! obj 6 val))
611 (define (set-tm:yday obj val) (vector-set! obj 7 val))
612 (define (set-tm:isdst obj val) (vector-set! obj 8 val))
613 (define (set-tm:gmtoff obj val) (vector-set! obj 9 val))
614 (define (set-tm:zone obj val) (vector-set! obj 10 val))
616 (define (tms:clock obj) (vector-ref obj 0))
617 (define (tms:utime obj) (vector-ref obj 1))
618 (define (tms:stime obj) (vector-ref obj 2))
619 (define (tms:cutime obj) (vector-ref obj 3))
620 (define (tms:cstime obj) (vector-ref obj 4))
622 (define file-position ftell)
623 (define (file-set-position port offset . whence)
624 (let ((whence (if (eq? whence '()) SEEK_SET (car whence))))
625 (seek port offset whence)))
627 (define (move->fdes fd/port fd)
628 (cond ((integer? fd/port)
629 (dup->fdes fd/port fd)
633 (primitive-move->fdes fd/port fd)
634 (set-port-revealed! fd/port 1)
637 (define (release-port-handle port)
638 (let ((revealed (port-revealed port)))
640 (set-port-revealed! port (- revealed 1)))))
642 (define (dup->port port/fd mode . maybe-fd)
643 (let ((port (fdopen (apply dup->fdes port/fd maybe-fd)
646 (set-port-revealed! port 1))
649 (define (dup->inport port/fd . maybe-fd)
650 (apply dup->port port/fd "r" maybe-fd))
652 (define (dup->outport port/fd . maybe-fd)
653 (apply dup->port port/fd "w" maybe-fd))
655 (define (dup port/fd . maybe-fd)
656 (if (integer? port/fd)
657 (apply dup->fdes port/fd maybe-fd)
658 (apply dup->port port/fd (port-mode port/fd) maybe-fd)))
660 (define (duplicate-port port modes)
661 (dup->port port modes))
663 (define (fdes->inport fdes)
664 (let loop ((rest-ports (fdes->ports fdes)))
665 (cond ((null? rest-ports)
666 (let ((result (fdopen fdes "r")))
667 (set-port-revealed! result 1)
669 ((input-port? (car rest-ports))
670 (set-port-revealed! (car rest-ports)
671 (+ (port-revealed (car rest-ports)) 1))
674 (loop (cdr rest-ports))))))
676 (define (fdes->outport fdes)
677 (let loop ((rest-ports (fdes->ports fdes)))
678 (cond ((null? rest-ports)
679 (let ((result (fdopen fdes "w")))
680 (set-port-revealed! result 1)
682 ((output-port? (car rest-ports))
683 (set-port-revealed! (car rest-ports)
684 (+ (port-revealed (car rest-ports)) 1))
687 (loop (cdr rest-ports))))))
689 (define (port->fdes port)
690 (set-port-revealed! port (+ (port-revealed port) 1))
693 (define (setenv name value)
695 (putenv (string-append name "=" value))
698 (define (unsetenv name)
699 "Remove the entry for NAME from the environment."
707 ;;; Here for backward compatability
709 (define scheme-file-suffix (lambda () ".scm"))
711 (define (in-vicinity vicinity file)
712 (let ((tail (let ((len (string-length vicinity)))
715 (string-ref vicinity (- len 1))))))
716 (string-append vicinity
725 ;;; {Help for scm_shell}
727 ;;; The argument-processing code used by Guile-based shells generates
728 ;;; Scheme code based on the argument list. This page contains help
729 ;;; functions for the code it generates.
732 (define (command-line) (program-arguments))
734 ;; This is mostly for the internal use of the code generated by
735 ;; scm_compile_shell_switches.
737 (define (turn-on-debugging)
738 (debug-enable 'debug)
739 (debug-enable 'backtrace)
740 (read-enable 'positions))
742 (define (load-user-init)
743 (let* ((home (or (getenv "HOME")
744 (false-if-exception (passwd:dir (getpwuid (getuid))))
745 "/")) ;; fallback for cygwin etc.
746 (init-file (in-vicinity home ".guile")))
747 (if (file-exists? init-file)
748 (primitive-load init-file))))
752 ;;; {The interpreter stack}
755 (defmacro start-stack (tag exp)
756 `(%start-stack ,tag (lambda () ,exp)))
760 ;;; {Loading by paths}
763 ;;; Load a Scheme source file named NAME, searching for it in the
764 ;;; directories listed in %load-path, and applying each of the file
765 ;;; name extensions listed in %load-extensions.
766 (define (load-from-path name)
767 (start-stack 'load-stack
768 (primitive-load-path name)))
770 (define %load-verbosely #f)
771 (define (assert-load-verbosity v) (set! %load-verbosely v))
773 (define (%load-announce file)
775 (with-output-to-port (current-error-port)
783 (set! %load-hook %load-announce)
785 (define (load name . reader)
786 (with-fluid* current-reader (and (pair? reader) (car reader))
788 (start-stack 'load-stack
789 (primitive-load name)))))
793 ;;; {Transcendental Functions}
795 ;;; Derived from "Transcen.scm", Complex trancendental functions for SCM.
796 ;;; Written by Jerry D. Hedden, (C) FSF.
797 ;;; See the file `COPYING' for terms applying to this program.
801 (let ((integer-expt integer-expt))
803 (cond ((and (exact? z2) (integer? z2))
804 (integer-expt z1 z2))
805 ((and (real? z2) (real? z1) (>= z1 0))
808 (exp (* z2 (log z1))))))))
811 (if (real? z) ($sinh z)
812 (let ((x (real-part z)) (y (imag-part z)))
813 (make-rectangular (* ($sinh x) ($cos y))
814 (* ($cosh x) ($sin y))))))
816 (if (real? z) ($cosh z)
817 (let ((x (real-part z)) (y (imag-part z)))
818 (make-rectangular (* ($cosh x) ($cos y))
819 (* ($sinh x) ($sin y))))))
821 (if (real? z) ($tanh z)
822 (let* ((x (* 2 (real-part z)))
823 (y (* 2 (imag-part z)))
824 (w (+ ($cosh x) ($cos y))))
825 (make-rectangular (/ ($sinh x) w) (/ ($sin y) w)))))
828 (if (real? z) ($asinh z)
829 (log (+ z (sqrt (+ (* z z) 1))))))
832 (if (and (real? z) (>= z 1))
834 (log (+ z (sqrt (- (* z z) 1))))))
837 (if (and (real? z) (> z -1) (< z 1))
839 (/ (log (/ (+ 1 z) (- 1 z))) 2)))
842 (if (real? z) ($sin z)
843 (let ((x (real-part z)) (y (imag-part z)))
844 (make-rectangular (* ($sin x) ($cosh y))
845 (* ($cos x) ($sinh y))))))
847 (if (real? z) ($cos z)
848 (let ((x (real-part z)) (y (imag-part z)))
849 (make-rectangular (* ($cos x) ($cosh y))
850 (- (* ($sin x) ($sinh y)))))))
852 (if (real? z) ($tan z)
853 (let* ((x (* 2 (real-part z)))
854 (y (* 2 (imag-part z)))
855 (w (+ ($cos x) ($cosh y))))
856 (make-rectangular (/ ($sin x) w) (/ ($sinh y) w)))))
859 (if (and (real? z) (>= z -1) (<= z 1))
861 (* -i (asinh (* +i z)))))
864 (if (and (real? z) (>= z -1) (<= z 1))
866 (+ (/ (angle -1) 2) (* +i (asinh (* +i z))))))
870 (if (real? z) ($atan z)
871 (/ (log (/ (- +i z) (+ +i z))) +2i))
876 ;;; {Reader Extensions}
878 ;;; Reader code for various "#c" forms.
881 (read-hash-extend #\' (lambda (c port)
884 (define read-eval? (make-fluid))
885 (fluid-set! read-eval? #f)
886 (read-hash-extend #\.
888 (if (fluid-ref read-eval?)
889 (eval (read port) (interaction-environment))
891 "#. read expansion found and read-eval? is #f."))))
895 ;;; {Command Line Options}
898 (define (get-option argv kw-opts kw-args return)
903 ((or (not (eq? #\- (string-ref (car argv) 0)))
904 (eq? (string-length (car argv)) 1))
905 (return 'normal-arg (car argv) (cdr argv)))
907 ((eq? #\- (string-ref (car argv) 1))
908 (let* ((kw-arg-pos (or (string-index (car argv) #\=)
909 (string-length (car argv))))
910 (kw (symbol->keyword (substring (car argv) 2 kw-arg-pos)))
911 (kw-opt? (member kw kw-opts))
912 (kw-arg? (member kw kw-args))
913 (arg (or (and (not (eq? kw-arg-pos (string-length (car argv))))
914 (substring (car argv)
916 (string-length (car argv))))
918 (begin (set! argv (cdr argv)) (car argv))))))
919 (if (or kw-opt? kw-arg?)
920 (return kw arg (cdr argv))
921 (return 'usage-error kw (cdr argv)))))
924 (let* ((char (substring (car argv) 1 2))
925 (kw (symbol->keyword char)))
929 (let* ((rest-car (substring (car argv) 2 (string-length (car argv))))
930 (new-argv (if (= 0 (string-length rest-car))
932 (cons (string-append "-" rest-car) (cdr argv)))))
933 (return kw #f new-argv)))
936 (let* ((rest-car (substring (car argv) 2 (string-length (car argv))))
937 (arg (if (= 0 (string-length rest-car))
940 (new-argv (if (= 0 (string-length rest-car))
943 (return kw arg new-argv)))
945 (else (return 'usage-error kw argv)))))))
947 (define (for-next-option proc argv kw-opts kw-args)
948 (let loop ((argv argv))
949 (get-option argv kw-opts kw-args
950 (lambda (opt opt-arg argv)
951 (and opt (proc opt opt-arg argv loop))))))
953 (define (display-usage-report kw-desc)
956 (or (eq? (car kw) #t)
959 (help (cadr opt-desc))
960 (opts (car opt-desc))
961 (opts-proper (if (string? (car opts)) (cdr opts) opts))
962 (arg-name (if (string? (car opts))
963 (string-append "<" (car opts) ">")
965 (left-part (string-append
966 (with-output-to-string
968 (map (lambda (x) (display (keyword->symbol x)) (display " "))
971 (middle-part (if (and (< (string-length left-part) 30)
972 (< (string-length help) 40))
973 (make-string (- 30 (string-length left-part)) #\ )
976 (display middle-part)
983 (define (transform-usage-lambda cases)
984 (let* ((raw-usage (delq! 'else (map car cases)))
985 (usage-sans-specials (map (lambda (x)
986 (or (and (not (list? x)) x)
987 (and (symbol? (car x)) #t)
988 (and (boolean? (car x)) #t)
991 (usage-desc (delq! #t usage-sans-specials))
992 (kw-desc (map car usage-desc))
993 (kw-opts (apply append (map (lambda (x) (and (not (string? (car x))) x)) kw-desc)))
994 (kw-args (apply append (map (lambda (x) (and (string? (car x)) (cdr x))) kw-desc)))
995 (transmogrified-cases (map (lambda (case)
996 (cons (let ((opts (car case)))
997 (if (or (boolean? opts) (eq? 'else opts))
1000 ((symbol? (car opts)) opts)
1001 ((boolean? (car opts)) opts)
1002 ((string? (caar opts)) (cdar opts))
1003 (else (car opts)))))
1006 `(let ((%display-usage (lambda () (display-usage-report ',usage-desc))))
1008 (let %next-arg ((%argv %argv))
1012 (lambda (%opt %arg %new-argv)
1014 ,@ transmogrified-cases))))))))
1019 ;;; {Low Level Modules}
1021 ;;; These are the low level data structures for modules.
1023 ;;; Every module object is of the type 'module-type', which is a record
1024 ;;; consisting of the following members:
1026 ;;; - eval-closure: the function that defines for its module the strategy that
1027 ;;; shall be followed when looking up symbols in the module.
1029 ;;; An eval-closure is a function taking two arguments: the symbol to be
1030 ;;; looked up and a boolean value telling whether a binding for the symbol
1031 ;;; should be created if it does not exist yet. If the symbol lookup
1032 ;;; succeeded (either because an existing binding was found or because a new
1033 ;;; binding was created), a variable object representing the binding is
1034 ;;; returned. Otherwise, the value #f is returned. Note that the eval
1035 ;;; closure does not take the module to be searched as an argument: During
1036 ;;; construction of the eval-closure, the eval-closure has to store the
1037 ;;; module it belongs to in its environment. This means, that any
1038 ;;; eval-closure can belong to only one module.
1040 ;;; The eval-closure of a module can be defined arbitrarily. However, three
1041 ;;; special cases of eval-closures are to be distinguished: During startup
1042 ;;; the module system is not yet activated. In this phase, no modules are
1043 ;;; defined and all bindings are automatically stored by the system in the
1044 ;;; pre-modules-obarray. Since no eval-closures exist at this time, the
1045 ;;; functions which require an eval-closure as their argument need to be
1046 ;;; passed the value #f.
1048 ;;; The other two special cases of eval-closures are the
1049 ;;; standard-eval-closure and the standard-interface-eval-closure. Both
1050 ;;; behave equally for the case that no new binding is to be created. The
1051 ;;; difference between the two comes in, when the boolean argument to the
1052 ;;; eval-closure indicates that a new binding shall be created if it is not
1055 ;;; Given that no new binding shall be created, both standard eval-closures
1056 ;;; define the following standard strategy of searching bindings in the
1057 ;;; module: First, the module's obarray is searched for the symbol. Second,
1058 ;;; if no binding for the symbol was found in the module's obarray, the
1059 ;;; module's binder procedure is exececuted. If this procedure did not
1060 ;;; return a binding for the symbol, the modules referenced in the module's
1061 ;;; uses list are recursively searched for a binding of the symbol. If the
1062 ;;; binding can not be found in these modules also, the symbol lookup has
1065 ;;; If a new binding shall be created, the standard-interface-eval-closure
1066 ;;; immediately returns indicating failure. That is, it does not even try
1067 ;;; to look up the symbol. In contrast, the standard-eval-closure would
1068 ;;; first search the obarray, and if no binding was found there, would
1069 ;;; create a new binding in the obarray, therefore not calling the binder
1070 ;;; procedure or searching the modules in the uses list.
1072 ;;; The explanation of the following members obarray, binder and uses
1073 ;;; assumes that the symbol lookup follows the strategy that is defined in
1074 ;;; the standard-eval-closure and the standard-interface-eval-closure.
1076 ;;; - obarray: a hash table that maps symbols to variable objects. In this
1077 ;;; hash table, the definitions are found that are local to the module (that
1078 ;;; is, not imported from other modules). When looking up bindings in the
1079 ;;; module, this hash table is searched first.
1081 ;;; - binder: either #f or a function taking a module and a symbol argument.
1082 ;;; If it is a function it is called after the obarray has been
1083 ;;; unsuccessfully searched for a binding. It then can provide bindings
1084 ;;; that would otherwise not be found locally in the module.
1086 ;;; - uses: a list of modules from which non-local bindings can be inherited.
1087 ;;; These modules are the third place queried for bindings after the obarray
1088 ;;; has been unsuccessfully searched and the binder function did not deliver
1089 ;;; a result either.
1091 ;;; - transformer: either #f or a function taking a scheme expression as
1092 ;;; delivered by read. If it is a function, it will be called to perform
1093 ;;; syntax transformations (e. g. makro expansion) on the given scheme
1094 ;;; expression. The output of the transformer function will then be passed
1095 ;;; to Guile's internal memoizer. This means that the output must be valid
1096 ;;; scheme code. The only exception is, that the output may make use of the
1097 ;;; syntax extensions provided to identify the modules that a binding
1100 ;;; - name: the name of the module. This is used for all kinds of printing
1101 ;;; outputs. In certain places the module name also serves as a way of
1102 ;;; identification. When adding a module to the uses list of another
1103 ;;; module, it is made sure that the new uses list will not contain two
1104 ;;; modules of the same name.
1106 ;;; - kind: classification of the kind of module. The value is (currently?)
1107 ;;; only used for printing. It has no influence on how a module is treated.
1108 ;;; Currently the following values are used when setting the module kind:
1109 ;;; 'module, 'directory, 'interface, 'custom-interface. If no explicit kind
1110 ;;; is set, it defaults to 'module.
1112 ;;; - duplicates-handlers: a list of procedures that get called to make a
1113 ;;; choice between two duplicate bindings when name clashes occur. See the
1114 ;;; `duplicate-handlers' global variable below.
1116 ;;; - observers: a list of procedures that get called when the module is
1119 ;;; - weak-observers: a weak-key hash table of procedures that get called
1120 ;;; when the module is modified. See `module-observe-weak' for details.
1122 ;;; In addition, the module may (must?) contain a binding for
1123 ;;; `%module-public-interface'. This variable should be bound to a module
1124 ;;; representing the exported interface of a module. See the
1125 ;;; `module-public-interface' and `module-export!' procedures.
1127 ;;; !!! warning: The interface to lazy binder procedures is going
1128 ;;; to be changed in an incompatible way to permit all the basic
1129 ;;; module ops to be virtualized.
1131 ;;; (make-module size use-list lazy-binding-proc) => module
1132 ;;; module-{obarray,uses,binder}[|-set!]
1133 ;;; (module? obj) => [#t|#f]
1134 ;;; (module-locally-bound? module symbol) => [#t|#f]
1135 ;;; (module-bound? module symbol) => [#t|#f]
1136 ;;; (module-symbol-locally-interned? module symbol) => [#t|#f]
1137 ;;; (module-symbol-interned? module symbol) => [#t|#f]
1138 ;;; (module-local-variable module symbol) => [#<variable ...> | #f]
1139 ;;; (module-variable module symbol) => [#<variable ...> | #f]
1140 ;;; (module-symbol-binding module symbol opt-value)
1141 ;;; => [ <obj> | opt-value | an error occurs ]
1142 ;;; (module-make-local-var! module symbol) => #<variable...>
1143 ;;; (module-add! module symbol var) => unspecified
1144 ;;; (module-remove! module symbol) => unspecified
1145 ;;; (module-for-each proc module) => unspecified
1146 ;;; (make-scm-module) => module ; a lazy copy of the symhash module
1147 ;;; (set-current-module module) => unspecified
1148 ;;; (current-module) => #<module...>
1154 ;;; {Printing Modules}
1157 ;; This is how modules are printed. You can re-define it.
1158 ;; (Redefining is actually more complicated than simply redefining
1159 ;; %print-module because that would only change the binding and not
1160 ;; the value stored in the vtable that determines how record are
1163 (define (%print-module mod port) ; unused args: depth length style table)
1165 (display (or (module-kind mod) "module") port)
1166 (let ((name (module-name mod)))
1170 (display name port))))
1172 (display (number->string (object-address mod) 16) port)
1177 ;; A module is characterized by an obarray in which local symbols
1178 ;; are interned, a list of modules, "uses", from which non-local
1179 ;; bindings can be inherited, and an optional lazy-binder which
1180 ;; is a (CLOSURE module symbol) which, as a last resort, can provide
1181 ;; bindings that would otherwise not be found locally in the module.
1183 ;; NOTE: If you change anything here, you also need to change
1184 ;; libguile/modules.h.
1187 (make-record-type 'module
1188 '(obarray uses binder eval-closure transformer name kind
1189 duplicates-handlers import-obarray
1190 observers weak-observers)
1193 ;; make-module &opt size uses binder
1195 ;; Create a new module, perhaps with a particular size of obarray,
1196 ;; initial uses list, or binding procedure.
1201 (define (parse-arg index default)
1202 (if (> (length args) index)
1203 (list-ref args index)
1206 (define %default-import-size
1207 ;; Typical number of imported bindings actually used by a module.
1210 (if (> (length args) 3)
1211 (error "Too many args to make-module." args))
1213 (let ((size (parse-arg 0 31))
1214 (uses (parse-arg 1 '()))
1215 (binder (parse-arg 2 #f)))
1217 (if (not (integer? size))
1218 (error "Illegal size to make-module." size))
1219 (if (not (and (list? uses)
1220 (and-map module? uses)))
1221 (error "Incorrect use list." uses))
1222 (if (and binder (not (procedure? binder)))
1224 "Lazy-binder expected to be a procedure or #f." binder))
1226 (let ((module (module-constructor (make-hash-table size)
1227 uses binder #f %pre-modules-transformer
1229 (make-hash-table %default-import-size)
1231 (make-weak-key-hash-table 31))))
1233 ;; We can't pass this as an argument to module-constructor,
1234 ;; because we need it to close over a pointer to the module
1236 (set-module-eval-closure! module (standard-eval-closure module))
1240 (define module-constructor (record-constructor module-type))
1241 (define module-obarray (record-accessor module-type 'obarray))
1242 (define set-module-obarray! (record-modifier module-type 'obarray))
1243 (define module-uses (record-accessor module-type 'uses))
1244 (define set-module-uses! (record-modifier module-type 'uses))
1245 (define module-binder (record-accessor module-type 'binder))
1246 (define set-module-binder! (record-modifier module-type 'binder))
1248 ;; NOTE: This binding is used in libguile/modules.c.
1249 (define module-eval-closure (record-accessor module-type 'eval-closure))
1251 (define module-transformer (record-accessor module-type 'transformer))
1252 (define set-module-transformer! (record-modifier module-type 'transformer))
1253 ;; (define module-name (record-accessor module-type 'name)) wait until mods are booted
1254 (define set-module-name! (record-modifier module-type 'name))
1255 (define module-kind (record-accessor module-type 'kind))
1256 (define set-module-kind! (record-modifier module-type 'kind))
1257 (define module-duplicates-handlers
1258 (record-accessor module-type 'duplicates-handlers))
1259 (define set-module-duplicates-handlers!
1260 (record-modifier module-type 'duplicates-handlers))
1261 (define module-observers (record-accessor module-type 'observers))
1262 (define set-module-observers! (record-modifier module-type 'observers))
1263 (define module-weak-observers (record-accessor module-type 'weak-observers))
1264 (define module? (record-predicate module-type))
1266 (define module-import-obarray (record-accessor module-type 'import-obarray))
1268 (define set-module-eval-closure!
1269 (let ((setter (record-modifier module-type 'eval-closure)))
1270 (lambda (module closure)
1271 (setter module closure)
1272 ;; Make it possible to lookup the module from the environment.
1273 ;; This implementation is correct since an eval closure can belong
1274 ;; to maximally one module.
1275 (set-procedure-property! closure 'module module))))
1279 ;;; {Observer protocol}
1282 (define (module-observe module proc)
1283 (set-module-observers! module (cons proc (module-observers module)))
1286 (define (module-observe-weak module observer-id . proc)
1287 ;; Register PROC as an observer of MODULE under name OBSERVER-ID (which can
1288 ;; be any Scheme object). PROC is invoked and passed MODULE any time
1289 ;; MODULE is modified. PROC gets unregistered when OBSERVER-ID gets GC'd
1290 ;; (thus, it is never unregistered if OBSERVER-ID is an immediate value,
1293 ;; The two-argument version is kept for backward compatibility: when called
1294 ;; with two arguments, the observer gets unregistered when closure PROC
1295 ;; gets GC'd (making it impossible to use an anonymous lambda for PROC).
1297 (let ((proc (if (null? proc) observer-id (car proc))))
1298 (hashq-set! (module-weak-observers module) observer-id proc)))
1300 (define (module-unobserve token)
1301 (let ((module (car token))
1304 (hash-remove! (module-weak-observers module) id)
1305 (set-module-observers! module (delq1! id (module-observers module)))))
1308 (define module-defer-observers #f)
1309 (define module-defer-observers-mutex (make-mutex 'recursive))
1310 (define module-defer-observers-table (make-hash-table))
1312 (define (module-modified m)
1313 (if module-defer-observers
1314 (hash-set! module-defer-observers-table m #t)
1315 (module-call-observers m)))
1317 ;;; This function can be used to delay calls to observers so that they
1318 ;;; can be called once only in the face of massive updating of modules.
1320 (define (call-with-deferred-observers thunk)
1323 (lock-mutex module-defer-observers-mutex)
1324 (set! module-defer-observers #t))
1327 (set! module-defer-observers #f)
1328 (hash-for-each (lambda (m dummy)
1329 (module-call-observers m))
1330 module-defer-observers-table)
1331 (hash-clear! module-defer-observers-table)
1332 (unlock-mutex module-defer-observers-mutex))))
1334 (define (module-call-observers m)
1335 (for-each (lambda (proc) (proc m)) (module-observers m))
1337 ;; We assume that weak observers don't (un)register themselves as they are
1338 ;; called since this would preclude proper iteration over the hash table
1340 (hash-for-each (lambda (id proc) (proc m)) (module-weak-observers m)))
1344 ;;; {Module Searching in General}
1346 ;;; We sometimes want to look for properties of a symbol
1347 ;;; just within the obarray of one module. If the property
1348 ;;; holds, then it is said to hold ``locally'' as in, ``The symbol
1349 ;;; DISPLAY is locally rebound in the module `safe-guile'.''
1352 ;;; Other times, we want to test for a symbol property in the obarray
1353 ;;; of M and, if it is not found there, try each of the modules in the
1354 ;;; uses list of M. This is the normal way of testing for some
1355 ;;; property, so we state these properties without qualification as
1356 ;;; in: ``The symbol 'fnord is interned in module M because it is
1357 ;;; interned locally in module M2 which is a member of the uses list
1361 ;; module-search fn m
1363 ;; return the first non-#f result of FN applied to M and then to
1364 ;; the modules in the uses of m, and so on recursively. If all applications
1365 ;; return #f, then so does this function.
1367 (define (module-search fn m v)
1370 (or (module-search fn (car pos) v)
1373 (loop (module-uses m))))
1376 ;;; {Is a symbol bound in a module?}
1378 ;;; Symbol S in Module M is bound if S is interned in M and if the binding
1379 ;;; of S in M has been set to some well-defined value.
1382 ;; module-locally-bound? module symbol
1384 ;; Is a symbol bound (interned and defined) locally in a given module?
1386 (define (module-locally-bound? m v)
1387 (let ((var (module-local-variable m v)))
1389 (variable-bound? var))))
1391 ;; module-bound? module symbol
1393 ;; Is a symbol bound (interned and defined) anywhere in a given module
1396 (define (module-bound? m v)
1397 (module-search module-locally-bound? m v))
1399 ;;; {Is a symbol interned in a module?}
1401 ;;; Symbol S in Module M is interned if S occurs in
1402 ;;; of S in M has been set to some well-defined value.
1404 ;;; It is possible to intern a symbol in a module without providing
1405 ;;; an initial binding for the corresponding variable. This is done
1407 ;;; (module-add! module symbol (make-undefined-variable))
1409 ;;; In that case, the symbol is interned in the module, but not
1410 ;;; bound there. The unbound symbol shadows any binding for that
1411 ;;; symbol that might otherwise be inherited from a member of the uses list.
1414 (define (module-obarray-get-handle ob key)
1415 ((if (symbol? key) hashq-get-handle hash-get-handle) ob key))
1417 (define (module-obarray-ref ob key)
1418 ((if (symbol? key) hashq-ref hash-ref) ob key))
1420 (define (module-obarray-set! ob key val)
1421 ((if (symbol? key) hashq-set! hash-set!) ob key val))
1423 (define (module-obarray-remove! ob key)
1424 ((if (symbol? key) hashq-remove! hash-remove!) ob key))
1426 ;; module-symbol-locally-interned? module symbol
1428 ;; is a symbol interned (not neccessarily defined) locally in a given module
1429 ;; or its uses? Interned symbols shadow inherited bindings even if
1430 ;; they are not themselves bound to a defined value.
1432 (define (module-symbol-locally-interned? m v)
1433 (not (not (module-obarray-get-handle (module-obarray m) v))))
1435 ;; module-symbol-interned? module symbol
1437 ;; is a symbol interned (not neccessarily defined) anywhere in a given module
1438 ;; or its uses? Interned symbols shadow inherited bindings even if
1439 ;; they are not themselves bound to a defined value.
1441 (define (module-symbol-interned? m v)
1442 (module-search module-symbol-locally-interned? m v))
1445 ;;; {Mapping modules x symbols --> variables}
1448 ;; module-local-variable module symbol
1449 ;; return the local variable associated with a MODULE and SYMBOL.
1451 ;;; This function is very important. It is the only function that can
1452 ;;; return a variable from a module other than the mutators that store
1453 ;;; new variables in modules. Therefore, this function is the location
1454 ;;; of the "lazy binder" hack.
1456 ;;; If symbol is defined in MODULE, and if the definition binds symbol
1457 ;;; to a variable, return that variable object.
1459 ;;; If the symbols is not found at first, but the module has a lazy binder,
1460 ;;; then try the binder.
1462 ;;; If the symbol is not found at all, return #f.
1464 ;;; (This is now written in C, see `modules.c'.)
1467 ;;; {Mapping modules x symbols --> bindings}
1469 ;;; These are similar to the mapping to variables, except that the
1470 ;;; variable is dereferenced.
1473 ;; module-symbol-binding module symbol opt-value
1475 ;; return the binding of a variable specified by name within
1476 ;; a given module, signalling an error if the variable is unbound.
1477 ;; If the OPT-VALUE is passed, then instead of signalling an error,
1478 ;; return OPT-VALUE.
1480 (define (module-symbol-local-binding m v . opt-val)
1481 (let ((var (module-local-variable m v)))
1482 (if (and var (variable-bound? var))
1484 (if (not (null? opt-val))
1486 (error "Locally unbound variable." v)))))
1488 ;; module-symbol-binding module symbol opt-value
1490 ;; return the binding of a variable specified by name within
1491 ;; a given module, signalling an error if the variable is unbound.
1492 ;; If the OPT-VALUE is passed, then instead of signalling an error,
1493 ;; return OPT-VALUE.
1495 (define (module-symbol-binding m v . opt-val)
1496 (let ((var (module-variable m v)))
1497 (if (and var (variable-bound? var))
1499 (if (not (null? opt-val))
1501 (error "Unbound variable." v)))))
1506 ;;; {Adding Variables to Modules}
1509 ;; module-make-local-var! module symbol
1511 ;; ensure a variable for V in the local namespace of M.
1512 ;; If no variable was already there, then create a new and uninitialzied
1515 ;; This function is used in modules.c.
1517 (define (module-make-local-var! m v)
1518 (or (let ((b (module-obarray-ref (module-obarray m) v)))
1521 ;; Mark as modified since this function is called when
1522 ;; the standard eval closure defines a binding
1526 ;; Create a new local variable.
1527 (let ((local-var (make-undefined-variable)))
1528 (module-add! m v local-var)
1531 ;; module-ensure-local-variable! module symbol
1533 ;; Ensure that there is a local variable in MODULE for SYMBOL. If
1534 ;; there is no binding for SYMBOL, create a new uninitialized
1535 ;; variable. Return the local variable.
1537 (define (module-ensure-local-variable! module symbol)
1538 (or (module-local-variable module symbol)
1539 (let ((var (make-undefined-variable)))
1540 (module-add! module symbol var)
1543 ;; module-add! module symbol var
1545 ;; ensure a particular variable for V in the local namespace of M.
1547 (define (module-add! m v var)
1548 (if (not (variable? var))
1549 (error "Bad variable to module-add!" var))
1550 (module-obarray-set! (module-obarray m) v var)
1551 (module-modified m))
1555 ;; make sure that a symbol is undefined in the local namespace of M.
1557 (define (module-remove! m v)
1558 (module-obarray-remove! (module-obarray m) v)
1559 (module-modified m))
1561 (define (module-clear! m)
1562 (hash-clear! (module-obarray m))
1563 (module-modified m))
1565 ;; MODULE-FOR-EACH -- exported
1567 ;; Call PROC on each symbol in MODULE, with arguments of (SYMBOL VARIABLE).
1569 (define (module-for-each proc module)
1570 (hash-for-each proc (module-obarray module)))
1572 (define (module-map proc module)
1573 (hash-map->list proc (module-obarray module)))
1577 ;;; {Low Level Bootstrapping}
1582 ;; A root module uses the pre-modules-obarray as its obarray. This
1583 ;; special obarray accumulates all bindings that have been established
1584 ;; before the module system is fully booted.
1586 ;; (The obarray continues to be used by code that has been closed over
1587 ;; before the module system has been booted.)
1589 (define (make-root-module)
1590 (let ((m (make-module 0)))
1591 (set-module-obarray! m (%get-pre-modules-obarray))
1596 ;; The root interface is a module that uses the same obarray as the
1597 ;; root module. It does not allow new definitions, tho.
1599 (define (make-scm-module)
1600 (let ((m (make-module 0)))
1601 (set-module-obarray! m (%get-pre-modules-obarray))
1602 (set-module-eval-closure! m (standard-interface-eval-closure m))
1608 ;;; {Module-based Loading}
1611 (define (save-module-excursion thunk)
1612 (let ((inner-module (current-module))
1614 (dynamic-wind (lambda ()
1615 (set! outer-module (current-module))
1616 (set-current-module inner-module)
1617 (set! inner-module #f))
1620 (set! inner-module (current-module))
1621 (set-current-module outer-module)
1622 (set! outer-module #f)))))
1624 (define basic-load load)
1626 (define (load-module filename . reader)
1627 (save-module-excursion
1629 (let ((oldname (and (current-load-port)
1630 (port-filename (current-load-port)))))
1633 (> (string-length filename) 0)
1634 (not (char=? (string-ref filename 0) #\/))
1635 (not (string=? (dirname oldname) ".")))
1636 (string-append (dirname oldname) "/" filename)
1643 ;;; {MODULE-REF -- exported}
1646 ;; Returns the value of a variable called NAME in MODULE or any of its
1647 ;; used modules. If there is no such variable, then if the optional third
1648 ;; argument DEFAULT is present, it is returned; otherwise an error is signaled.
1650 (define (module-ref module name . rest)
1651 (let ((variable (module-variable module name)))
1652 (if (and variable (variable-bound? variable))
1653 (variable-ref variable)
1655 (error "No variable named" name 'in module)
1656 (car rest) ; default value
1659 ;; MODULE-SET! -- exported
1661 ;; Sets the variable called NAME in MODULE (or in a module that MODULE uses)
1662 ;; to VALUE; if there is no such variable, an error is signaled.
1664 (define (module-set! module name value)
1665 (let ((variable (module-variable module name)))
1667 (variable-set! variable value)
1668 (error "No variable named" name 'in module))))
1670 ;; MODULE-DEFINE! -- exported
1672 ;; Sets the variable called NAME in MODULE to VALUE; if there is no such
1673 ;; variable, it is added first.
1675 (define (module-define! module name value)
1676 (let ((variable (module-local-variable module name)))
1679 (variable-set! variable value)
1680 (module-modified module))
1681 (let ((variable (make-variable value)))
1682 (module-add! module name variable)))))
1684 ;; MODULE-DEFINED? -- exported
1686 ;; Return #t iff NAME is defined in MODULE (or in a module that MODULE
1689 (define (module-defined? module name)
1690 (let ((variable (module-variable module name)))
1691 (and variable (variable-bound? variable))))
1693 ;; MODULE-USE! module interface
1695 ;; Add INTERFACE to the list of interfaces used by MODULE.
1697 (define (module-use! module interface)
1698 (if (not (or (eq? module interface)
1699 (memq interface (module-uses module))))
1701 ;; Newly used modules must be appended rather than consed, so that
1702 ;; `module-variable' traverses the use list starting from the first
1704 (set-module-uses! module
1705 (append (filter (lambda (m)
1707 (equal? (module-name m)
1708 (module-name interface))))
1709 (module-uses module))
1712 (module-modified module))))
1714 ;; MODULE-USE-INTERFACES! module interfaces
1716 ;; Same as MODULE-USE! but add multiple interfaces and check for duplicates
1718 (define (module-use-interfaces! module interfaces)
1719 (set-module-uses! module
1720 (append (module-uses module) interfaces))
1721 (module-modified module))
1725 ;;; {Recursive Namespaces}
1727 ;;; A hierarchical namespace emerges if we consider some module to be
1728 ;;; root, and variables bound to modules as nested namespaces.
1730 ;;; The routines in this file manage variable names in hierarchical namespace.
1731 ;;; Each variable name is a list of elements, looked up in successively nested
1734 ;;; (nested-ref some-root-module '(foo bar baz))
1735 ;;; => <value of a variable named baz in the module bound to bar in
1736 ;;; the module bound to foo in some-root-module>
1741 ;;; ;; a-root is a module
1742 ;;; ;; name is a list of symbols
1744 ;;; nested-ref a-root name
1745 ;;; nested-set! a-root name val
1746 ;;; nested-define! a-root name val
1747 ;;; nested-remove! a-root name
1750 ;;; (current-module) is a natural choice for a-root so for convenience there are
1753 ;;; local-ref name == nested-ref (current-module) name
1754 ;;; local-set! name val == nested-set! (current-module) name val
1755 ;;; local-define! name val == nested-define! (current-module) name val
1756 ;;; local-remove! name == nested-remove! (current-module) name
1760 (define (nested-ref root names)
1761 (let loop ((cur root)
1765 ((not (module? cur)) #f)
1766 (else (loop (module-ref cur (car elts) #f) (cdr elts))))))
1768 (define (nested-set! root names val)
1769 (let loop ((cur root)
1771 (if (null? (cdr elts))
1772 (module-set! cur (car elts) val)
1773 (loop (module-ref cur (car elts)) (cdr elts)))))
1775 (define (nested-define! root names val)
1776 (let loop ((cur root)
1778 (if (null? (cdr elts))
1779 (module-define! cur (car elts) val)
1780 (loop (module-ref cur (car elts)) (cdr elts)))))
1782 (define (nested-remove! root names)
1783 (let loop ((cur root)
1785 (if (null? (cdr elts))
1786 (module-remove! cur (car elts))
1787 (loop (module-ref cur (car elts)) (cdr elts)))))
1789 (define (local-ref names) (nested-ref (current-module) names))
1790 (define (local-set! names val) (nested-set! (current-module) names val))
1791 (define (local-define names val) (nested-define! (current-module) names val))
1792 (define (local-remove names) (nested-remove! (current-module) names))
1797 ;;; {The (%app) module}
1799 ;;; The root of conventionally named objects not directly in the top level.
1802 ;;; (%app modules guile)
1804 ;;; The directory of all modules and the standard root module.
1807 ;; module-public-interface is defined in C.
1808 (define (set-module-public-interface! m i)
1809 (module-define! m '%module-public-interface i))
1810 (define (set-system-module! m s)
1811 (set-procedure-property! (module-eval-closure m) 'system-module s))
1812 (define the-root-module (make-root-module))
1813 (define the-scm-module (make-scm-module))
1814 (set-module-public-interface! the-root-module the-scm-module)
1815 (set-module-name! the-root-module '(guile))
1816 (set-module-name! the-scm-module '(guile))
1817 (set-module-kind! the-scm-module 'interface)
1818 (set-system-module! the-root-module #t)
1819 (set-system-module! the-scm-module #t)
1821 ;; NOTE: This binding is used in libguile/modules.c.
1823 (define (make-modules-in module name)
1827 (let* ((var (module-local-variable module (car name)))
1828 (val (and var (variable-bound? var) (variable-ref var))))
1831 (let ((m (make-module 31)))
1832 (set-module-kind! m 'directory)
1833 (set-module-name! m (append (or (module-name module) '())
1835 (module-define! module (car name) m)
1839 (define (beautify-user-module! module)
1840 (let ((interface (module-public-interface module)))
1841 (if (or (not interface)
1842 (eq? interface module))
1843 (let ((interface (make-module 31)))
1844 (set-module-name! interface (module-name module))
1845 (set-module-kind! interface 'interface)
1846 (set-module-public-interface! module interface))))
1847 (if (and (not (memq the-scm-module (module-uses module)))
1848 (not (eq? module the-root-module)))
1849 ;; Import the default set of bindings (from the SCM module) in MODULE.
1850 (module-use! module the-scm-module)))
1852 ;; NOTE: This binding is used in libguile/modules.c.
1854 (define resolve-module
1855 (let ((the-root-module the-root-module))
1856 (lambda (name . maybe-autoload)
1857 (if (equal? name '(guile))
1859 (let ((full-name (append '(%app modules) name)))
1860 (let ((already (nested-ref the-root-module full-name))
1861 (autoload (or (null? maybe-autoload) (car maybe-autoload))))
1863 ((and already (module? already)
1864 (or (not autoload) (module-public-interface already)))
1865 ;; A hit, a palpable hit.
1868 ;; Try to autoload the module, and recurse.
1869 (try-load-module name)
1870 (resolve-module name #f))
1872 ;; A module is not bound (but maybe something else is),
1873 ;; we're not autoloading -- here's the weird semantics,
1874 ;; we create an empty module.
1875 (make-modules-in the-root-module full-name)))))))))
1877 ;; Cheat. These bindings are needed by modules.c, but we don't want
1878 ;; to move their real definition here because that would be unnatural.
1880 (define try-module-autoload #f)
1881 (define process-define-module #f)
1882 (define process-use-modules #f)
1883 (define module-export! #f)
1884 (define default-duplicate-binding-procedures #f)
1886 (define %app (make-module 31))
1887 (define app %app) ;; for backwards compatability
1889 (local-define '(%app modules) (make-module 31))
1890 (local-define '(%app modules guile) the-root-module)
1892 ;; This boots the module system. All bindings needed by modules.c
1893 ;; must have been defined by now.
1895 (set-current-module the-root-module)
1896 ;; definition deferred for syncase's benefit
1897 (define module-name (record-accessor module-type 'name))
1899 ;; (define-special-value '(%app modules new-ws) (lambda () (make-scm-module)))
1901 (define (try-load-module name)
1902 (try-module-autoload name))
1904 (define (purify-module! module)
1905 "Removes bindings in MODULE which are inherited from the (guile) module."
1906 (let ((use-list (module-uses module)))
1907 (if (and (pair? use-list)
1908 (eq? (car (last-pair use-list)) the-scm-module))
1909 (set-module-uses! module (reverse (cdr (reverse use-list)))))))
1911 ;; Return a module that is an interface to the module designated by
1914 ;; `resolve-interface' takes four keyword arguments:
1916 ;; #:select SELECTION
1918 ;; SELECTION is a list of binding-specs to be imported; A binding-spec
1919 ;; is either a symbol or a pair of symbols (ORIG . SEEN), where ORIG
1920 ;; is the name in the used module and SEEN is the name in the using
1921 ;; module. Note that SEEN is also passed through RENAMER, below. The
1922 ;; default is to select all bindings. If you specify no selection but
1923 ;; a renamer, only the bindings that already exist in the used module
1924 ;; are made available in the interface. Bindings that are added later
1925 ;; are not picked up.
1929 ;; BINDINGS is a list of bindings which should not be imported.
1933 ;; PREFIX is a symbol that will be appended to each exported name.
1934 ;; The default is to not perform any renaming.
1936 ;; #:renamer RENAMER
1938 ;; RENAMER is a procedure that takes a symbol and returns its new
1939 ;; name. The default is not perform any renaming.
1941 ;; Signal "no code for module" error if module name is not resolvable
1942 ;; or its public interface is not available. Signal "no binding"
1943 ;; error if selected binding does not exist in the used module.
1945 (define (resolve-interface name . args)
1947 (define (get-keyword-arg args kw def)
1948 (cond ((memq kw args)
1950 (if (null? (cdr kw-arg))
1951 (error "keyword without value: " kw))
1956 (let* ((select (get-keyword-arg args #:select #f))
1957 (hide (get-keyword-arg args #:hide '()))
1958 (renamer (or (get-keyword-arg args #:renamer #f)
1959 (let ((prefix (get-keyword-arg args #:prefix #f)))
1960 (and prefix (symbol-prefix-proc prefix)))
1962 (module (resolve-module name))
1963 (public-i (and module (module-public-interface module))))
1964 (and (or (not module) (not public-i))
1965 (error "no code for module" name))
1966 (if (and (not select) (null? hide) (eq? renamer identity))
1968 (let ((selection (or select (module-map (lambda (sym var) sym)
1970 (custom-i (make-module 31)))
1971 (set-module-kind! custom-i 'custom-interface)
1972 (set-module-name! custom-i name)
1973 ;; XXX - should use a lazy binder so that changes to the
1974 ;; used module are picked up automatically.
1975 (for-each (lambda (bspec)
1976 (let* ((direct? (symbol? bspec))
1977 (orig (if direct? bspec (car bspec)))
1978 (seen (if direct? bspec (cdr bspec)))
1979 (var (or (module-local-variable public-i orig)
1980 (module-local-variable module orig)
1982 ;; fixme: format manually for now
1984 #f "no binding `~A' in module ~A"
1986 (if (memq orig hide)
1987 (set! hide (delq! orig hide))
1988 (module-add! custom-i
1992 ;; Check that we are not hiding bindings which don't exist
1993 (for-each (lambda (binding)
1994 (if (not (module-local-variable public-i binding))
1997 #f "no binding `~A' to hide in module ~A"
2002 (define (symbol-prefix-proc prefix)
2004 (symbol-append prefix symbol)))
2006 ;; This function is called from "modules.c". If you change it, be
2007 ;; sure to update "modules.c" as well.
2009 (define (process-define-module args)
2010 (let* ((module-id (car args))
2011 (module (resolve-module module-id #f))
2013 (unrecognized (lambda (arg)
2014 (error "unrecognized define-module argument" arg))))
2015 (beautify-user-module! module)
2016 (let loop ((kws kws)
2017 (reversed-interfaces '())
2024 (call-with-deferred-observers
2026 (module-use-interfaces! module (reverse reversed-interfaces))
2027 (module-export! module exports)
2028 (module-replace! module replacements)
2029 (module-re-export! module re-exports)
2030 (if (not (null? autoloads))
2031 (apply module-autoload! module autoloads))))
2033 ((#:use-module #:use-syntax)
2034 (or (pair? (cdr kws))
2037 ((equal? (caadr kws) '(ice-9 syncase))
2038 (issue-deprecation-warning
2039 "(ice-9 syncase) is deprecated. Support for syntax-case is now in Guile core.")
2047 (let* ((interface-args (cadr kws))
2048 (interface (apply resolve-interface interface-args)))
2049 (and (eq? (car kws) #:use-syntax)
2050 (or (symbol? (caar interface-args))
2051 (error "invalid module name for use-syntax"
2052 (car interface-args)))
2053 (set-module-transformer!
2055 (module-ref interface
2056 (car (last-pair (car interface-args)))
2059 (cons interface reversed-interfaces)
2065 (or (and (pair? (cdr kws)) (pair? (cddr kws)))
2072 (let ((name (cadr kws))
2073 (bindings (caddr kws)))
2074 (cons* name bindings autoloads))))
2076 (set-system-module! module #t)
2077 (loop (cdr kws) reversed-interfaces exports re-exports
2078 replacements autoloads))
2080 (purify-module! module)
2081 (loop (cdr kws) reversed-interfaces exports re-exports
2082 replacements autoloads))
2084 (if (not (pair? (cdr kws)))
2086 (set-module-duplicates-handlers!
2088 (lookup-duplicates-handlers (cadr kws)))
2089 (loop (cddr kws) reversed-interfaces exports re-exports
2090 replacements autoloads))
2091 ((#:export #:export-syntax)
2092 (or (pair? (cdr kws))
2096 (append (cadr kws) exports)
2100 ((#:re-export #:re-export-syntax)
2101 (or (pair? (cdr kws))
2106 (append (cadr kws) re-exports)
2109 ((#:replace #:replace-syntax)
2110 (or (pair? (cdr kws))
2116 (append (cadr kws) replacements)
2119 (unrecognized kws)))))
2120 (run-hook module-defined-hook module)
2123 ;; `module-defined-hook' is a hook that is run whenever a new module
2124 ;; is defined. Its members are called with one argument, the new
2126 (define module-defined-hook (make-hook 1))
2133 (define (make-autoload-interface module name bindings)
2134 (let ((b (lambda (a sym definep)
2135 (and (memq sym bindings)
2136 (let ((i (module-public-interface (resolve-module name))))
2138 (error "missing interface for module" name))
2139 (let ((autoload (memq a (module-uses module))))
2140 ;; Replace autoload-interface with actual interface if
2141 ;; that has not happened yet.
2142 (if (pair? autoload)
2143 (set-car! autoload i)))
2144 (module-local-variable i sym))))))
2145 (module-constructor (make-hash-table 0) '() b #f #f name 'autoload #f
2146 (make-hash-table 0) '() (make-weak-value-hash-table 31))))
2148 (define (module-autoload! module . args)
2149 "Have @var{module} automatically load the module named @var{name} when one
2150 of the symbols listed in @var{bindings} is looked up. @var{args} should be a
2151 list of module-name/binding-list pairs, e.g., as in @code{(module-autoload!
2152 module '(ice-9 q) '(make-q q-length))}."
2153 (let loop ((args args))
2157 (error "invalid name+binding autoload list" args))
2159 (let ((name (car args))
2160 (bindings (cadr args)))
2161 (module-use! module (make-autoload-interface module
2163 (loop (cddr args)))))))
2168 ;;; {Autoloading modules}
2171 (define autoloads-in-progress '())
2173 ;; This function is called from "modules.c". If you change it, be
2174 ;; sure to update "modules.c" as well.
2176 (define (try-module-autoload module-name)
2177 (let* ((reverse-name (reverse module-name))
2178 (name (symbol->string (car reverse-name)))
2179 (dir-hint-module-name (reverse (cdr reverse-name)))
2180 (dir-hint (apply string-append
2182 (string-append (symbol->string elt) "/"))
2183 dir-hint-module-name))))
2184 (resolve-module dir-hint-module-name #f)
2185 (and (not (autoload-done-or-in-progress? dir-hint name))
2187 (define (load-file proc file)
2188 (save-module-excursion (lambda () (proc file)))
2191 (lambda () (autoload-in-progress! dir-hint name))
2193 (let ((file (in-vicinity dir-hint name)))
2194 (let ((compiled (and load-compiled
2196 (string-append file ".go"))))
2197 (source (%search-load-path file)))
2200 (< (stat:mtime (stat compiled))
2201 (stat:mtime (stat source)))))
2203 (warn "source file" source "newer than" compiled))
2204 (with-fluid* current-reader #f
2205 (lambda () (load-file primitive-load source))))
2207 (load-file load-compiled compiled))))))
2208 (lambda () (set-autoloaded! dir-hint name didit)))
2213 ;;; {Dynamic linking of modules}
2216 (define autoloads-done '((guile . guile)))
2218 (define (autoload-done-or-in-progress? p m)
2219 (let ((n (cons p m)))
2220 (->bool (or (member n autoloads-done)
2221 (member n autoloads-in-progress)))))
2223 (define (autoload-done! p m)
2224 (let ((n (cons p m)))
2225 (set! autoloads-in-progress
2226 (delete! n autoloads-in-progress))
2227 (or (member n autoloads-done)
2228 (set! autoloads-done (cons n autoloads-done)))))
2230 (define (autoload-in-progress! p m)
2231 (let ((n (cons p m)))
2232 (set! autoloads-done
2233 (delete! n autoloads-done))
2234 (set! autoloads-in-progress (cons n autoloads-in-progress))))
2236 (define (set-autoloaded! p m done?)
2238 (autoload-done! p m)
2239 (let ((n (cons p m)))
2240 (set! autoloads-done (delete! n autoloads-done))
2241 (set! autoloads-in-progress (delete! n autoloads-in-progress)))))
2245 ;;; {Run-time options}
2248 (defmacro define-option-interface (option-group)
2249 (let* ((option-name car)
2251 (option-documentation caddr)
2253 ;; Below follow the macros defining the run-time option interfaces.
2255 (make-options (lambda (interface)
2257 (cond ((null? args) (,interface))
2259 (,interface (car args)) (,interface))
2262 (display (option-name option))
2263 (if (< (string-length
2264 (symbol->string (option-name option)))
2268 (display (option-value option))
2270 (display (option-documentation option))
2272 (,interface #t)))))))
2274 (make-enable (lambda (interface)
2276 (,interface (append flags (,interface)))
2279 (make-disable (lambda (interface)
2281 (let ((options (,interface)))
2282 (for-each (lambda (flag)
2283 (set! options (delq! flag options)))
2285 (,interface options)
2287 (let* ((interface (car option-group))
2288 (options/enable/disable (cadr option-group)))
2290 (define ,(car options/enable/disable)
2291 ,(make-options interface))
2292 (define ,(cadr options/enable/disable)
2293 ,(make-enable interface))
2294 (define ,(caddr options/enable/disable)
2295 ,(make-disable interface))
2296 (defmacro ,(caaddr option-group) (opt val)
2297 `(,',(car options/enable/disable)
2298 (append (,',(car options/enable/disable))
2299 (list ',opt ,val))))))))
2301 (define-option-interface
2302 (eval-options-interface
2303 (eval-options eval-enable eval-disable)
2306 (define-option-interface
2307 (debug-options-interface
2308 (debug-options debug-enable debug-disable)
2311 (define-option-interface
2312 (evaluator-traps-interface
2313 (traps trap-enable trap-disable)
2316 (define-option-interface
2317 (read-options-interface
2318 (read-options read-enable read-disable)
2321 (define-option-interface
2322 (print-options-interface
2323 (print-options print-enable print-disable)
2331 (define (repl read evaler print)
2332 (let loop ((source (read (current-input-port))))
2333 (print (evaler source))
2334 (loop (read (current-input-port)))))
2336 ;; A provisional repl that acts like the SCM repl:
2338 (define scm-repl-silent #f)
2339 (define (assert-repl-silence v) (set! scm-repl-silent v))
2341 (define *unspecified* (if #f #f))
2342 (define (unspecified? v) (eq? v *unspecified*))
2344 (define scm-repl-print-unspecified #f)
2345 (define (assert-repl-print-unspecified v) (set! scm-repl-print-unspecified v))
2347 (define scm-repl-verbose #f)
2348 (define (assert-repl-verbosity v) (set! scm-repl-verbose v))
2350 (define scm-repl-prompt "guile> ")
2352 (define (set-repl-prompt! v) (set! scm-repl-prompt v))
2354 (define (default-pre-unwind-handler key . args)
2355 (save-stack pre-unwind-handler-dispatch)
2356 (apply throw key args))
2358 (define (pre-unwind-handler-dispatch key . args)
2359 (apply default-pre-unwind-handler key args))
2361 (define abort-hook (make-hook))
2363 ;; these definitions are used if running a script.
2364 ;; otherwise redefined in error-catching-loop.
2365 (define (set-batch-mode?! arg) #t)
2366 (define (batch-mode?) #t)
2368 (define (error-catching-loop thunk)
2371 (define (loop first)
2376 (call-with-unblocked-asyncs
2382 ;; This line is needed because mark
2383 ;; doesn't do closures quite right.
2384 ;; Unreferenced locals should be
2387 (let loop ((v (thunk)))
2391 (lambda (key . args)
2398 (apply throw 'switch-repl args))
2401 ;; This is one of the closures that require
2402 ;; (set! first #f) above
2405 (run-hook abort-hook)
2406 (force-output (current-output-port))
2407 (display "ABORT: " (current-error-port))
2408 (write args (current-error-port))
2409 (newline (current-error-port))
2413 (not has-shown-debugger-hint?)
2414 (not (memq 'backtrace
2415 (debug-options-interface)))
2416 (stack? (fluid-ref the-last-stack)))
2418 (newline (current-error-port))
2420 "Type \"(backtrace)\" to get more information or \"(debug)\" to enter the debugger.\n"
2421 (current-error-port))
2422 (set! has-shown-debugger-hint? #t)))
2423 (force-output (current-error-port)))
2425 (primitive-exit 1)))
2426 (set! stack-saved? #f)))
2429 ;; This is the other cons-leak closure...
2431 (cond ((= (length args) 4)
2432 (apply handle-system-error key args))
2434 (apply bad-throw key args)))))))
2436 ;; Note that having just `pre-unwind-handler-dispatch'
2437 ;; here is connected with the mechanism that
2438 ;; produces a nice backtrace upon error. If, for
2439 ;; example, this is replaced with (lambda args
2440 ;; (apply pre-unwind-handler-dispatch args)), the stack
2441 ;; cutting (in save-stack) goes wrong and ends up
2442 ;; saving no stack at all, so there is no
2444 pre-unwind-handler-dispatch)))
2446 (if next (loop next) status)))
2447 (set! set-batch-mode?! (lambda (arg)
2449 (set! interactive #f)
2452 (error "sorry, not implemented")))))
2453 (set! batch-mode? (lambda () (not interactive)))
2454 (call-with-blocked-asyncs
2455 (lambda () (loop (lambda () #t))))))
2457 ;;(define the-last-stack (make-fluid)) Defined by scm_init_backtrace ()
2458 (define before-signal-stack (make-fluid))
2459 (define stack-saved? #f)
2461 (define (save-stack . narrowing)
2463 (cond ((not (memq 'debug (debug-options-interface)))
2464 (fluid-set! the-last-stack #f)
2465 (set! stack-saved? #t))
2471 (apply make-stack #t save-stack primitive-eval #t 0 narrowing))
2473 (apply make-stack #t save-stack 0 #t 0 narrowing))
2475 (apply make-stack #t save-stack tk-stack-mark #t 0 narrowing))
2477 (apply make-stack #t save-stack 0 1 narrowing))
2479 (let ((id (stack-id #t)))
2480 (and (procedure? id)
2481 (apply make-stack #t save-stack id #t 0 narrowing))))))
2482 (set! stack-saved? #t)))))
2484 (define before-error-hook (make-hook))
2485 (define after-error-hook (make-hook))
2486 (define before-backtrace-hook (make-hook))
2487 (define after-backtrace-hook (make-hook))
2489 (define has-shown-debugger-hint? #f)
2491 (define (handle-system-error key . args)
2492 (let ((cep (current-error-port)))
2493 (cond ((not (stack? (fluid-ref the-last-stack))))
2494 ((memq 'backtrace (debug-options-interface))
2495 (let ((highlights (if (or (eq? key 'wrong-type-arg)
2496 (eq? key 'out-of-range))
2499 (run-hook before-backtrace-hook)
2501 (display "Backtrace:\n")
2502 (display-backtrace (fluid-ref the-last-stack) cep
2505 (run-hook after-backtrace-hook))))
2506 (run-hook before-error-hook)
2507 (apply display-error (fluid-ref the-last-stack) cep args)
2508 (run-hook after-error-hook)
2510 (throw 'abort key)))
2512 (define (quit . args)
2513 (apply throw 'quit args))
2517 ;;(define has-shown-backtrace-hint? #f) Defined by scm_init_backtrace ()
2519 ;; Replaced by C code:
2520 ;;(define (backtrace)
2521 ;; (if (fluid-ref the-last-stack)
2524 ;; (display-backtrace (fluid-ref the-last-stack) (current-output-port))
2526 ;; (if (and (not has-shown-backtrace-hint?)
2527 ;; (not (memq 'backtrace (debug-options-interface))))
2530 ;;"Type \"(debug-enable 'backtrace)\" if you would like a backtrace
2531 ;;automatically if an error occurs in the future.\n")
2532 ;; (set! has-shown-backtrace-hint? #t))))
2533 ;; (display "No backtrace available.\n")))
2535 (define (error-catching-repl r e p)
2536 (error-catching-loop
2538 (call-with-values (lambda () (e (r)))
2539 (lambda the-values (for-each p the-values))))))
2541 (define (gc-run-time)
2542 (cdr (assq 'gc-time-taken (gc-stats))))
2544 (define before-read-hook (make-hook))
2545 (define after-read-hook (make-hook))
2546 (define before-eval-hook (make-hook 1))
2547 (define after-eval-hook (make-hook 1))
2548 (define before-print-hook (make-hook 1))
2549 (define after-print-hook (make-hook 1))
2551 ;;; The default repl-reader function. We may override this if we've
2552 ;;; the readline library.
2555 (display (if (string? prompt) prompt (prompt)))
2557 (run-hook before-read-hook)
2558 ((or (fluid-ref current-reader) read) (current-input-port))))
2560 (define (scm-style-repl)
2565 (repl-report-start-timing (lambda ()
2566 (set! start-gc-rt (gc-run-time))
2567 (set! start-rt (get-internal-run-time))))
2568 (repl-report (lambda ()
2570 (display (inexact->exact
2571 (* 1000 (/ (- (get-internal-run-time) start-rt)
2572 internal-time-units-per-second))))
2574 (display (inexact->exact
2575 (* 1000 (/ (- (gc-run-time) start-gc-rt)
2576 internal-time-units-per-second))))
2577 (display " msec in gc)\n")))
2579 (consume-trailing-whitespace
2581 (let ((ch (peek-char)))
2584 ((or (char=? ch #\space) (char=? ch #\tab))
2586 (consume-trailing-whitespace))
2587 ((char=? ch #\newline)
2591 (let ((prompt (cond ((string? scm-repl-prompt)
2593 ((thunk? scm-repl-prompt)
2595 (scm-repl-prompt "> ")
2597 (repl-reader prompt))))
2599 ;; As described in R4RS, the READ procedure updates the
2600 ;; port to point to the first character past the end of
2601 ;; the external representation of the object. This
2602 ;; means that it doesn't consume the newline typically
2603 ;; found after an expression. This means that, when
2604 ;; debugging Guile with GDB, GDB gets the newline, which
2605 ;; it often interprets as a "continue" command, making
2606 ;; breakpoints kind of useless. So, consume any
2607 ;; trailing newline here, as well as any whitespace
2609 ;; But not if EOF, for control-D.
2610 (if (not (eof-object? val))
2611 (consume-trailing-whitespace))
2612 (run-hook after-read-hook)
2613 (if (eof-object? val)
2615 (repl-report-start-timing)
2616 (if scm-repl-verbose
2619 (display ";;; EOF -- quitting")
2624 (-eval (lambda (sourc)
2625 (repl-report-start-timing)
2626 (run-hook before-eval-hook sourc)
2627 (let ((val (start-stack 'repl-stack
2628 ;; If you change this procedure
2629 ;; (primitive-eval), please also
2630 ;; modify the repl-stack case in
2631 ;; save-stack so that stack cutting
2632 ;; continues to work.
2633 (primitive-eval sourc))))
2634 (run-hook after-eval-hook sourc)
2638 (-print (let ((maybe-print (lambda (result)
2639 (if (or scm-repl-print-unspecified
2640 (not (unspecified? result)))
2645 (if (not scm-repl-silent)
2647 (run-hook before-print-hook result)
2648 (maybe-print result)
2649 (run-hook after-print-hook result)
2650 (if scm-repl-verbose
2654 (-quit (lambda (args)
2655 (if scm-repl-verbose
2657 (display ";;; QUIT executed, repl exitting")
2663 (if scm-repl-verbose
2665 (display ";;; ABORT executed.")
2668 (repl -read -eval -print))))
2670 (let ((status (error-catching-repl -read
2678 ;;; {IOTA functions: generating lists of numbers}
2682 (let loop ((count (1- n)) (result '()))
2683 (if (< count 0) result
2684 (loop (1- count) (cons count result)))))
2690 ;;; Similar to `begin' but returns a list of the results of all constituent
2691 ;;; forms instead of the result of the last form.
2692 ;;; (The definition relies on the current left-to-right
2693 ;;; order of evaluation of operands in applications.)
2696 (defmacro collect forms
2704 ;; with-fluids is a convenience wrapper for the builtin procedure
2705 ;; `with-fluids*'. The syntax is just like `let':
2707 ;; (with-fluids ((fluid val)
2711 (defmacro with-fluids (bindings . body)
2712 (let ((fluids (map car bindings))
2713 (values (map cadr bindings)))
2714 (if (and (= (length fluids) 1) (= (length values) 1))
2715 `(with-fluid* ,(car fluids) ,(car values) (lambda () ,@body))
2716 `(with-fluids* (list ,@fluids) (list ,@values)
2717 (lambda () ,@body)))))
2721 ;;; with `continue' and `break'.
2724 ;; The inner `do' loop avoids re-establishing a catch every iteration,
2725 ;; that's only necessary if continue is actually used. A new key is
2726 ;; generated every time, so break and continue apply to their originating
2727 ;; `while' even when recursing.
2729 ;; FIXME: This macro is unintentionally unhygienic with respect to let,
2730 ;; make-symbol, do, throw, catch, lambda, and not.
2732 (define-macro (while cond . body)
2733 (let ((keyvar (make-symbol "while-keyvar")))
2734 `(let ((,keyvar (make-symbol "while-key")))
2738 (let ((break (lambda () (throw ,keyvar #t)))
2739 (continue (lambda () (throw ,keyvar #f))))
2750 ;;; {Module System Macros}
2753 ;; Return a list of expressions that evaluate to the appropriate
2754 ;; arguments for resolve-interface according to SPEC.
2758 (if (memq 'prefix (read-options))
2759 (error "boot-9 must be compiled with #:kw, not :kw")))
2761 (define (compile-interface-spec spec)
2762 (define (make-keyarg sym key quote?)
2763 (cond ((or (memq sym spec)
2767 (list key (list 'quote (cadr rest)))
2768 (list key (cadr rest)))))
2771 (define (map-apply func list)
2772 (map (lambda (args) (apply func args)) list))
2775 '((:select #:select #t)
2777 (:prefix #:prefix #t)
2778 (:renamer #:renamer #f)))
2779 (if (not (pair? (car spec)))
2782 ,@(apply append (map-apply make-keyarg keys)))))
2784 (define (keyword-like-symbol->keyword sym)
2785 (symbol->keyword (string->symbol (substring (symbol->string sym) 1))))
2787 (define (compile-define-module-args args)
2788 ;; Just quote everything except #:use-module and #:use-syntax. We
2789 ;; need to know about all arguments regardless since we want to turn
2790 ;; symbols that look like keywords into real keywords, and the
2791 ;; keyword args in a define-module form are not regular
2792 ;; (i.e. no-backtrace doesn't take a value).
2793 (let loop ((compiled-args `((quote ,(car args))))
2796 (reverse! compiled-args))
2797 ;; symbol in keyword position
2798 ((symbol? (car args))
2800 (cons (keyword-like-symbol->keyword (car args)) (cdr args))))
2801 ((memq (car args) '(#:no-backtrace #:pure))
2802 (loop (cons (car args) compiled-args)
2805 (error "keyword without value:" (car args)))
2806 ((memq (car args) '(#:use-module #:use-syntax))
2807 (loop (cons* `(list ,@(compile-interface-spec (cadr args)))
2811 ((eq? (car args) #:autoload)
2812 (loop (cons* `(quote ,(caddr args))
2813 `(quote ,(cadr args))
2818 (loop (cons* `(quote ,(cadr args))
2823 (defmacro define-module args
2826 (let ((m (process-define-module
2827 (list ,@(compile-define-module-args args)))))
2828 (set-current-module m)
2831 ;; The guts of the use-modules macro. Add the interfaces of the named
2832 ;; modules to the use-list of the current module, in order.
2834 ;; This function is called by "modules.c". If you change it, be sure
2835 ;; to change scm_c_use_module as well.
2837 (define (process-use-modules module-interface-args)
2838 (let ((interfaces (map (lambda (mif-args)
2839 (or (apply resolve-interface mif-args)
2840 (error "no such module" mif-args)))
2841 module-interface-args)))
2842 (call-with-deferred-observers
2844 (module-use-interfaces! (current-module) interfaces)))))
2846 (defmacro use-modules modules
2849 (process-use-modules
2850 (list ,@(map (lambda (m)
2851 `(list ,@(compile-interface-spec m)))
2855 (defmacro use-syntax (spec)
2858 (issue-deprecation-warning
2859 "`use-syntax' is deprecated. Please contact guile-devel for more info.")
2860 (process-use-modules (list (list ,@(compile-interface-spec spec))))
2863 ;; Dirk:FIXME:: This incorrect (according to R5RS) syntax needs to be changed
2864 ;; as soon as guile supports hygienic macros.
2865 (define-syntax define-private
2870 (define-syntax define-public
2872 ((_ (name . args) . body)
2873 (define-public name (lambda args . body)))
2879 (define-syntax defmacro-public
2881 ((_ name args . body)
2883 (defmacro name args . body)
2884 (export-syntax name)))))
2886 ;; Export a local variable
2888 ;; This function is called from "modules.c". If you change it, be
2889 ;; sure to update "modules.c" as well.
2891 (define (module-export! m names)
2892 (let ((public-i (module-public-interface m)))
2893 (for-each (lambda (name)
2894 (let ((var (module-ensure-local-variable! m name)))
2895 (module-add! public-i name var)))
2898 (define (module-replace! m names)
2899 (let ((public-i (module-public-interface m)))
2900 (for-each (lambda (name)
2901 (let ((var (module-ensure-local-variable! m name)))
2902 (set-object-property! var 'replace #t)
2903 (module-add! public-i name var)))
2906 ;; Re-export a imported variable
2908 (define (module-re-export! m names)
2909 (let ((public-i (module-public-interface m)))
2910 (for-each (lambda (name)
2911 (let ((var (module-variable m name)))
2913 (error "Undefined variable:" name))
2914 ((eq? var (module-local-variable m name))
2915 (error "re-exporting local variable:" name))
2917 (module-add! public-i name var)))))
2920 (defmacro export names
2921 `(call-with-deferred-observers
2923 (module-export! (current-module) ',names))))
2925 (defmacro re-export names
2926 `(call-with-deferred-observers
2928 (module-re-export! (current-module) ',names))))
2930 (defmacro export-syntax names
2933 (defmacro re-export-syntax names
2934 `(re-export ,@names))
2936 (define load load-module)
2940 ;;; {Compiler interface}
2942 ;;; The full compiler interface can be found in (system). Here we put a
2943 ;;; few useful procedures into the global namespace.
2945 (module-autoload! the-scm-module
2946 '(system base compile)
2948 compile-time-environment))
2956 (define make-mutable-parameter
2957 (let ((make (lambda (fluid converter)
2961 (fluid-set! fluid (converter (car args))))))))
2962 (lambda (init . converter)
2963 (let ((fluid (make-fluid))
2964 (converter (if (null? converter)
2967 (fluid-set! fluid (converter init))
2968 (make fluid converter)))))
2972 ;;; {Handling of duplicate imported bindings}
2975 ;; Duplicate handlers take the following arguments:
2977 ;; module importing module
2978 ;; name conflicting name
2979 ;; int1 old interface where name occurs
2980 ;; val1 value of binding in old interface
2981 ;; int2 new interface where name occurs
2982 ;; val2 value of binding in new interface
2983 ;; var previous resolution or #f
2984 ;; val value of previous resolution
2986 ;; A duplicate handler can take three alternative actions:
2988 ;; 1. return #f => leave responsibility to next handler
2989 ;; 2. exit with an error
2990 ;; 3. return a variable resolving the conflict
2993 (define duplicate-handlers
2994 (let ((m (make-module 7)))
2996 (define (check module name int1 val1 int2 val2 var val)
2997 (scm-error 'misc-error
2999 "~A: `~A' imported from both ~A and ~A"
3000 (list (module-name module)
3006 (define (warn module name int1 val1 int2 val2 var val)
3007 (format (current-error-port)
3008 "WARNING: ~A: `~A' imported from both ~A and ~A\n"
3009 (module-name module)
3015 (define (replace module name int1 val1 int2 val2 var val)
3016 (let ((old (or (and var (object-property var 'replace) var)
3017 (module-variable int1 name)))
3018 (new (module-variable int2 name)))
3019 (if (object-property old 'replace)
3020 (and (or (eq? old new)
3021 (not (object-property new 'replace)))
3023 (and (object-property new 'replace)
3026 (define (warn-override-core module name int1 val1 int2 val2 var val)
3027 (and (eq? int1 the-scm-module)
3029 (format (current-error-port)
3030 "WARNING: ~A: imported module ~A overrides core binding `~A'\n"
3031 (module-name module)
3034 (module-local-variable int2 name))))
3036 (define (first module name int1 val1 int2 val2 var val)
3037 (or var (module-local-variable int1 name)))
3039 (define (last module name int1 val1 int2 val2 var val)
3040 (module-local-variable int2 name))
3042 (define (noop module name int1 val1 int2 val2 var val)
3045 (set-module-name! m 'duplicate-handlers)
3046 (set-module-kind! m 'interface)
3047 (module-define! m 'check check)
3048 (module-define! m 'warn warn)
3049 (module-define! m 'replace replace)
3050 (module-define! m 'warn-override-core warn-override-core)
3051 (module-define! m 'first first)
3052 (module-define! m 'last last)
3053 (module-define! m 'merge-generics noop)
3054 (module-define! m 'merge-accessors noop)
3057 (define (lookup-duplicates-handlers handler-names)
3059 (map (lambda (handler-name)
3060 (or (module-symbol-local-binding
3061 duplicate-handlers handler-name #f)
3062 (error "invalid duplicate handler name:"
3064 (if (list? handler-names)
3066 (list handler-names)))))
3068 (define default-duplicate-binding-procedures
3069 (make-mutable-parameter #f))
3071 (define default-duplicate-binding-handler
3072 (make-mutable-parameter '(replace warn-override-core warn last)
3073 (lambda (handler-names)
3074 (default-duplicate-binding-procedures
3075 (lookup-duplicates-handlers handler-names))
3080 ;;; {`cond-expand' for SRFI-0 support.}
3082 ;;; This syntactic form expands into different commands or
3083 ;;; definitions, depending on the features provided by the Scheme
3089 ;;; --> (cond-expand <cond-expand-clause>+)
3090 ;;; | (cond-expand <cond-expand-clause>* (else <command-or-definition>))
3091 ;;; <cond-expand-clause>
3092 ;;; --> (<feature-requirement> <command-or-definition>*)
3093 ;;; <feature-requirement>
3094 ;;; --> <feature-identifier>
3095 ;;; | (and <feature-requirement>*)
3096 ;;; | (or <feature-requirement>*)
3097 ;;; | (not <feature-requirement>)
3098 ;;; <feature-identifier>
3099 ;;; --> <a symbol which is the name or alias of a SRFI>
3101 ;;; Additionally, this implementation provides the
3102 ;;; <feature-identifier>s `guile' and `r5rs', so that programs can
3103 ;;; determine the implementation type and the supported standard.
3105 ;;; Currently, the following feature identifiers are supported:
3107 ;;; guile r5rs srfi-0 srfi-4 srfi-6 srfi-13 srfi-14 srfi-55 srfi-61
3109 ;;; Remember to update the features list when adding more SRFIs.
3112 (define %cond-expand-features
3113 ;; Adjust the above comment when changing this.
3116 srfi-0 ;; cond-expand itself
3117 srfi-4 ;; homogenous numeric vectors
3118 srfi-6 ;; open-input-string etc, in the guile core
3119 srfi-13 ;; string library
3120 srfi-14 ;; character sets
3121 srfi-55 ;; require-extension
3122 srfi-61 ;; general cond clause
3125 ;; This table maps module public interfaces to the list of features.
3127 (define %cond-expand-table (make-hash-table 31))
3129 ;; Add one or more features to the `cond-expand' feature list of the
3132 (define (cond-expand-provide module features)
3133 (let ((mod (module-public-interface module)))
3135 (hashq-set! %cond-expand-table mod
3136 (append (hashq-ref %cond-expand-table mod '())
3140 (procedure->memoizing-macro
3142 (let ((clauses (cdr exp))
3143 (syntax-error (lambda (cl)
3144 (error "invalid clause in `cond-expand'" cl))))
3150 (or (memq clause %cond-expand-features)
3151 (let lp ((uses (module-uses (env-module env))))
3154 (hashq-ref %cond-expand-table
3160 ((eq? 'and (car clause))
3161 (let lp ((l (cdr clause)))
3165 (and (test-clause (car l)) (lp (cdr l))))
3167 (syntax-error clause)))))
3168 ((eq? 'or (car clause))
3169 (let lp ((l (cdr clause)))
3173 (or (test-clause (car l)) (lp (cdr l))))
3175 (syntax-error clause)))))
3176 ((eq? 'not (car clause))
3177 (cond ((not (pair? (cdr clause)))
3178 (syntax-error clause))
3179 ((pair? (cddr clause))
3180 ((syntax-error clause))))
3181 (not (test-clause (cadr clause))))
3183 (syntax-error clause))))
3185 (syntax-error clause))))))
3186 (let lp ((c clauses))
3189 (error "Unfulfilled `cond-expand'"))
3192 ((not (pair? (car c)))
3193 (syntax-error (car c)))
3194 ((test-clause (caar c))
3195 `(begin ,@(cdar c)))
3196 ((eq? (caar c) 'else)
3199 `(begin ,@(cdar c)))
3201 (lp (cdr c))))))))))
3203 ;; This procedure gets called from the startup code with a list of
3204 ;; numbers, which are the numbers of the SRFIs to be loaded on startup.
3206 (define (use-srfis srfis)
3207 (process-use-modules
3209 (list (list 'srfi (string->symbol
3210 (string-append "srfi-" (number->string num))))))
3215 ;;; srfi-55: require-extension
3218 (define-macro (require-extension extension-spec)
3219 ;; This macro only handles the srfi extension, which, at present, is
3220 ;; the only one defined by the standard.
3221 (if (not (pair? extension-spec))
3222 (scm-error 'wrong-type-arg "require-extension"
3223 "Not an extension: ~S" (list extension-spec) #f))
3224 (let ((extension (car extension-spec))
3225 (extension-args (cdr extension-spec)))
3228 (let ((use-list '()))
3231 (if (not (integer? i))
3232 (scm-error 'wrong-type-arg "require-extension"
3233 "Invalid srfi name: ~S" (list i) #f))
3234 (let ((srfi-sym (string->symbol
3235 (string-append "srfi-" (number->string i)))))
3236 (if (not (memq srfi-sym %cond-expand-features))
3237 (set! use-list (cons `(use-modules (srfi ,srfi-sym))
3240 (if (pair? use-list)
3241 ;; i.e. (begin (use-modules x) (use-modules y) (use-modules z))
3242 `(begin ,@(reverse! use-list)))))
3245 'wrong-type-arg "require-extension"
3246 "Not a recognized extension type: ~S" (list extension) #f)))))
3250 ;;; {Load emacs interface support if emacs option is given.}
3253 (define (named-module-use! user usee)
3254 (module-use! (resolve-module user) (resolve-interface usee)))
3256 (define (load-emacs-interface)
3257 (and (provided? 'debug-extensions)
3258 (debug-enable 'backtrace))
3259 (named-module-use! '(guile-user) '(ice-9 emacs)))
3263 (define using-readline?
3264 (let ((using-readline? (make-fluid)))
3265 (make-procedure-with-setter
3266 (lambda () (fluid-ref using-readline?))
3267 (lambda (v) (fluid-set! using-readline? v)))))
3270 (let ((guile-user-module (resolve-module '(guile-user))))
3272 ;; Load emacs interface support if emacs option is given.
3273 (if (and (module-defined? guile-user-module 'use-emacs-interface)
3274 (module-ref guile-user-module 'use-emacs-interface))
3275 (load-emacs-interface))
3277 ;; Use some convenient modules (in reverse order)
3279 (set-current-module guile-user-module)
3280 (process-use-modules
3285 (if (provided? 'regex)
3288 (if (provided? 'threads)
3289 '(((ice-9 threads)))
3291 ;; load debugger on demand
3292 (module-autoload! guile-user-module '(ice-9 debugger) '(debug))
3294 ;; Note: SIGFPE, SIGSEGV and SIGBUS are actually "query-only" (see
3295 ;; scmsigs.c scm_sigaction_for_thread), so the handlers setup here have
3297 (let ((old-handlers #f)
3298 (start-repl (module-ref (resolve-interface '(system repl repl))
3300 (signals (if (provided? 'posix)
3301 `((,SIGINT . "User interrupt")
3302 (,SIGFPE . "Arithmetic error")
3304 . "Bad memory access (Segmentation violation)"))
3306 ;; no SIGBUS on mingw
3307 (if (defined? 'SIGBUS)
3308 (set! signals (acons SIGBUS "Bad memory access (bus error)"
3315 (let ((make-handler (lambda (msg)
3317 ;; Make a backup copy of the stack
3318 (fluid-set! before-signal-stack
3319 (fluid-ref the-last-stack))
3327 (map (lambda (sig-msg)
3328 (sigaction (car sig-msg)
3329 (make-handler (cdr sig-msg))))
3332 ;; the protected thunk.
3334 (let ((status (start-repl 'scheme)))
3335 (run-hook exit-hook)
3340 (map (lambda (sig-msg old-handler)
3341 (if (not (car old-handler))
3342 ;; restore original C handler.
3343 (sigaction (car sig-msg) #f)
3344 ;; restore Scheme handler, SIG_IGN or SIG_DFL.
3345 (sigaction (car sig-msg)
3347 (cdr old-handler))))
3348 signals old-handlers))))))
3350 ;;; This hook is run at the very end of an interactive session.
3352 (define exit-hook (make-hook))
3356 ;;; {Deprecated stuff}
3360 (define (feature? sym)
3361 (issue-deprecation-warning
3362 "`feature?' is deprecated. Use `provided?' instead.")
3366 (primitive-load-path "ice-9/deprecated"))
3370 ;;; Place the user in the guile-user module.
3373 ;;; FIXME: annotate ?
3374 ;; (define (syncase exp)
3375 ;; (with-fluids ((expansion-eval-closure
3376 ;; (module-eval-closure (current-module))))
3377 ;; (deannotate/source-properties (sc-expand (annotate exp)))))
3379 (define-module (guile-user))
3381 ;;; boot-9.scm ends here