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
39 (primitive-load-path "ice-9/r4rs")
43 ;;; {Simple Debugging Tools}
46 ;; peek takes any number of arguments, writes them to the
47 ;; current ouput port, and returns the last argument.
48 ;; It is handy to wrap around an expression to look at
49 ;; a value each time is evaluated, e.g.:
51 ;; (+ 10 (troublesome-fn))
52 ;; => (+ 10 (pk 'troublesome-fn-returned (troublesome-fn)))
55 (define (peek . stuff)
60 (car (last-pair stuff)))
64 (define (warn . stuff)
65 (with-output-to-port (current-error-port)
68 (display ";;; WARNING ")
71 (car (last-pair stuff)))))
79 (if (not (memq sym *features*))
80 (set! *features* (cons sym *features*))))
82 ;; Return #t iff FEATURE is available to this Guile interpreter. In SLIB,
83 ;; provided? also checks to see if the module is available. We should do that
86 (define (provided? feature)
87 (and (memq feature *features*) #t))
89 ;; let format alias simple-format until the more complete version is loaded
91 (define format simple-format)
93 ;; this is scheme wrapping the C code so the final pred call is a tail call,
95 (define (string-any char_pred s . rest)
96 (let ((start (if (null? rest)
98 (end (if (or (null? rest) (null? (cdr rest)))
99 (string-length s) (cadr rest))))
100 (if (and (procedure? char_pred)
102 (<= end (string-length s))) ;; let c-code handle range error
103 (or (string-any-c-code char_pred s start (1- end))
104 (char_pred (string-ref s (1- end))))
105 (string-any-c-code char_pred s start end))))
107 ;; this is scheme wrapping the C code so the final pred call is a tail call,
109 (define (string-every char_pred s . rest)
110 (let ((start (if (null? rest)
112 (end (if (or (null? rest) (null? (cdr rest)))
113 (string-length s) (cadr rest))))
114 (if (and (procedure? char_pred)
116 (<= end (string-length s))) ;; let c-code handle range error
117 (and (string-every-c-code char_pred s start (1- end))
118 (char_pred (string-ref s (1- end))))
119 (string-every-c-code char_pred s start end))))
121 ;; A variant of string-fill! that we keep for compatability
123 (define (substring-fill! str start end fill)
124 (string-fill! str fill start end))
128 ;; Before the module system boots, there are no module names. But
129 ;; psyntax does want a module-name definition, so give it one.
130 (define (module-name x)
132 (define (module-add! module sym var)
133 (hashq-set! (%get-pre-modules-obarray) sym var))
134 (define sc-macro 'sc-macro)
135 (define (make-module-ref mod var public?)
138 (equal? mod (module-name (current-module)))
140 (not (module-variable (resolve-module mod) var))))
143 (list (if public? '@ '@@) mod var))))
144 (define (resolve-module . args)
147 (define sc-expand #f)
148 (define sc-expand3 #f)
150 (define install-global-transformer #f)
151 (define syntax-dispatch #f)
152 (define syntax-error #f)
153 (define (annotation? x) #f)
155 (define bound-identifier=? #f)
156 (define datum->syntax-object #f)
157 (define free-identifier=? #f)
158 (define generate-temporaries #f)
159 (define identifier? #f)
160 (define syntax-object->datum #f)
162 (define (void) (if #f #f))
165 (lambda (f first . rest)
168 (let andmap ((first first))
169 (let ((x (car first)) (first (cdr first)))
172 (and (f x) (andmap first)))))
173 (let andmap ((first first) (rest rest))
174 (let ((x (car first))
177 (rest (map cdr rest)))
179 (apply f (cons x xr))
180 (and (apply f (cons x xr)) (andmap first rest)))))))))
182 (define (syncase-error who format-string why what)
183 (%start-stack 'syncase-stack
185 (scm-error 'misc-error who "~A ~S" (list why what) '()))))
187 ;; Until the module system is booted, this will be the current expander.
188 (primitive-load-path "ice-9/psyntax-pp")
190 (define %pre-modules-transformer sc-expand)
194 ;; Before compiling, make sure any symbols are resolved in the (guile)
195 ;; module, the primary location of those symbols, rather than in
196 ;; (guile-user), the default module that we compile in.
199 (set-current-module (resolve-module '(guile))))
203 ;;; Depends on: features, eval-case
206 (define-syntax define-macro
209 ((_ (macro . args) . body)
210 (syntax (define-macro macro (lambda args . body))))
211 ((_ macro transformer)
215 (let ((v (syntax-object->datum y)))
216 (datum->syntax-object y (apply transformer (cdr v)))))))))))
218 (define-syntax defmacro
221 ((_ macro args . body)
222 (syntax (define-macro macro (lambda args . body)))))))
230 ;;; Depends on: defmacro
233 (defmacro begin-deprecated forms
234 (if (include-deprecated-features)
240 ;;; {Trivial Functions}
243 (define (identity x) x)
244 (define (and=> value procedure) (and value (procedure value)))
245 (define call/cc call-with-current-continuation)
247 ;;; apply-to-args is functionally redundant with apply and, worse,
248 ;;; is less general than apply since it only takes two arguments.
250 ;;; On the other hand, apply-to-args is a syntacticly convenient way to
251 ;;; perform binding in many circumstances when the "let" family of
252 ;;; of forms don't cut it. E.g.:
254 ;;; (apply-to-args (return-3d-mouse-coords)
259 (define (apply-to-args args fn) (apply fn args))
261 (defmacro false-if-exception (expr)
262 `(catch #t (lambda () ,expr)
267 ;;; {General Properties}
270 ;; This is a more modern interface to properties. It will replace all
271 ;; other property-like things eventually.
273 (define (make-object-property)
274 (let ((prop (primitive-make-property #f)))
275 (make-procedure-with-setter
276 (lambda (obj) (primitive-property-ref prop obj))
277 (lambda (obj val) (primitive-property-set! prop obj val)))))
281 ;;; {Symbol Properties}
284 (define (symbol-property sym prop)
285 (let ((pair (assoc prop (symbol-pref sym))))
286 (and pair (cdr pair))))
288 (define (set-symbol-property! sym prop val)
289 (let ((pair (assoc prop (symbol-pref sym))))
292 (symbol-pset! sym (acons prop val (symbol-pref sym))))))
294 (define (symbol-property-remove! sym prop)
295 (let ((pair (assoc prop (symbol-pref sym))))
297 (symbol-pset! sym (delq! pair (symbol-pref sym))))))
304 (define (array-shape a)
305 (map (lambda (ind) (if (number? ind) (list 0 (+ -1 ind)) ind))
306 (array-dimensions a)))
313 (define (kw-arg-ref args kw)
314 (let ((rem (member kw args)))
315 (and rem (pair? (cdr rem)) (cadr rem))))
322 (define (struct-layout s)
323 (struct-ref (struct-vtable s) vtable-index-layout))
330 ;; Printing records: by default, records are printed as
332 ;; #<type-name field1: val1 field2: val2 ...>
334 ;; You can change that by giving a custom printing function to
335 ;; MAKE-RECORD-TYPE (after the list of field symbols). This function
336 ;; will be called like
338 ;; (<printer> object port)
340 ;; It should print OBJECT to PORT.
342 (define (inherit-print-state old-port new-port)
343 (if (get-print-state old-port)
344 (port-with-print-state new-port (get-print-state old-port))
347 ;; 0: type-name, 1: fields
348 (define record-type-vtable
349 (make-vtable-vtable "prpr" 0
351 (cond ((eq? s record-type-vtable)
352 (display "#<record-type-vtable>" p))
354 (display "#<record-type " p)
355 (display (record-type-name s) p)
358 (define (record-type? obj)
359 (and (struct? obj) (eq? record-type-vtable (struct-vtable obj))))
361 (define (make-record-type type-name fields . opt)
362 (let ((printer-fn (and (pair? opt) (car opt))))
363 (let ((struct (make-struct record-type-vtable 0
366 (map (lambda (f) "pw") fields)))
370 (display type-name p)
371 (let loop ((fields fields)
374 ((not (null? fields))
376 (display (car fields) p)
378 (display (struct-ref s off) p)
379 (loop (cdr fields) (+ 1 off)))))
382 (copy-tree fields))))
383 ;; Temporary solution: Associate a name to the record type descriptor
384 ;; so that the object system can create a wrapper class for it.
385 (set-struct-vtable-name! struct (if (symbol? type-name)
387 (string->symbol type-name)))
390 (define (record-type-name obj)
391 (if (record-type? obj)
392 (struct-ref obj vtable-offset-user)
393 (error 'not-a-record-type obj)))
395 (define (record-type-fields obj)
396 (if (record-type? obj)
397 (struct-ref obj (+ 1 vtable-offset-user))
398 (error 'not-a-record-type obj)))
400 (define (record-constructor rtd . opt)
401 (let ((field-names (if (pair? opt) (car opt) (record-type-fields rtd))))
403 `(lambda ,field-names
404 (make-struct ',rtd 0 ,@(map (lambda (f)
405 (if (memq f field-names)
408 (record-type-fields rtd)))))))
410 (define (record-predicate rtd)
411 (lambda (obj) (and (struct? obj) (eq? rtd (struct-vtable obj)))))
413 (define (%record-type-error rtd obj) ;; private helper
414 (or (eq? rtd (record-type-descriptor obj))
415 (scm-error 'wrong-type-arg "%record-type-check"
416 "Wrong type record (want `~S'): ~S"
417 (list (record-type-name rtd) obj)
420 (define (record-accessor rtd field-name)
421 (let ((pos (list-index (record-type-fields rtd) field-name)))
423 (error 'no-such-field field-name))
425 (if (eq? (struct-vtable obj) rtd)
427 (%record-type-error rtd obj)))))
429 (define (record-modifier rtd field-name)
430 (let ((pos (list-index (record-type-fields rtd) field-name)))
432 (error 'no-such-field field-name))
434 (if (eq? (struct-vtable obj) rtd)
435 (struct-set! obj pos val)
436 (%record-type-error rtd obj)))))
438 (define (record? obj)
439 (and (struct? obj) (record-type? (struct-vtable obj))))
441 (define (record-type-descriptor obj)
444 (error 'not-a-record obj)))
453 (define (->bool x) (not (not x)))
460 (define (symbol-append . args)
461 (string->symbol (apply string-append (map symbol->string args))))
463 (define (list->symbol . args)
464 (string->symbol (apply list->string args)))
466 (define (symbol . args)
467 (string->symbol (apply string args)))
474 (define (list-index l k)
480 (loop (+ n 1) (cdr l))))))
484 ;;; {and-map and or-map}
486 ;;; (and-map fn lst) is like (and (fn (car lst)) (fn (cadr lst)) (fn...) ...)
487 ;;; (or-map fn lst) is like (or (fn (car lst)) (fn (cadr lst)) (fn...) ...)
492 ;; Apply f to successive elements of l until exhaustion or f returns #f.
493 ;; If returning early, return #f. Otherwise, return the last value returned
494 ;; by f. If f has never been called because l is empty, return #t.
496 (define (and-map f lst)
497 (let loop ((result #t)
502 (loop (f (car l)) (cdr l))))))
506 ;; Apply f to successive elements of l until exhaustion or while f returns #f.
507 ;; If returning early, return the return value of f.
509 (define (or-map f lst)
510 (let loop ((result #f)
514 (loop (f (car l)) (cdr l))))))
518 (if (provided? 'posix)
519 (primitive-load-path "ice-9/posix"))
521 (if (provided? 'socket)
522 (primitive-load-path "ice-9/networking"))
524 ;; For reference, Emacs file-exists-p uses stat in this same way.
525 ;; ENHANCE-ME: Catching an exception from stat is a bit wasteful, do this in
526 ;; C where all that's needed is to inspect the return from stat().
528 (if (provided? 'posix)
530 (->bool (false-if-exception (stat str))))
532 (let ((port (catch 'system-error (lambda () (open-file str OPEN_READ))
534 (if port (begin (close-port port) #t)
537 (define file-is-directory?
538 (if (provided? 'posix)
540 (eq? (stat:type (stat str)) 'directory))
542 (let ((port (catch 'system-error
543 (lambda () (open-file (string-append str "/.")
546 (if port (begin (close-port port) #t)
549 (define (has-suffix? str suffix)
550 (string-suffix? suffix str))
552 (define (system-error-errno args)
553 (if (eq? (car args) 'system-error)
554 (car (list-ref args 4))
562 (define (error . args)
565 (scm-error 'misc-error #f "?" #f #f)
566 (let loop ((msg "~A")
568 (if (not (null? rest))
569 (loop (string-append msg " ~S")
571 (scm-error 'misc-error #f msg args #f)))))
573 ;; bad-throw is the hook that is called upon a throw to a an unhandled
574 ;; key (unless the throw has four arguments, in which case
575 ;; it's usually interpreted as an error throw.)
576 ;; If the key has a default handler (a throw-handler-default property),
577 ;; it is applied to the throw.
579 (define (bad-throw key . args)
580 (let ((default (symbol-property key 'throw-handler-default)))
581 (or (and default (apply default key args))
582 (apply error "unhandled-exception:" key args))))
586 (define (tm:sec obj) (vector-ref obj 0))
587 (define (tm:min obj) (vector-ref obj 1))
588 (define (tm:hour obj) (vector-ref obj 2))
589 (define (tm:mday obj) (vector-ref obj 3))
590 (define (tm:mon obj) (vector-ref obj 4))
591 (define (tm:year obj) (vector-ref obj 5))
592 (define (tm:wday obj) (vector-ref obj 6))
593 (define (tm:yday obj) (vector-ref obj 7))
594 (define (tm:isdst obj) (vector-ref obj 8))
595 (define (tm:gmtoff obj) (vector-ref obj 9))
596 (define (tm:zone obj) (vector-ref obj 10))
598 (define (set-tm:sec obj val) (vector-set! obj 0 val))
599 (define (set-tm:min obj val) (vector-set! obj 1 val))
600 (define (set-tm:hour obj val) (vector-set! obj 2 val))
601 (define (set-tm:mday obj val) (vector-set! obj 3 val))
602 (define (set-tm:mon obj val) (vector-set! obj 4 val))
603 (define (set-tm:year obj val) (vector-set! obj 5 val))
604 (define (set-tm:wday obj val) (vector-set! obj 6 val))
605 (define (set-tm:yday obj val) (vector-set! obj 7 val))
606 (define (set-tm:isdst obj val) (vector-set! obj 8 val))
607 (define (set-tm:gmtoff obj val) (vector-set! obj 9 val))
608 (define (set-tm:zone obj val) (vector-set! obj 10 val))
610 (define (tms:clock obj) (vector-ref obj 0))
611 (define (tms:utime obj) (vector-ref obj 1))
612 (define (tms:stime obj) (vector-ref obj 2))
613 (define (tms:cutime obj) (vector-ref obj 3))
614 (define (tms:cstime obj) (vector-ref obj 4))
616 (define file-position ftell)
617 (define (file-set-position port offset . whence)
618 (let ((whence (if (eq? whence '()) SEEK_SET (car whence))))
619 (seek port offset whence)))
621 (define (move->fdes fd/port fd)
622 (cond ((integer? fd/port)
623 (dup->fdes fd/port fd)
627 (primitive-move->fdes fd/port fd)
628 (set-port-revealed! fd/port 1)
631 (define (release-port-handle port)
632 (let ((revealed (port-revealed port)))
634 (set-port-revealed! port (- revealed 1)))))
636 (define (dup->port port/fd mode . maybe-fd)
637 (let ((port (fdopen (apply dup->fdes port/fd maybe-fd)
640 (set-port-revealed! port 1))
643 (define (dup->inport port/fd . maybe-fd)
644 (apply dup->port port/fd "r" maybe-fd))
646 (define (dup->outport port/fd . maybe-fd)
647 (apply dup->port port/fd "w" maybe-fd))
649 (define (dup port/fd . maybe-fd)
650 (if (integer? port/fd)
651 (apply dup->fdes port/fd maybe-fd)
652 (apply dup->port port/fd (port-mode port/fd) maybe-fd)))
654 (define (duplicate-port port modes)
655 (dup->port port modes))
657 (define (fdes->inport fdes)
658 (let loop ((rest-ports (fdes->ports fdes)))
659 (cond ((null? rest-ports)
660 (let ((result (fdopen fdes "r")))
661 (set-port-revealed! result 1)
663 ((input-port? (car rest-ports))
664 (set-port-revealed! (car rest-ports)
665 (+ (port-revealed (car rest-ports)) 1))
668 (loop (cdr rest-ports))))))
670 (define (fdes->outport fdes)
671 (let loop ((rest-ports (fdes->ports fdes)))
672 (cond ((null? rest-ports)
673 (let ((result (fdopen fdes "w")))
674 (set-port-revealed! result 1)
676 ((output-port? (car rest-ports))
677 (set-port-revealed! (car rest-ports)
678 (+ (port-revealed (car rest-ports)) 1))
681 (loop (cdr rest-ports))))))
683 (define (port->fdes port)
684 (set-port-revealed! port (+ (port-revealed port) 1))
687 (define (setenv name value)
689 (putenv (string-append name "=" value))
692 (define (unsetenv name)
693 "Remove the entry for NAME from the environment."
701 ;;; Here for backward compatability
703 (define scheme-file-suffix (lambda () ".scm"))
705 (define (in-vicinity vicinity file)
706 (let ((tail (let ((len (string-length vicinity)))
709 (string-ref vicinity (- len 1))))))
710 (string-append vicinity
719 ;;; {Help for scm_shell}
721 ;;; The argument-processing code used by Guile-based shells generates
722 ;;; Scheme code based on the argument list. This page contains help
723 ;;; functions for the code it generates.
726 (define (command-line) (program-arguments))
728 ;; This is mostly for the internal use of the code generated by
729 ;; scm_compile_shell_switches.
731 (define (turn-on-debugging)
732 (debug-enable 'debug)
733 (debug-enable 'backtrace)
734 (read-enable 'positions))
736 (define (load-user-init)
737 (let* ((home (or (getenv "HOME")
738 (false-if-exception (passwd:dir (getpwuid (getuid))))
739 "/")) ;; fallback for cygwin etc.
740 (init-file (in-vicinity home ".guile")))
741 (if (file-exists? init-file)
742 (primitive-load init-file))))
746 ;;; {The interpreter stack}
749 (defmacro start-stack (tag exp)
750 `(%start-stack ,tag (lambda () ,exp)))
754 ;;; {Loading by paths}
757 ;;; Load a Scheme source file named NAME, searching for it in the
758 ;;; directories listed in %load-path, and applying each of the file
759 ;;; name extensions listed in %load-extensions.
760 (define (load-from-path name)
761 (start-stack 'load-stack
762 (primitive-load-path name)))
764 (define %load-verbosely #f)
765 (define (assert-load-verbosity v) (set! %load-verbosely v))
767 (define (%load-announce file)
769 (with-output-to-port (current-error-port)
777 (set! %load-hook %load-announce)
779 (define (load name . reader)
780 (with-fluid* current-reader (and (pair? reader) (car reader))
782 (start-stack 'load-stack
783 (primitive-load name)))))
787 ;;; {Transcendental Functions}
789 ;;; Derived from "Transcen.scm", Complex trancendental functions for SCM.
790 ;;; Written by Jerry D. Hedden, (C) FSF.
791 ;;; See the file `COPYING' for terms applying to this program.
795 (let ((integer-expt integer-expt))
797 (cond ((and (exact? z2) (integer? z2))
798 (integer-expt z1 z2))
799 ((and (real? z2) (real? z1) (>= z1 0))
802 (exp (* z2 (log z1))))))))
805 (if (real? z) ($sinh z)
806 (let ((x (real-part z)) (y (imag-part z)))
807 (make-rectangular (* ($sinh x) ($cos y))
808 (* ($cosh x) ($sin y))))))
810 (if (real? z) ($cosh z)
811 (let ((x (real-part z)) (y (imag-part z)))
812 (make-rectangular (* ($cosh x) ($cos y))
813 (* ($sinh x) ($sin y))))))
815 (if (real? z) ($tanh z)
816 (let* ((x (* 2 (real-part z)))
817 (y (* 2 (imag-part z)))
818 (w (+ ($cosh x) ($cos y))))
819 (make-rectangular (/ ($sinh x) w) (/ ($sin y) w)))))
822 (if (real? z) ($asinh z)
823 (log (+ z (sqrt (+ (* z z) 1))))))
826 (if (and (real? z) (>= z 1))
828 (log (+ z (sqrt (- (* z z) 1))))))
831 (if (and (real? z) (> z -1) (< z 1))
833 (/ (log (/ (+ 1 z) (- 1 z))) 2)))
836 (if (real? z) ($sin z)
837 (let ((x (real-part z)) (y (imag-part z)))
838 (make-rectangular (* ($sin x) ($cosh y))
839 (* ($cos x) ($sinh y))))))
841 (if (real? z) ($cos z)
842 (let ((x (real-part z)) (y (imag-part z)))
843 (make-rectangular (* ($cos x) ($cosh y))
844 (- (* ($sin x) ($sinh y)))))))
846 (if (real? z) ($tan z)
847 (let* ((x (* 2 (real-part z)))
848 (y (* 2 (imag-part z)))
849 (w (+ ($cos x) ($cosh y))))
850 (make-rectangular (/ ($sin x) w) (/ ($sinh y) w)))))
853 (if (and (real? z) (>= z -1) (<= z 1))
855 (* -i (asinh (* +i z)))))
858 (if (and (real? z) (>= z -1) (<= z 1))
860 (+ (/ (angle -1) 2) (* +i (asinh (* +i z))))))
864 (if (real? z) ($atan z)
865 (/ (log (/ (- +i z) (+ +i z))) +2i))
870 ;;; {Reader Extensions}
872 ;;; Reader code for various "#c" forms.
875 (read-hash-extend #\' (lambda (c port)
878 (define read-eval? (make-fluid))
879 (fluid-set! read-eval? #f)
880 (read-hash-extend #\.
882 (if (fluid-ref read-eval?)
883 (eval (read port) (interaction-environment))
885 "#. read expansion found and read-eval? is #f."))))
889 ;;; {Command Line Options}
892 (define (get-option argv kw-opts kw-args return)
897 ((or (not (eq? #\- (string-ref (car argv) 0)))
898 (eq? (string-length (car argv)) 1))
899 (return 'normal-arg (car argv) (cdr argv)))
901 ((eq? #\- (string-ref (car argv) 1))
902 (let* ((kw-arg-pos (or (string-index (car argv) #\=)
903 (string-length (car argv))))
904 (kw (symbol->keyword (substring (car argv) 2 kw-arg-pos)))
905 (kw-opt? (member kw kw-opts))
906 (kw-arg? (member kw kw-args))
907 (arg (or (and (not (eq? kw-arg-pos (string-length (car argv))))
908 (substring (car argv)
910 (string-length (car argv))))
912 (begin (set! argv (cdr argv)) (car argv))))))
913 (if (or kw-opt? kw-arg?)
914 (return kw arg (cdr argv))
915 (return 'usage-error kw (cdr argv)))))
918 (let* ((char (substring (car argv) 1 2))
919 (kw (symbol->keyword char)))
923 (let* ((rest-car (substring (car argv) 2 (string-length (car argv))))
924 (new-argv (if (= 0 (string-length rest-car))
926 (cons (string-append "-" rest-car) (cdr argv)))))
927 (return kw #f new-argv)))
930 (let* ((rest-car (substring (car argv) 2 (string-length (car argv))))
931 (arg (if (= 0 (string-length rest-car))
934 (new-argv (if (= 0 (string-length rest-car))
937 (return kw arg new-argv)))
939 (else (return 'usage-error kw argv)))))))
941 (define (for-next-option proc argv kw-opts kw-args)
942 (let loop ((argv argv))
943 (get-option argv kw-opts kw-args
944 (lambda (opt opt-arg argv)
945 (and opt (proc opt opt-arg argv loop))))))
947 (define (display-usage-report kw-desc)
950 (or (eq? (car kw) #t)
953 (help (cadr opt-desc))
954 (opts (car opt-desc))
955 (opts-proper (if (string? (car opts)) (cdr opts) opts))
956 (arg-name (if (string? (car opts))
957 (string-append "<" (car opts) ">")
959 (left-part (string-append
960 (with-output-to-string
962 (map (lambda (x) (display (keyword->symbol x)) (display " "))
965 (middle-part (if (and (< (string-length left-part) 30)
966 (< (string-length help) 40))
967 (make-string (- 30 (string-length left-part)) #\ )
970 (display middle-part)
977 (define (transform-usage-lambda cases)
978 (let* ((raw-usage (delq! 'else (map car cases)))
979 (usage-sans-specials (map (lambda (x)
980 (or (and (not (list? x)) x)
981 (and (symbol? (car x)) #t)
982 (and (boolean? (car x)) #t)
985 (usage-desc (delq! #t usage-sans-specials))
986 (kw-desc (map car usage-desc))
987 (kw-opts (apply append (map (lambda (x) (and (not (string? (car x))) x)) kw-desc)))
988 (kw-args (apply append (map (lambda (x) (and (string? (car x)) (cdr x))) kw-desc)))
989 (transmogrified-cases (map (lambda (case)
990 (cons (let ((opts (car case)))
991 (if (or (boolean? opts) (eq? 'else opts))
994 ((symbol? (car opts)) opts)
995 ((boolean? (car opts)) opts)
996 ((string? (caar opts)) (cdar opts))
1000 `(let ((%display-usage (lambda () (display-usage-report ',usage-desc))))
1002 (let %next-arg ((%argv %argv))
1006 (lambda (%opt %arg %new-argv)
1008 ,@ transmogrified-cases))))))))
1013 ;;; {Low Level Modules}
1015 ;;; These are the low level data structures for modules.
1017 ;;; Every module object is of the type 'module-type', which is a record
1018 ;;; consisting of the following members:
1020 ;;; - eval-closure: the function that defines for its module the strategy that
1021 ;;; shall be followed when looking up symbols in the module.
1023 ;;; An eval-closure is a function taking two arguments: the symbol to be
1024 ;;; looked up and a boolean value telling whether a binding for the symbol
1025 ;;; should be created if it does not exist yet. If the symbol lookup
1026 ;;; succeeded (either because an existing binding was found or because a new
1027 ;;; binding was created), a variable object representing the binding is
1028 ;;; returned. Otherwise, the value #f is returned. Note that the eval
1029 ;;; closure does not take the module to be searched as an argument: During
1030 ;;; construction of the eval-closure, the eval-closure has to store the
1031 ;;; module it belongs to in its environment. This means, that any
1032 ;;; eval-closure can belong to only one module.
1034 ;;; The eval-closure of a module can be defined arbitrarily. However, three
1035 ;;; special cases of eval-closures are to be distinguished: During startup
1036 ;;; the module system is not yet activated. In this phase, no modules are
1037 ;;; defined and all bindings are automatically stored by the system in the
1038 ;;; pre-modules-obarray. Since no eval-closures exist at this time, the
1039 ;;; functions which require an eval-closure as their argument need to be
1040 ;;; passed the value #f.
1042 ;;; The other two special cases of eval-closures are the
1043 ;;; standard-eval-closure and the standard-interface-eval-closure. Both
1044 ;;; behave equally for the case that no new binding is to be created. The
1045 ;;; difference between the two comes in, when the boolean argument to the
1046 ;;; eval-closure indicates that a new binding shall be created if it is not
1049 ;;; Given that no new binding shall be created, both standard eval-closures
1050 ;;; define the following standard strategy of searching bindings in the
1051 ;;; module: First, the module's obarray is searched for the symbol. Second,
1052 ;;; if no binding for the symbol was found in the module's obarray, the
1053 ;;; module's binder procedure is exececuted. If this procedure did not
1054 ;;; return a binding for the symbol, the modules referenced in the module's
1055 ;;; uses list are recursively searched for a binding of the symbol. If the
1056 ;;; binding can not be found in these modules also, the symbol lookup has
1059 ;;; If a new binding shall be created, the standard-interface-eval-closure
1060 ;;; immediately returns indicating failure. That is, it does not even try
1061 ;;; to look up the symbol. In contrast, the standard-eval-closure would
1062 ;;; first search the obarray, and if no binding was found there, would
1063 ;;; create a new binding in the obarray, therefore not calling the binder
1064 ;;; procedure or searching the modules in the uses list.
1066 ;;; The explanation of the following members obarray, binder and uses
1067 ;;; assumes that the symbol lookup follows the strategy that is defined in
1068 ;;; the standard-eval-closure and the standard-interface-eval-closure.
1070 ;;; - obarray: a hash table that maps symbols to variable objects. In this
1071 ;;; hash table, the definitions are found that are local to the module (that
1072 ;;; is, not imported from other modules). When looking up bindings in the
1073 ;;; module, this hash table is searched first.
1075 ;;; - binder: either #f or a function taking a module and a symbol argument.
1076 ;;; If it is a function it is called after the obarray has been
1077 ;;; unsuccessfully searched for a binding. It then can provide bindings
1078 ;;; that would otherwise not be found locally in the module.
1080 ;;; - uses: a list of modules from which non-local bindings can be inherited.
1081 ;;; These modules are the third place queried for bindings after the obarray
1082 ;;; has been unsuccessfully searched and the binder function did not deliver
1083 ;;; a result either.
1085 ;;; - transformer: either #f or a function taking a scheme expression as
1086 ;;; delivered by read. If it is a function, it will be called to perform
1087 ;;; syntax transformations (e. g. makro expansion) on the given scheme
1088 ;;; expression. The output of the transformer function will then be passed
1089 ;;; to Guile's internal memoizer. This means that the output must be valid
1090 ;;; scheme code. The only exception is, that the output may make use of the
1091 ;;; syntax extensions provided to identify the modules that a binding
1094 ;;; - name: the name of the module. This is used for all kinds of printing
1095 ;;; outputs. In certain places the module name also serves as a way of
1096 ;;; identification. When adding a module to the uses list of another
1097 ;;; module, it is made sure that the new uses list will not contain two
1098 ;;; modules of the same name.
1100 ;;; - kind: classification of the kind of module. The value is (currently?)
1101 ;;; only used for printing. It has no influence on how a module is treated.
1102 ;;; Currently the following values are used when setting the module kind:
1103 ;;; 'module, 'directory, 'interface, 'custom-interface. If no explicit kind
1104 ;;; is set, it defaults to 'module.
1106 ;;; - duplicates-handlers: a list of procedures that get called to make a
1107 ;;; choice between two duplicate bindings when name clashes occur. See the
1108 ;;; `duplicate-handlers' global variable below.
1110 ;;; - observers: a list of procedures that get called when the module is
1113 ;;; - weak-observers: a weak-key hash table of procedures that get called
1114 ;;; when the module is modified. See `module-observe-weak' for details.
1116 ;;; In addition, the module may (must?) contain a binding for
1117 ;;; `%module-public-interface'. This variable should be bound to a module
1118 ;;; representing the exported interface of a module. See the
1119 ;;; `module-public-interface' and `module-export!' procedures.
1121 ;;; !!! warning: The interface to lazy binder procedures is going
1122 ;;; to be changed in an incompatible way to permit all the basic
1123 ;;; module ops to be virtualized.
1125 ;;; (make-module size use-list lazy-binding-proc) => module
1126 ;;; module-{obarray,uses,binder}[|-set!]
1127 ;;; (module? obj) => [#t|#f]
1128 ;;; (module-locally-bound? module symbol) => [#t|#f]
1129 ;;; (module-bound? module symbol) => [#t|#f]
1130 ;;; (module-symbol-locally-interned? module symbol) => [#t|#f]
1131 ;;; (module-symbol-interned? module symbol) => [#t|#f]
1132 ;;; (module-local-variable module symbol) => [#<variable ...> | #f]
1133 ;;; (module-variable module symbol) => [#<variable ...> | #f]
1134 ;;; (module-symbol-binding module symbol opt-value)
1135 ;;; => [ <obj> | opt-value | an error occurs ]
1136 ;;; (module-make-local-var! module symbol) => #<variable...>
1137 ;;; (module-add! module symbol var) => unspecified
1138 ;;; (module-remove! module symbol) => unspecified
1139 ;;; (module-for-each proc module) => unspecified
1140 ;;; (make-scm-module) => module ; a lazy copy of the symhash module
1141 ;;; (set-current-module module) => unspecified
1142 ;;; (current-module) => #<module...>
1148 ;;; {Printing Modules}
1151 ;; This is how modules are printed. You can re-define it.
1152 ;; (Redefining is actually more complicated than simply redefining
1153 ;; %print-module because that would only change the binding and not
1154 ;; the value stored in the vtable that determines how record are
1157 (define (%print-module mod port) ; unused args: depth length style table)
1159 (display (or (module-kind mod) "module") port)
1160 (let ((name (module-name mod)))
1164 (display name port))))
1166 (display (number->string (object-address mod) 16) port)
1171 ;; A module is characterized by an obarray in which local symbols
1172 ;; are interned, a list of modules, "uses", from which non-local
1173 ;; bindings can be inherited, and an optional lazy-binder which
1174 ;; is a (CLOSURE module symbol) which, as a last resort, can provide
1175 ;; bindings that would otherwise not be found locally in the module.
1177 ;; NOTE: If you change anything here, you also need to change
1178 ;; libguile/modules.h.
1181 (make-record-type 'module
1182 '(obarray uses binder eval-closure transformer name kind
1183 duplicates-handlers import-obarray
1184 observers weak-observers)
1187 ;; make-module &opt size uses binder
1189 ;; Create a new module, perhaps with a particular size of obarray,
1190 ;; initial uses list, or binding procedure.
1195 (define (parse-arg index default)
1196 (if (> (length args) index)
1197 (list-ref args index)
1200 (define %default-import-size
1201 ;; Typical number of imported bindings actually used by a module.
1204 (if (> (length args) 3)
1205 (error "Too many args to make-module." args))
1207 (let ((size (parse-arg 0 31))
1208 (uses (parse-arg 1 '()))
1209 (binder (parse-arg 2 #f)))
1211 (if (not (integer? size))
1212 (error "Illegal size to make-module." size))
1213 (if (not (and (list? uses)
1214 (and-map module? uses)))
1215 (error "Incorrect use list." uses))
1216 (if (and binder (not (procedure? binder)))
1218 "Lazy-binder expected to be a procedure or #f." binder))
1220 (let ((module (module-constructor (make-hash-table size)
1221 uses binder #f %pre-modules-transformer
1223 (make-hash-table %default-import-size)
1225 (make-weak-key-hash-table 31))))
1227 ;; We can't pass this as an argument to module-constructor,
1228 ;; because we need it to close over a pointer to the module
1230 (set-module-eval-closure! module (standard-eval-closure module))
1234 (define module-constructor (record-constructor module-type))
1235 (define module-obarray (record-accessor module-type 'obarray))
1236 (define set-module-obarray! (record-modifier module-type 'obarray))
1237 (define module-uses (record-accessor module-type 'uses))
1238 (define set-module-uses! (record-modifier module-type 'uses))
1239 (define module-binder (record-accessor module-type 'binder))
1240 (define set-module-binder! (record-modifier module-type 'binder))
1242 ;; NOTE: This binding is used in libguile/modules.c.
1243 (define module-eval-closure (record-accessor module-type 'eval-closure))
1245 (define module-transformer (record-accessor module-type 'transformer))
1246 (define set-module-transformer! (record-modifier module-type 'transformer))
1247 ;; (define module-name (record-accessor module-type 'name)) wait until mods are booted
1248 (define set-module-name! (record-modifier module-type 'name))
1249 (define module-kind (record-accessor module-type 'kind))
1250 (define set-module-kind! (record-modifier module-type 'kind))
1251 (define module-duplicates-handlers
1252 (record-accessor module-type 'duplicates-handlers))
1253 (define set-module-duplicates-handlers!
1254 (record-modifier module-type 'duplicates-handlers))
1255 (define module-observers (record-accessor module-type 'observers))
1256 (define set-module-observers! (record-modifier module-type 'observers))
1257 (define module-weak-observers (record-accessor module-type 'weak-observers))
1258 (define module? (record-predicate module-type))
1260 (define module-import-obarray (record-accessor module-type 'import-obarray))
1262 (define set-module-eval-closure!
1263 (let ((setter (record-modifier module-type 'eval-closure)))
1264 (lambda (module closure)
1265 (setter module closure)
1266 ;; Make it possible to lookup the module from the environment.
1267 ;; This implementation is correct since an eval closure can belong
1268 ;; to maximally one module.
1269 (set-procedure-property! closure 'module module))))
1273 ;;; {Observer protocol}
1276 (define (module-observe module proc)
1277 (set-module-observers! module (cons proc (module-observers module)))
1280 (define (module-observe-weak module observer-id . proc)
1281 ;; Register PROC as an observer of MODULE under name OBSERVER-ID (which can
1282 ;; be any Scheme object). PROC is invoked and passed MODULE any time
1283 ;; MODULE is modified. PROC gets unregistered when OBSERVER-ID gets GC'd
1284 ;; (thus, it is never unregistered if OBSERVER-ID is an immediate value,
1287 ;; The two-argument version is kept for backward compatibility: when called
1288 ;; with two arguments, the observer gets unregistered when closure PROC
1289 ;; gets GC'd (making it impossible to use an anonymous lambda for PROC).
1291 (let ((proc (if (null? proc) observer-id (car proc))))
1292 (hashq-set! (module-weak-observers module) observer-id proc)))
1294 (define (module-unobserve token)
1295 (let ((module (car token))
1298 (hash-remove! (module-weak-observers module) id)
1299 (set-module-observers! module (delq1! id (module-observers module)))))
1302 (define module-defer-observers #f)
1303 (define module-defer-observers-mutex (make-mutex 'recursive))
1304 (define module-defer-observers-table (make-hash-table))
1306 (define (module-modified m)
1307 (if module-defer-observers
1308 (hash-set! module-defer-observers-table m #t)
1309 (module-call-observers m)))
1311 ;;; This function can be used to delay calls to observers so that they
1312 ;;; can be called once only in the face of massive updating of modules.
1314 (define (call-with-deferred-observers thunk)
1317 (lock-mutex module-defer-observers-mutex)
1318 (set! module-defer-observers #t))
1321 (set! module-defer-observers #f)
1322 (hash-for-each (lambda (m dummy)
1323 (module-call-observers m))
1324 module-defer-observers-table)
1325 (hash-clear! module-defer-observers-table)
1326 (unlock-mutex module-defer-observers-mutex))))
1328 (define (module-call-observers m)
1329 (for-each (lambda (proc) (proc m)) (module-observers m))
1331 ;; We assume that weak observers don't (un)register themselves as they are
1332 ;; called since this would preclude proper iteration over the hash table
1334 (hash-for-each (lambda (id proc) (proc m)) (module-weak-observers m)))
1338 ;;; {Module Searching in General}
1340 ;;; We sometimes want to look for properties of a symbol
1341 ;;; just within the obarray of one module. If the property
1342 ;;; holds, then it is said to hold ``locally'' as in, ``The symbol
1343 ;;; DISPLAY is locally rebound in the module `safe-guile'.''
1346 ;;; Other times, we want to test for a symbol property in the obarray
1347 ;;; of M and, if it is not found there, try each of the modules in the
1348 ;;; uses list of M. This is the normal way of testing for some
1349 ;;; property, so we state these properties without qualification as
1350 ;;; in: ``The symbol 'fnord is interned in module M because it is
1351 ;;; interned locally in module M2 which is a member of the uses list
1355 ;; module-search fn m
1357 ;; return the first non-#f result of FN applied to M and then to
1358 ;; the modules in the uses of m, and so on recursively. If all applications
1359 ;; return #f, then so does this function.
1361 (define (module-search fn m v)
1364 (or (module-search fn (car pos) v)
1367 (loop (module-uses m))))
1370 ;;; {Is a symbol bound in a module?}
1372 ;;; Symbol S in Module M is bound if S is interned in M and if the binding
1373 ;;; of S in M has been set to some well-defined value.
1376 ;; module-locally-bound? module symbol
1378 ;; Is a symbol bound (interned and defined) locally in a given module?
1380 (define (module-locally-bound? m v)
1381 (let ((var (module-local-variable m v)))
1383 (variable-bound? var))))
1385 ;; module-bound? module symbol
1387 ;; Is a symbol bound (interned and defined) anywhere in a given module
1390 (define (module-bound? m v)
1391 (module-search module-locally-bound? m v))
1393 ;;; {Is a symbol interned in a module?}
1395 ;;; Symbol S in Module M is interned if S occurs in
1396 ;;; of S in M has been set to some well-defined value.
1398 ;;; It is possible to intern a symbol in a module without providing
1399 ;;; an initial binding for the corresponding variable. This is done
1401 ;;; (module-add! module symbol (make-undefined-variable))
1403 ;;; In that case, the symbol is interned in the module, but not
1404 ;;; bound there. The unbound symbol shadows any binding for that
1405 ;;; symbol that might otherwise be inherited from a member of the uses list.
1408 (define (module-obarray-get-handle ob key)
1409 ((if (symbol? key) hashq-get-handle hash-get-handle) ob key))
1411 (define (module-obarray-ref ob key)
1412 ((if (symbol? key) hashq-ref hash-ref) ob key))
1414 (define (module-obarray-set! ob key val)
1415 ((if (symbol? key) hashq-set! hash-set!) ob key val))
1417 (define (module-obarray-remove! ob key)
1418 ((if (symbol? key) hashq-remove! hash-remove!) ob key))
1420 ;; module-symbol-locally-interned? module symbol
1422 ;; is a symbol interned (not neccessarily defined) locally in a given module
1423 ;; or its uses? Interned symbols shadow inherited bindings even if
1424 ;; they are not themselves bound to a defined value.
1426 (define (module-symbol-locally-interned? m v)
1427 (not (not (module-obarray-get-handle (module-obarray m) v))))
1429 ;; module-symbol-interned? module symbol
1431 ;; is a symbol interned (not neccessarily defined) anywhere in a given module
1432 ;; or its uses? Interned symbols shadow inherited bindings even if
1433 ;; they are not themselves bound to a defined value.
1435 (define (module-symbol-interned? m v)
1436 (module-search module-symbol-locally-interned? m v))
1439 ;;; {Mapping modules x symbols --> variables}
1442 ;; module-local-variable module symbol
1443 ;; return the local variable associated with a MODULE and SYMBOL.
1445 ;;; This function is very important. It is the only function that can
1446 ;;; return a variable from a module other than the mutators that store
1447 ;;; new variables in modules. Therefore, this function is the location
1448 ;;; of the "lazy binder" hack.
1450 ;;; If symbol is defined in MODULE, and if the definition binds symbol
1451 ;;; to a variable, return that variable object.
1453 ;;; If the symbols is not found at first, but the module has a lazy binder,
1454 ;;; then try the binder.
1456 ;;; If the symbol is not found at all, return #f.
1458 ;;; (This is now written in C, see `modules.c'.)
1461 ;;; {Mapping modules x symbols --> bindings}
1463 ;;; These are similar to the mapping to variables, except that the
1464 ;;; variable is dereferenced.
1467 ;; module-symbol-binding module symbol opt-value
1469 ;; return the binding of a variable specified by name within
1470 ;; a given module, signalling an error if the variable is unbound.
1471 ;; If the OPT-VALUE is passed, then instead of signalling an error,
1472 ;; return OPT-VALUE.
1474 (define (module-symbol-local-binding m v . opt-val)
1475 (let ((var (module-local-variable m v)))
1476 (if (and var (variable-bound? var))
1478 (if (not (null? opt-val))
1480 (error "Locally unbound variable." v)))))
1482 ;; module-symbol-binding module symbol opt-value
1484 ;; return the binding of a variable specified by name within
1485 ;; a given module, signalling an error if the variable is unbound.
1486 ;; If the OPT-VALUE is passed, then instead of signalling an error,
1487 ;; return OPT-VALUE.
1489 (define (module-symbol-binding m v . opt-val)
1490 (let ((var (module-variable m v)))
1491 (if (and var (variable-bound? var))
1493 (if (not (null? opt-val))
1495 (error "Unbound variable." v)))))
1500 ;;; {Adding Variables to Modules}
1503 ;; module-make-local-var! module symbol
1505 ;; ensure a variable for V in the local namespace of M.
1506 ;; If no variable was already there, then create a new and uninitialzied
1509 ;; This function is used in modules.c.
1511 (define (module-make-local-var! m v)
1512 (or (let ((b (module-obarray-ref (module-obarray m) v)))
1515 ;; Mark as modified since this function is called when
1516 ;; the standard eval closure defines a binding
1520 ;; Create a new local variable.
1521 (let ((local-var (make-undefined-variable)))
1522 (module-add! m v local-var)
1525 ;; module-ensure-local-variable! module symbol
1527 ;; Ensure that there is a local variable in MODULE for SYMBOL. If
1528 ;; there is no binding for SYMBOL, create a new uninitialized
1529 ;; variable. Return the local variable.
1531 (define (module-ensure-local-variable! module symbol)
1532 (or (module-local-variable module symbol)
1533 (let ((var (make-undefined-variable)))
1534 (module-add! module symbol var)
1537 ;; module-add! module symbol var
1539 ;; ensure a particular variable for V in the local namespace of M.
1541 (define (module-add! m v var)
1542 (if (not (variable? var))
1543 (error "Bad variable to module-add!" var))
1544 (module-obarray-set! (module-obarray m) v var)
1545 (module-modified m))
1549 ;; make sure that a symbol is undefined in the local namespace of M.
1551 (define (module-remove! m v)
1552 (module-obarray-remove! (module-obarray m) v)
1553 (module-modified m))
1555 (define (module-clear! m)
1556 (hash-clear! (module-obarray m))
1557 (module-modified m))
1559 ;; MODULE-FOR-EACH -- exported
1561 ;; Call PROC on each symbol in MODULE, with arguments of (SYMBOL VARIABLE).
1563 (define (module-for-each proc module)
1564 (hash-for-each proc (module-obarray module)))
1566 (define (module-map proc module)
1567 (hash-map->list proc (module-obarray module)))
1571 ;;; {Low Level Bootstrapping}
1576 ;; A root module uses the pre-modules-obarray as its obarray. This
1577 ;; special obarray accumulates all bindings that have been established
1578 ;; before the module system is fully booted.
1580 ;; (The obarray continues to be used by code that has been closed over
1581 ;; before the module system has been booted.)
1583 (define (make-root-module)
1584 (let ((m (make-module 0)))
1585 (set-module-obarray! m (%get-pre-modules-obarray))
1590 ;; The root interface is a module that uses the same obarray as the
1591 ;; root module. It does not allow new definitions, tho.
1593 (define (make-scm-module)
1594 (let ((m (make-module 0)))
1595 (set-module-obarray! m (%get-pre-modules-obarray))
1596 (set-module-eval-closure! m (standard-interface-eval-closure m))
1602 ;;; {Module-based Loading}
1605 (define (save-module-excursion thunk)
1606 (let ((inner-module (current-module))
1608 (dynamic-wind (lambda ()
1609 (set! outer-module (current-module))
1610 (set-current-module inner-module)
1611 (set! inner-module #f))
1614 (set! inner-module (current-module))
1615 (set-current-module outer-module)
1616 (set! outer-module #f)))))
1618 (define basic-load load)
1620 (define (load-module filename . reader)
1621 (save-module-excursion
1623 (let ((oldname (and (current-load-port)
1624 (port-filename (current-load-port)))))
1627 (> (string-length filename) 0)
1628 (not (char=? (string-ref filename 0) #\/))
1629 (not (string=? (dirname oldname) ".")))
1630 (string-append (dirname oldname) "/" filename)
1637 ;;; {MODULE-REF -- exported}
1640 ;; Returns the value of a variable called NAME in MODULE or any of its
1641 ;; used modules. If there is no such variable, then if the optional third
1642 ;; argument DEFAULT is present, it is returned; otherwise an error is signaled.
1644 (define (module-ref module name . rest)
1645 (let ((variable (module-variable module name)))
1646 (if (and variable (variable-bound? variable))
1647 (variable-ref variable)
1649 (error "No variable named" name 'in module)
1650 (car rest) ; default value
1653 ;; MODULE-SET! -- exported
1655 ;; Sets the variable called NAME in MODULE (or in a module that MODULE uses)
1656 ;; to VALUE; if there is no such variable, an error is signaled.
1658 (define (module-set! module name value)
1659 (let ((variable (module-variable module name)))
1661 (variable-set! variable value)
1662 (error "No variable named" name 'in module))))
1664 ;; MODULE-DEFINE! -- exported
1666 ;; Sets the variable called NAME in MODULE to VALUE; if there is no such
1667 ;; variable, it is added first.
1669 (define (module-define! module name value)
1670 (let ((variable (module-local-variable module name)))
1673 (variable-set! variable value)
1674 (module-modified module))
1675 (let ((variable (make-variable value)))
1676 (module-add! module name variable)))))
1678 ;; MODULE-DEFINED? -- exported
1680 ;; Return #t iff NAME is defined in MODULE (or in a module that MODULE
1683 (define (module-defined? module name)
1684 (let ((variable (module-variable module name)))
1685 (and variable (variable-bound? variable))))
1687 ;; MODULE-USE! module interface
1689 ;; Add INTERFACE to the list of interfaces used by MODULE.
1691 (define (module-use! module interface)
1692 (if (not (or (eq? module interface)
1693 (memq interface (module-uses module))))
1695 ;; Newly used modules must be appended rather than consed, so that
1696 ;; `module-variable' traverses the use list starting from the first
1698 (set-module-uses! module
1699 (append (filter (lambda (m)
1701 (equal? (module-name m)
1702 (module-name interface))))
1703 (module-uses module))
1706 (module-modified module))))
1708 ;; MODULE-USE-INTERFACES! module interfaces
1710 ;; Same as MODULE-USE! but add multiple interfaces and check for duplicates
1712 (define (module-use-interfaces! module interfaces)
1713 (set-module-uses! module
1714 (append (module-uses module) interfaces))
1715 (module-modified module))
1719 ;;; {Recursive Namespaces}
1721 ;;; A hierarchical namespace emerges if we consider some module to be
1722 ;;; root, and variables bound to modules as nested namespaces.
1724 ;;; The routines in this file manage variable names in hierarchical namespace.
1725 ;;; Each variable name is a list of elements, looked up in successively nested
1728 ;;; (nested-ref some-root-module '(foo bar baz))
1729 ;;; => <value of a variable named baz in the module bound to bar in
1730 ;;; the module bound to foo in some-root-module>
1735 ;;; ;; a-root is a module
1736 ;;; ;; name is a list of symbols
1738 ;;; nested-ref a-root name
1739 ;;; nested-set! a-root name val
1740 ;;; nested-define! a-root name val
1741 ;;; nested-remove! a-root name
1744 ;;; (current-module) is a natural choice for a-root so for convenience there are
1747 ;;; local-ref name == nested-ref (current-module) name
1748 ;;; local-set! name val == nested-set! (current-module) name val
1749 ;;; local-define! name val == nested-define! (current-module) name val
1750 ;;; local-remove! name == nested-remove! (current-module) name
1754 (define (nested-ref root names)
1755 (let loop ((cur root)
1759 ((not (module? cur)) #f)
1760 (else (loop (module-ref cur (car elts) #f) (cdr elts))))))
1762 (define (nested-set! root names val)
1763 (let loop ((cur root)
1765 (if (null? (cdr elts))
1766 (module-set! cur (car elts) val)
1767 (loop (module-ref cur (car elts)) (cdr elts)))))
1769 (define (nested-define! root names val)
1770 (let loop ((cur root)
1772 (if (null? (cdr elts))
1773 (module-define! cur (car elts) val)
1774 (loop (module-ref cur (car elts)) (cdr elts)))))
1776 (define (nested-remove! root names)
1777 (let loop ((cur root)
1779 (if (null? (cdr elts))
1780 (module-remove! cur (car elts))
1781 (loop (module-ref cur (car elts)) (cdr elts)))))
1783 (define (local-ref names) (nested-ref (current-module) names))
1784 (define (local-set! names val) (nested-set! (current-module) names val))
1785 (define (local-define names val) (nested-define! (current-module) names val))
1786 (define (local-remove names) (nested-remove! (current-module) names))
1791 ;;; {The (%app) module}
1793 ;;; The root of conventionally named objects not directly in the top level.
1796 ;;; (%app modules guile)
1798 ;;; The directory of all modules and the standard root module.
1801 ;; module-public-interface is defined in C.
1802 (define (set-module-public-interface! m i)
1803 (module-define! m '%module-public-interface i))
1804 (define (set-system-module! m s)
1805 (set-procedure-property! (module-eval-closure m) 'system-module s))
1806 (define the-root-module (make-root-module))
1807 (define the-scm-module (make-scm-module))
1808 (set-module-public-interface! the-root-module the-scm-module)
1809 (set-module-name! the-root-module '(guile))
1810 (set-module-name! the-scm-module '(guile))
1811 (set-module-kind! the-scm-module 'interface)
1812 (set-system-module! the-root-module #t)
1813 (set-system-module! the-scm-module #t)
1815 ;; NOTE: This binding is used in libguile/modules.c.
1817 (define (make-modules-in module name)
1821 (let* ((var (module-local-variable module (car name)))
1822 (val (and var (variable-bound? var) (variable-ref var))))
1825 (let ((m (make-module 31)))
1826 (set-module-kind! m 'directory)
1827 (set-module-name! m (append (or (module-name module) '())
1829 (module-define! module (car name) m)
1833 (define (beautify-user-module! module)
1834 (let ((interface (module-public-interface module)))
1835 (if (or (not interface)
1836 (eq? interface module))
1837 (let ((interface (make-module 31)))
1838 (set-module-name! interface (module-name module))
1839 (set-module-kind! interface 'interface)
1840 (set-module-public-interface! module interface))))
1841 (if (and (not (memq the-scm-module (module-uses module)))
1842 (not (eq? module the-root-module)))
1843 ;; Import the default set of bindings (from the SCM module) in MODULE.
1844 (module-use! module the-scm-module)))
1846 ;; NOTE: This binding is used in libguile/modules.c.
1848 (define resolve-module
1849 (let ((the-root-module the-root-module))
1850 (lambda (name . maybe-autoload)
1851 (if (equal? name '(guile))
1853 (let ((full-name (append '(%app modules) name)))
1854 (let ((already (nested-ref the-root-module full-name))
1855 (autoload (or (null? maybe-autoload) (car maybe-autoload))))
1857 ((and already (module? already)
1858 (or (not autoload) (module-public-interface already)))
1859 ;; A hit, a palpable hit.
1862 ;; Try to autoload the module, and recurse.
1863 (try-load-module name)
1864 (resolve-module name #f))
1866 ;; A module is not bound (but maybe something else is),
1867 ;; we're not autoloading -- here's the weird semantics,
1868 ;; we create an empty module.
1869 (make-modules-in the-root-module full-name)))))))))
1871 ;; Cheat. These bindings are needed by modules.c, but we don't want
1872 ;; to move their real definition here because that would be unnatural.
1874 (define try-module-autoload #f)
1875 (define process-define-module #f)
1876 (define process-use-modules #f)
1877 (define module-export! #f)
1878 (define default-duplicate-binding-procedures #f)
1880 (define %app (make-module 31))
1881 (define app %app) ;; for backwards compatability
1883 (local-define '(%app modules) (make-module 31))
1884 (local-define '(%app modules guile) the-root-module)
1886 ;; This boots the module system. All bindings needed by modules.c
1887 ;; must have been defined by now.
1889 (set-current-module the-root-module)
1890 ;; definition deferred for syncase's benefit
1891 (define module-name (record-accessor module-type 'name))
1893 ;; (define-special-value '(%app modules new-ws) (lambda () (make-scm-module)))
1895 (define (try-load-module name)
1896 (try-module-autoload name))
1898 (define (purify-module! module)
1899 "Removes bindings in MODULE which are inherited from the (guile) module."
1900 (let ((use-list (module-uses module)))
1901 (if (and (pair? use-list)
1902 (eq? (car (last-pair use-list)) the-scm-module))
1903 (set-module-uses! module (reverse (cdr (reverse use-list)))))))
1905 ;; Return a module that is an interface to the module designated by
1908 ;; `resolve-interface' takes four keyword arguments:
1910 ;; #:select SELECTION
1912 ;; SELECTION is a list of binding-specs to be imported; A binding-spec
1913 ;; is either a symbol or a pair of symbols (ORIG . SEEN), where ORIG
1914 ;; is the name in the used module and SEEN is the name in the using
1915 ;; module. Note that SEEN is also passed through RENAMER, below. The
1916 ;; default is to select all bindings. If you specify no selection but
1917 ;; a renamer, only the bindings that already exist in the used module
1918 ;; are made available in the interface. Bindings that are added later
1919 ;; are not picked up.
1923 ;; BINDINGS is a list of bindings which should not be imported.
1927 ;; PREFIX is a symbol that will be appended to each exported name.
1928 ;; The default is to not perform any renaming.
1930 ;; #:renamer RENAMER
1932 ;; RENAMER is a procedure that takes a symbol and returns its new
1933 ;; name. The default is not perform any renaming.
1935 ;; Signal "no code for module" error if module name is not resolvable
1936 ;; or its public interface is not available. Signal "no binding"
1937 ;; error if selected binding does not exist in the used module.
1939 (define (resolve-interface name . args)
1941 (define (get-keyword-arg args kw def)
1942 (cond ((memq kw args)
1944 (if (null? (cdr kw-arg))
1945 (error "keyword without value: " kw))
1950 (let* ((select (get-keyword-arg args #:select #f))
1951 (hide (get-keyword-arg args #:hide '()))
1952 (renamer (or (get-keyword-arg args #:renamer #f)
1953 (let ((prefix (get-keyword-arg args #:prefix #f)))
1954 (and prefix (symbol-prefix-proc prefix)))
1956 (module (resolve-module name))
1957 (public-i (and module (module-public-interface module))))
1958 (and (or (not module) (not public-i))
1959 (error "no code for module" name))
1960 (if (and (not select) (null? hide) (eq? renamer identity))
1962 (let ((selection (or select (module-map (lambda (sym var) sym)
1964 (custom-i (make-module 31)))
1965 (set-module-kind! custom-i 'custom-interface)
1966 (set-module-name! custom-i name)
1967 ;; XXX - should use a lazy binder so that changes to the
1968 ;; used module are picked up automatically.
1969 (for-each (lambda (bspec)
1970 (let* ((direct? (symbol? bspec))
1971 (orig (if direct? bspec (car bspec)))
1972 (seen (if direct? bspec (cdr bspec)))
1973 (var (or (module-local-variable public-i orig)
1974 (module-local-variable module orig)
1976 ;; fixme: format manually for now
1978 #f "no binding `~A' in module ~A"
1980 (if (memq orig hide)
1981 (set! hide (delq! orig hide))
1982 (module-add! custom-i
1986 ;; Check that we are not hiding bindings which don't exist
1987 (for-each (lambda (binding)
1988 (if (not (module-local-variable public-i binding))
1991 #f "no binding `~A' to hide in module ~A"
1996 (define (symbol-prefix-proc prefix)
1998 (symbol-append prefix symbol)))
2000 ;; This function is called from "modules.c". If you change it, be
2001 ;; sure to update "modules.c" as well.
2003 (define (process-define-module args)
2004 (let* ((module-id (car args))
2005 (module (resolve-module module-id #f))
2007 (unrecognized (lambda (arg)
2008 (error "unrecognized define-module argument" arg))))
2009 (beautify-user-module! module)
2010 (let loop ((kws kws)
2011 (reversed-interfaces '())
2018 (call-with-deferred-observers
2020 (module-use-interfaces! module (reverse reversed-interfaces))
2021 (module-export! module exports)
2022 (module-replace! module replacements)
2023 (module-re-export! module re-exports)
2024 (if (not (null? autoloads))
2025 (apply module-autoload! module autoloads))))
2027 ((#:use-module #:use-syntax)
2028 (or (pair? (cdr kws))
2031 ((equal? (caadr kws) '(ice-9 syncase))
2032 (issue-deprecation-warning
2033 "(ice-9 syncase) is deprecated. Support for syntax-case is now in Guile core.")
2041 (let* ((interface-args (cadr kws))
2042 (interface (apply resolve-interface interface-args)))
2043 (and (eq? (car kws) #:use-syntax)
2044 (or (symbol? (caar interface-args))
2045 (error "invalid module name for use-syntax"
2046 (car interface-args)))
2047 (set-module-transformer!
2049 (module-ref interface
2050 (car (last-pair (car interface-args)))
2053 (cons interface reversed-interfaces)
2059 (or (and (pair? (cdr kws)) (pair? (cddr kws)))
2066 (let ((name (cadr kws))
2067 (bindings (caddr kws)))
2068 (cons* name bindings autoloads))))
2070 (set-system-module! module #t)
2071 (loop (cdr kws) reversed-interfaces exports re-exports
2072 replacements autoloads))
2074 (purify-module! module)
2075 (loop (cdr kws) reversed-interfaces exports re-exports
2076 replacements autoloads))
2078 (if (not (pair? (cdr kws)))
2080 (set-module-duplicates-handlers!
2082 (lookup-duplicates-handlers (cadr kws)))
2083 (loop (cddr kws) reversed-interfaces exports re-exports
2084 replacements autoloads))
2085 ((#:export #:export-syntax)
2086 (or (pair? (cdr kws))
2090 (append (cadr kws) exports)
2094 ((#:re-export #:re-export-syntax)
2095 (or (pair? (cdr kws))
2100 (append (cadr kws) re-exports)
2103 ((#:replace #:replace-syntax)
2104 (or (pair? (cdr kws))
2110 (append (cadr kws) replacements)
2113 (unrecognized kws)))))
2114 (run-hook module-defined-hook module)
2117 ;; `module-defined-hook' is a hook that is run whenever a new module
2118 ;; is defined. Its members are called with one argument, the new
2120 (define module-defined-hook (make-hook 1))
2127 (define (make-autoload-interface module name bindings)
2128 (let ((b (lambda (a sym definep)
2129 (and (memq sym bindings)
2130 (let ((i (module-public-interface (resolve-module name))))
2132 (error "missing interface for module" name))
2133 (let ((autoload (memq a (module-uses module))))
2134 ;; Replace autoload-interface with actual interface if
2135 ;; that has not happened yet.
2136 (if (pair? autoload)
2137 (set-car! autoload i)))
2138 (module-local-variable i sym))))))
2139 (module-constructor (make-hash-table 0) '() b #f #f name 'autoload #f
2140 (make-hash-table 0) '() (make-weak-value-hash-table 31))))
2142 (define (module-autoload! module . args)
2143 "Have @var{module} automatically load the module named @var{name} when one
2144 of the symbols listed in @var{bindings} is looked up. @var{args} should be a
2145 list of module-name/binding-list pairs, e.g., as in @code{(module-autoload!
2146 module '(ice-9 q) '(make-q q-length))}."
2147 (let loop ((args args))
2151 (error "invalid name+binding autoload list" args))
2153 (let ((name (car args))
2154 (bindings (cadr args)))
2155 (module-use! module (make-autoload-interface module
2157 (loop (cddr args)))))))
2162 ;;; {Autoloading modules}
2165 (define autoloads-in-progress '())
2167 ;; This function is called from "modules.c". If you change it, be
2168 ;; sure to update "modules.c" as well.
2170 (define (try-module-autoload module-name)
2171 (let* ((reverse-name (reverse module-name))
2172 (name (symbol->string (car reverse-name)))
2173 (dir-hint-module-name (reverse (cdr reverse-name)))
2174 (dir-hint (apply string-append
2176 (string-append (symbol->string elt) "/"))
2177 dir-hint-module-name))))
2178 (resolve-module dir-hint-module-name #f)
2179 (and (not (autoload-done-or-in-progress? dir-hint name))
2181 (define (load-file proc file)
2182 (save-module-excursion (lambda () (proc file)))
2185 (lambda () (autoload-in-progress! dir-hint name))
2187 (let ((file (in-vicinity dir-hint name)))
2188 (let ((compiled (and load-compiled
2190 (string-append file ".go"))))
2191 (source (%search-load-path file)))
2194 (< (stat:mtime (stat compiled))
2195 (stat:mtime (stat source)))))
2197 (warn "source file" source "newer than" compiled))
2198 (with-fluid* current-reader #f
2199 (lambda () (load-file primitive-load source))))
2201 (load-file load-compiled compiled))))))
2202 (lambda () (set-autoloaded! dir-hint name didit)))
2207 ;;; {Dynamic linking of modules}
2210 (define autoloads-done '((guile . guile)))
2212 (define (autoload-done-or-in-progress? p m)
2213 (let ((n (cons p m)))
2214 (->bool (or (member n autoloads-done)
2215 (member n autoloads-in-progress)))))
2217 (define (autoload-done! p m)
2218 (let ((n (cons p m)))
2219 (set! autoloads-in-progress
2220 (delete! n autoloads-in-progress))
2221 (or (member n autoloads-done)
2222 (set! autoloads-done (cons n autoloads-done)))))
2224 (define (autoload-in-progress! p m)
2225 (let ((n (cons p m)))
2226 (set! autoloads-done
2227 (delete! n autoloads-done))
2228 (set! autoloads-in-progress (cons n autoloads-in-progress))))
2230 (define (set-autoloaded! p m done?)
2232 (autoload-done! p m)
2233 (let ((n (cons p m)))
2234 (set! autoloads-done (delete! n autoloads-done))
2235 (set! autoloads-in-progress (delete! n autoloads-in-progress)))))
2239 ;;; {Run-time options}
2242 (defmacro define-option-interface (option-group)
2243 (let* ((option-name car)
2245 (option-documentation caddr)
2247 ;; Below follow the macros defining the run-time option interfaces.
2249 (make-options (lambda (interface)
2251 (cond ((null? args) (,interface))
2253 (,interface (car args)) (,interface))
2256 (display (option-name option))
2257 (if (< (string-length
2258 (symbol->string (option-name option)))
2262 (display (option-value option))
2264 (display (option-documentation option))
2266 (,interface #t)))))))
2268 (make-enable (lambda (interface)
2270 (,interface (append flags (,interface)))
2273 (make-disable (lambda (interface)
2275 (let ((options (,interface)))
2276 (for-each (lambda (flag)
2277 (set! options (delq! flag options)))
2279 (,interface options)
2281 (let* ((interface (car option-group))
2282 (options/enable/disable (cadr option-group)))
2284 (define ,(car options/enable/disable)
2285 ,(make-options interface))
2286 (define ,(cadr options/enable/disable)
2287 ,(make-enable interface))
2288 (define ,(caddr options/enable/disable)
2289 ,(make-disable interface))
2290 (defmacro ,(caaddr option-group) (opt val)
2291 `(,',(car options/enable/disable)
2292 (append (,',(car options/enable/disable))
2293 (list ',opt ,val))))))))
2295 (define-option-interface
2296 (eval-options-interface
2297 (eval-options eval-enable eval-disable)
2300 (define-option-interface
2301 (debug-options-interface
2302 (debug-options debug-enable debug-disable)
2305 (define-option-interface
2306 (evaluator-traps-interface
2307 (traps trap-enable trap-disable)
2310 (define-option-interface
2311 (read-options-interface
2312 (read-options read-enable read-disable)
2315 (define-option-interface
2316 (print-options-interface
2317 (print-options print-enable print-disable)
2325 (define (repl read evaler print)
2326 (let loop ((source (read (current-input-port))))
2327 (print (evaler source))
2328 (loop (read (current-input-port)))))
2330 ;; A provisional repl that acts like the SCM repl:
2332 (define scm-repl-silent #f)
2333 (define (assert-repl-silence v) (set! scm-repl-silent v))
2335 (define *unspecified* (if #f #f))
2336 (define (unspecified? v) (eq? v *unspecified*))
2338 (define scm-repl-print-unspecified #f)
2339 (define (assert-repl-print-unspecified v) (set! scm-repl-print-unspecified v))
2341 (define scm-repl-verbose #f)
2342 (define (assert-repl-verbosity v) (set! scm-repl-verbose v))
2344 (define scm-repl-prompt "guile> ")
2346 (define (set-repl-prompt! v) (set! scm-repl-prompt v))
2348 (define (default-pre-unwind-handler key . args)
2349 (save-stack pre-unwind-handler-dispatch)
2350 (apply throw key args))
2352 (define (pre-unwind-handler-dispatch key . args)
2353 (apply default-pre-unwind-handler key args))
2355 (define abort-hook (make-hook))
2357 ;; these definitions are used if running a script.
2358 ;; otherwise redefined in error-catching-loop.
2359 (define (set-batch-mode?! arg) #t)
2360 (define (batch-mode?) #t)
2362 (define (error-catching-loop thunk)
2365 (define (loop first)
2370 (call-with-unblocked-asyncs
2376 ;; This line is needed because mark
2377 ;; doesn't do closures quite right.
2378 ;; Unreferenced locals should be
2381 (let loop ((v (thunk)))
2385 (lambda (key . args)
2392 (apply throw 'switch-repl args))
2395 ;; This is one of the closures that require
2396 ;; (set! first #f) above
2399 (run-hook abort-hook)
2400 (force-output (current-output-port))
2401 (display "ABORT: " (current-error-port))
2402 (write args (current-error-port))
2403 (newline (current-error-port))
2407 (not has-shown-debugger-hint?)
2408 (not (memq 'backtrace
2409 (debug-options-interface)))
2410 (stack? (fluid-ref the-last-stack)))
2412 (newline (current-error-port))
2414 "Type \"(backtrace)\" to get more information or \"(debug)\" to enter the debugger.\n"
2415 (current-error-port))
2416 (set! has-shown-debugger-hint? #t)))
2417 (force-output (current-error-port)))
2419 (primitive-exit 1)))
2420 (set! stack-saved? #f)))
2423 ;; This is the other cons-leak closure...
2425 (cond ((= (length args) 4)
2426 (apply handle-system-error key args))
2428 (apply bad-throw key args)))))))
2430 ;; Note that having just `pre-unwind-handler-dispatch'
2431 ;; here is connected with the mechanism that
2432 ;; produces a nice backtrace upon error. If, for
2433 ;; example, this is replaced with (lambda args
2434 ;; (apply pre-unwind-handler-dispatch args)), the stack
2435 ;; cutting (in save-stack) goes wrong and ends up
2436 ;; saving no stack at all, so there is no
2438 pre-unwind-handler-dispatch)))
2440 (if next (loop next) status)))
2441 (set! set-batch-mode?! (lambda (arg)
2443 (set! interactive #f)
2446 (error "sorry, not implemented")))))
2447 (set! batch-mode? (lambda () (not interactive)))
2448 (call-with-blocked-asyncs
2449 (lambda () (loop (lambda () #t))))))
2451 ;;(define the-last-stack (make-fluid)) Defined by scm_init_backtrace ()
2452 (define before-signal-stack (make-fluid))
2453 (define stack-saved? #f)
2455 (define (save-stack . narrowing)
2457 (cond ((not (memq 'debug (debug-options-interface)))
2458 (fluid-set! the-last-stack #f)
2459 (set! stack-saved? #t))
2465 (apply make-stack #t save-stack primitive-eval #t 0 narrowing))
2467 (apply make-stack #t save-stack 0 #t 0 narrowing))
2469 (apply make-stack #t save-stack tk-stack-mark #t 0 narrowing))
2471 (apply make-stack #t save-stack 0 1 narrowing))
2473 (let ((id (stack-id #t)))
2474 (and (procedure? id)
2475 (apply make-stack #t save-stack id #t 0 narrowing))))))
2476 (set! stack-saved? #t)))))
2478 (define before-error-hook (make-hook))
2479 (define after-error-hook (make-hook))
2480 (define before-backtrace-hook (make-hook))
2481 (define after-backtrace-hook (make-hook))
2483 (define has-shown-debugger-hint? #f)
2485 (define (handle-system-error key . args)
2486 (let ((cep (current-error-port)))
2487 (cond ((not (stack? (fluid-ref the-last-stack))))
2488 ((memq 'backtrace (debug-options-interface))
2489 (let ((highlights (if (or (eq? key 'wrong-type-arg)
2490 (eq? key 'out-of-range))
2493 (run-hook before-backtrace-hook)
2495 (display "Backtrace:\n")
2496 (display-backtrace (fluid-ref the-last-stack) cep
2499 (run-hook after-backtrace-hook))))
2500 (run-hook before-error-hook)
2501 (apply display-error (fluid-ref the-last-stack) cep args)
2502 (run-hook after-error-hook)
2504 (throw 'abort key)))
2506 (define (quit . args)
2507 (apply throw 'quit args))
2511 ;;(define has-shown-backtrace-hint? #f) Defined by scm_init_backtrace ()
2513 ;; Replaced by C code:
2514 ;;(define (backtrace)
2515 ;; (if (fluid-ref the-last-stack)
2518 ;; (display-backtrace (fluid-ref the-last-stack) (current-output-port))
2520 ;; (if (and (not has-shown-backtrace-hint?)
2521 ;; (not (memq 'backtrace (debug-options-interface))))
2524 ;;"Type \"(debug-enable 'backtrace)\" if you would like a backtrace
2525 ;;automatically if an error occurs in the future.\n")
2526 ;; (set! has-shown-backtrace-hint? #t))))
2527 ;; (display "No backtrace available.\n")))
2529 (define (error-catching-repl r e p)
2530 (error-catching-loop
2532 (call-with-values (lambda () (e (r)))
2533 (lambda the-values (for-each p the-values))))))
2535 (define (gc-run-time)
2536 (cdr (assq 'gc-time-taken (gc-stats))))
2538 (define before-read-hook (make-hook))
2539 (define after-read-hook (make-hook))
2540 (define before-eval-hook (make-hook 1))
2541 (define after-eval-hook (make-hook 1))
2542 (define before-print-hook (make-hook 1))
2543 (define after-print-hook (make-hook 1))
2545 ;;; The default repl-reader function. We may override this if we've
2546 ;;; the readline library.
2549 (display (if (string? prompt) prompt (prompt)))
2551 (run-hook before-read-hook)
2552 ((or (fluid-ref current-reader) read) (current-input-port))))
2554 (define (scm-style-repl)
2559 (repl-report-start-timing (lambda ()
2560 (set! start-gc-rt (gc-run-time))
2561 (set! start-rt (get-internal-run-time))))
2562 (repl-report (lambda ()
2564 (display (inexact->exact
2565 (* 1000 (/ (- (get-internal-run-time) start-rt)
2566 internal-time-units-per-second))))
2568 (display (inexact->exact
2569 (* 1000 (/ (- (gc-run-time) start-gc-rt)
2570 internal-time-units-per-second))))
2571 (display " msec in gc)\n")))
2573 (consume-trailing-whitespace
2575 (let ((ch (peek-char)))
2578 ((or (char=? ch #\space) (char=? ch #\tab))
2580 (consume-trailing-whitespace))
2581 ((char=? ch #\newline)
2585 (let ((prompt (cond ((string? scm-repl-prompt)
2587 ((thunk? scm-repl-prompt)
2589 (scm-repl-prompt "> ")
2591 (repl-reader prompt))))
2593 ;; As described in R4RS, the READ procedure updates the
2594 ;; port to point to the first character past the end of
2595 ;; the external representation of the object. This
2596 ;; means that it doesn't consume the newline typically
2597 ;; found after an expression. This means that, when
2598 ;; debugging Guile with GDB, GDB gets the newline, which
2599 ;; it often interprets as a "continue" command, making
2600 ;; breakpoints kind of useless. So, consume any
2601 ;; trailing newline here, as well as any whitespace
2603 ;; But not if EOF, for control-D.
2604 (if (not (eof-object? val))
2605 (consume-trailing-whitespace))
2606 (run-hook after-read-hook)
2607 (if (eof-object? val)
2609 (repl-report-start-timing)
2610 (if scm-repl-verbose
2613 (display ";;; EOF -- quitting")
2618 (-eval (lambda (sourc)
2619 (repl-report-start-timing)
2620 (run-hook before-eval-hook sourc)
2621 (let ((val (start-stack 'repl-stack
2622 ;; If you change this procedure
2623 ;; (primitive-eval), please also
2624 ;; modify the repl-stack case in
2625 ;; save-stack so that stack cutting
2626 ;; continues to work.
2627 (primitive-eval sourc))))
2628 (run-hook after-eval-hook sourc)
2632 (-print (let ((maybe-print (lambda (result)
2633 (if (or scm-repl-print-unspecified
2634 (not (unspecified? result)))
2639 (if (not scm-repl-silent)
2641 (run-hook before-print-hook result)
2642 (maybe-print result)
2643 (run-hook after-print-hook result)
2644 (if scm-repl-verbose
2648 (-quit (lambda (args)
2649 (if scm-repl-verbose
2651 (display ";;; QUIT executed, repl exitting")
2657 (if scm-repl-verbose
2659 (display ";;; ABORT executed.")
2662 (repl -read -eval -print))))
2664 (let ((status (error-catching-repl -read
2672 ;;; {IOTA functions: generating lists of numbers}
2676 (let loop ((count (1- n)) (result '()))
2677 (if (< count 0) result
2678 (loop (1- count) (cons count result)))))
2684 ;;; Similar to `begin' but returns a list of the results of all constituent
2685 ;;; forms instead of the result of the last form.
2686 ;;; (The definition relies on the current left-to-right
2687 ;;; order of evaluation of operands in applications.)
2690 (defmacro collect forms
2698 ;; with-fluids is a convenience wrapper for the builtin procedure
2699 ;; `with-fluids*'. The syntax is just like `let':
2701 ;; (with-fluids ((fluid val)
2705 (defmacro with-fluids (bindings . body)
2706 (let ((fluids (map car bindings))
2707 (values (map cadr bindings)))
2708 (if (and (= (length fluids) 1) (= (length values) 1))
2709 `(with-fluid* ,(car fluids) ,(car values) (lambda () ,@body))
2710 `(with-fluids* (list ,@fluids) (list ,@values)
2711 (lambda () ,@body)))))
2715 ;;; with `continue' and `break'.
2718 ;; The inner `do' loop avoids re-establishing a catch every iteration,
2719 ;; that's only necessary if continue is actually used. A new key is
2720 ;; generated every time, so break and continue apply to their originating
2721 ;; `while' even when recursing.
2723 ;; FIXME: This macro is unintentionally unhygienic with respect to let,
2724 ;; make-symbol, do, throw, catch, lambda, and not.
2726 (define-macro (while cond . body)
2727 (let ((keyvar (make-symbol "while-keyvar")))
2728 `(let ((,keyvar (make-symbol "while-key")))
2732 (let ((break (lambda () (throw ,keyvar #t)))
2733 (continue (lambda () (throw ,keyvar #f))))
2744 ;;; {Module System Macros}
2747 ;; Return a list of expressions that evaluate to the appropriate
2748 ;; arguments for resolve-interface according to SPEC.
2752 (if (memq 'prefix (read-options))
2753 (error "boot-9 must be compiled with #:kw, not :kw")))
2755 (define (compile-interface-spec spec)
2756 (define (make-keyarg sym key quote?)
2757 (cond ((or (memq sym spec)
2761 (list key (list 'quote (cadr rest)))
2762 (list key (cadr rest)))))
2765 (define (map-apply func list)
2766 (map (lambda (args) (apply func args)) list))
2769 '((:select #:select #t)
2771 (:prefix #:prefix #t)
2772 (:renamer #:renamer #f)))
2773 (if (not (pair? (car spec)))
2776 ,@(apply append (map-apply make-keyarg keys)))))
2778 (define (keyword-like-symbol->keyword sym)
2779 (symbol->keyword (string->symbol (substring (symbol->string sym) 1))))
2781 (define (compile-define-module-args args)
2782 ;; Just quote everything except #:use-module and #:use-syntax. We
2783 ;; need to know about all arguments regardless since we want to turn
2784 ;; symbols that look like keywords into real keywords, and the
2785 ;; keyword args in a define-module form are not regular
2786 ;; (i.e. no-backtrace doesn't take a value).
2787 (let loop ((compiled-args `((quote ,(car args))))
2790 (reverse! compiled-args))
2791 ;; symbol in keyword position
2792 ((symbol? (car args))
2794 (cons (keyword-like-symbol->keyword (car args)) (cdr args))))
2795 ((memq (car args) '(#:no-backtrace #:pure))
2796 (loop (cons (car args) compiled-args)
2799 (error "keyword without value:" (car args)))
2800 ((memq (car args) '(#:use-module #:use-syntax))
2801 (loop (cons* `(list ,@(compile-interface-spec (cadr args)))
2805 ((eq? (car args) #:autoload)
2806 (loop (cons* `(quote ,(caddr args))
2807 `(quote ,(cadr args))
2812 (loop (cons* `(quote ,(cadr args))
2817 (defmacro define-module args
2820 (let ((m (process-define-module
2821 (list ,@(compile-define-module-args args)))))
2822 (set-current-module m)
2825 ;; The guts of the use-modules macro. Add the interfaces of the named
2826 ;; modules to the use-list of the current module, in order.
2828 ;; This function is called by "modules.c". If you change it, be sure
2829 ;; to change scm_c_use_module as well.
2831 (define (process-use-modules module-interface-args)
2832 (let ((interfaces (map (lambda (mif-args)
2833 (or (apply resolve-interface mif-args)
2834 (error "no such module" mif-args)))
2835 module-interface-args)))
2836 (call-with-deferred-observers
2838 (module-use-interfaces! (current-module) interfaces)))))
2840 (defmacro use-modules modules
2843 (process-use-modules
2844 (list ,@(map (lambda (m)
2845 `(list ,@(compile-interface-spec m)))
2849 (defmacro use-syntax (spec)
2852 (issue-deprecation-warning
2853 "`use-syntax' is deprecated. Please contact guile-devel for more info.")
2854 (process-use-modules (list (list ,@(compile-interface-spec spec))))
2857 ;; Dirk:FIXME:: This incorrect (according to R5RS) syntax needs to be changed
2858 ;; as soon as guile supports hygienic macros.
2859 (define-syntax define-private
2864 (define-syntax define-public
2866 ((_ (name . args) . body)
2867 (define-public name (lambda args . body)))
2873 (define-syntax defmacro-public
2875 ((_ name args . body)
2877 (defmacro name args . body)
2878 (export-syntax name)))))
2880 ;; Export a local variable
2882 ;; This function is called from "modules.c". If you change it, be
2883 ;; sure to update "modules.c" as well.
2885 (define (module-export! m names)
2886 (let ((public-i (module-public-interface m)))
2887 (for-each (lambda (name)
2888 (let ((var (module-ensure-local-variable! m name)))
2889 (module-add! public-i name var)))
2892 (define (module-replace! m names)
2893 (let ((public-i (module-public-interface m)))
2894 (for-each (lambda (name)
2895 (let ((var (module-ensure-local-variable! m name)))
2896 (set-object-property! var 'replace #t)
2897 (module-add! public-i name var)))
2900 ;; Re-export a imported variable
2902 (define (module-re-export! m names)
2903 (let ((public-i (module-public-interface m)))
2904 (for-each (lambda (name)
2905 (let ((var (module-variable m name)))
2907 (error "Undefined variable:" name))
2908 ((eq? var (module-local-variable m name))
2909 (error "re-exporting local variable:" name))
2911 (module-add! public-i name var)))))
2914 (defmacro export names
2915 `(call-with-deferred-observers
2917 (module-export! (current-module) ',names))))
2919 (defmacro re-export names
2920 `(call-with-deferred-observers
2922 (module-re-export! (current-module) ',names))))
2924 (defmacro export-syntax names
2927 (defmacro re-export-syntax names
2928 `(re-export ,@names))
2930 (define load load-module)
2934 ;;; {Compiler interface}
2936 ;;; The full compiler interface can be found in (system). Here we put a
2937 ;;; few useful procedures into the global namespace.
2939 (module-autoload! the-scm-module
2940 '(system base compile)
2942 compile-time-environment))
2950 (define make-mutable-parameter
2951 (let ((make (lambda (fluid converter)
2955 (fluid-set! fluid (converter (car args))))))))
2956 (lambda (init . converter)
2957 (let ((fluid (make-fluid))
2958 (converter (if (null? converter)
2961 (fluid-set! fluid (converter init))
2962 (make fluid converter)))))
2966 ;;; {Handling of duplicate imported bindings}
2969 ;; Duplicate handlers take the following arguments:
2971 ;; module importing module
2972 ;; name conflicting name
2973 ;; int1 old interface where name occurs
2974 ;; val1 value of binding in old interface
2975 ;; int2 new interface where name occurs
2976 ;; val2 value of binding in new interface
2977 ;; var previous resolution or #f
2978 ;; val value of previous resolution
2980 ;; A duplicate handler can take three alternative actions:
2982 ;; 1. return #f => leave responsibility to next handler
2983 ;; 2. exit with an error
2984 ;; 3. return a variable resolving the conflict
2987 (define duplicate-handlers
2988 (let ((m (make-module 7)))
2990 (define (check module name int1 val1 int2 val2 var val)
2991 (scm-error 'misc-error
2993 "~A: `~A' imported from both ~A and ~A"
2994 (list (module-name module)
3000 (define (warn module name int1 val1 int2 val2 var val)
3001 (format (current-error-port)
3002 "WARNING: ~A: `~A' imported from both ~A and ~A\n"
3003 (module-name module)
3009 (define (replace module name int1 val1 int2 val2 var val)
3010 (let ((old (or (and var (object-property var 'replace) var)
3011 (module-variable int1 name)))
3012 (new (module-variable int2 name)))
3013 (if (object-property old 'replace)
3014 (and (or (eq? old new)
3015 (not (object-property new 'replace)))
3017 (and (object-property new 'replace)
3020 (define (warn-override-core module name int1 val1 int2 val2 var val)
3021 (and (eq? int1 the-scm-module)
3023 (format (current-error-port)
3024 "WARNING: ~A: imported module ~A overrides core binding `~A'\n"
3025 (module-name module)
3028 (module-local-variable int2 name))))
3030 (define (first module name int1 val1 int2 val2 var val)
3031 (or var (module-local-variable int1 name)))
3033 (define (last module name int1 val1 int2 val2 var val)
3034 (module-local-variable int2 name))
3036 (define (noop module name int1 val1 int2 val2 var val)
3039 (set-module-name! m 'duplicate-handlers)
3040 (set-module-kind! m 'interface)
3041 (module-define! m 'check check)
3042 (module-define! m 'warn warn)
3043 (module-define! m 'replace replace)
3044 (module-define! m 'warn-override-core warn-override-core)
3045 (module-define! m 'first first)
3046 (module-define! m 'last last)
3047 (module-define! m 'merge-generics noop)
3048 (module-define! m 'merge-accessors noop)
3051 (define (lookup-duplicates-handlers handler-names)
3053 (map (lambda (handler-name)
3054 (or (module-symbol-local-binding
3055 duplicate-handlers handler-name #f)
3056 (error "invalid duplicate handler name:"
3058 (if (list? handler-names)
3060 (list handler-names)))))
3062 (define default-duplicate-binding-procedures
3063 (make-mutable-parameter #f))
3065 (define default-duplicate-binding-handler
3066 (make-mutable-parameter '(replace warn-override-core warn last)
3067 (lambda (handler-names)
3068 (default-duplicate-binding-procedures
3069 (lookup-duplicates-handlers handler-names))
3074 ;;; {`cond-expand' for SRFI-0 support.}
3076 ;;; This syntactic form expands into different commands or
3077 ;;; definitions, depending on the features provided by the Scheme
3083 ;;; --> (cond-expand <cond-expand-clause>+)
3084 ;;; | (cond-expand <cond-expand-clause>* (else <command-or-definition>))
3085 ;;; <cond-expand-clause>
3086 ;;; --> (<feature-requirement> <command-or-definition>*)
3087 ;;; <feature-requirement>
3088 ;;; --> <feature-identifier>
3089 ;;; | (and <feature-requirement>*)
3090 ;;; | (or <feature-requirement>*)
3091 ;;; | (not <feature-requirement>)
3092 ;;; <feature-identifier>
3093 ;;; --> <a symbol which is the name or alias of a SRFI>
3095 ;;; Additionally, this implementation provides the
3096 ;;; <feature-identifier>s `guile' and `r5rs', so that programs can
3097 ;;; determine the implementation type and the supported standard.
3099 ;;; Currently, the following feature identifiers are supported:
3101 ;;; guile r5rs srfi-0 srfi-4 srfi-6 srfi-13 srfi-14 srfi-55 srfi-61
3103 ;;; Remember to update the features list when adding more SRFIs.
3106 (define %cond-expand-features
3107 ;; Adjust the above comment when changing this.
3110 srfi-0 ;; cond-expand itself
3111 srfi-4 ;; homogenous numeric vectors
3112 srfi-6 ;; open-input-string etc, in the guile core
3113 srfi-13 ;; string library
3114 srfi-14 ;; character sets
3115 srfi-55 ;; require-extension
3116 srfi-61 ;; general cond clause
3119 ;; This table maps module public interfaces to the list of features.
3121 (define %cond-expand-table (make-hash-table 31))
3123 ;; Add one or more features to the `cond-expand' feature list of the
3126 (define (cond-expand-provide module features)
3127 (let ((mod (module-public-interface module)))
3129 (hashq-set! %cond-expand-table mod
3130 (append (hashq-ref %cond-expand-table mod '())
3134 (procedure->memoizing-macro
3136 (let ((clauses (cdr exp))
3137 (syntax-error (lambda (cl)
3138 (error "invalid clause in `cond-expand'" cl))))
3144 (or (memq clause %cond-expand-features)
3145 (let lp ((uses (module-uses (env-module env))))
3148 (hashq-ref %cond-expand-table
3154 ((eq? 'and (car clause))
3155 (let lp ((l (cdr clause)))
3159 (and (test-clause (car l)) (lp (cdr l))))
3161 (syntax-error clause)))))
3162 ((eq? 'or (car clause))
3163 (let lp ((l (cdr clause)))
3167 (or (test-clause (car l)) (lp (cdr l))))
3169 (syntax-error clause)))))
3170 ((eq? 'not (car clause))
3171 (cond ((not (pair? (cdr clause)))
3172 (syntax-error clause))
3173 ((pair? (cddr clause))
3174 ((syntax-error clause))))
3175 (not (test-clause (cadr clause))))
3177 (syntax-error clause))))
3179 (syntax-error clause))))))
3180 (let lp ((c clauses))
3183 (error "Unfulfilled `cond-expand'"))
3186 ((not (pair? (car c)))
3187 (syntax-error (car c)))
3188 ((test-clause (caar c))
3189 `(begin ,@(cdar c)))
3190 ((eq? (caar c) 'else)
3193 `(begin ,@(cdar c)))
3195 (lp (cdr c))))))))))
3197 ;; This procedure gets called from the startup code with a list of
3198 ;; numbers, which are the numbers of the SRFIs to be loaded on startup.
3200 (define (use-srfis srfis)
3201 (process-use-modules
3203 (list (list 'srfi (string->symbol
3204 (string-append "srfi-" (number->string num))))))
3209 ;;; srfi-55: require-extension
3212 (define-macro (require-extension extension-spec)
3213 ;; This macro only handles the srfi extension, which, at present, is
3214 ;; the only one defined by the standard.
3215 (if (not (pair? extension-spec))
3216 (scm-error 'wrong-type-arg "require-extension"
3217 "Not an extension: ~S" (list extension-spec) #f))
3218 (let ((extension (car extension-spec))
3219 (extension-args (cdr extension-spec)))
3222 (let ((use-list '()))
3225 (if (not (integer? i))
3226 (scm-error 'wrong-type-arg "require-extension"
3227 "Invalid srfi name: ~S" (list i) #f))
3228 (let ((srfi-sym (string->symbol
3229 (string-append "srfi-" (number->string i)))))
3230 (if (not (memq srfi-sym %cond-expand-features))
3231 (set! use-list (cons `(use-modules (srfi ,srfi-sym))
3234 (if (pair? use-list)
3235 ;; i.e. (begin (use-modules x) (use-modules y) (use-modules z))
3236 `(begin ,@(reverse! use-list)))))
3239 'wrong-type-arg "require-extension"
3240 "Not a recognized extension type: ~S" (list extension) #f)))))
3244 ;;; {Load emacs interface support if emacs option is given.}
3247 (define (named-module-use! user usee)
3248 (module-use! (resolve-module user) (resolve-interface usee)))
3250 (define (load-emacs-interface)
3251 (and (provided? 'debug-extensions)
3252 (debug-enable 'backtrace))
3253 (named-module-use! '(guile-user) '(ice-9 emacs)))
3257 (define using-readline?
3258 (let ((using-readline? (make-fluid)))
3259 (make-procedure-with-setter
3260 (lambda () (fluid-ref using-readline?))
3261 (lambda (v) (fluid-set! using-readline? v)))))
3264 (let ((guile-user-module (resolve-module '(guile-user))))
3266 ;; Load emacs interface support if emacs option is given.
3267 (if (and (module-defined? guile-user-module 'use-emacs-interface)
3268 (module-ref guile-user-module 'use-emacs-interface))
3269 (load-emacs-interface))
3271 ;; Use some convenient modules (in reverse order)
3273 (set-current-module guile-user-module)
3274 (process-use-modules
3279 (if (provided? 'regex)
3282 (if (provided? 'threads)
3283 '(((ice-9 threads)))
3285 ;; load debugger on demand
3286 (module-autoload! guile-user-module '(ice-9 debugger) '(debug))
3288 ;; Note: SIGFPE, SIGSEGV and SIGBUS are actually "query-only" (see
3289 ;; scmsigs.c scm_sigaction_for_thread), so the handlers setup here have
3291 (let ((old-handlers #f)
3292 (start-repl (module-ref (resolve-interface '(system repl repl))
3294 (signals (if (provided? 'posix)
3295 `((,SIGINT . "User interrupt")
3296 (,SIGFPE . "Arithmetic error")
3298 . "Bad memory access (Segmentation violation)"))
3300 ;; no SIGBUS on mingw
3301 (if (defined? 'SIGBUS)
3302 (set! signals (acons SIGBUS "Bad memory access (bus error)"
3309 (let ((make-handler (lambda (msg)
3311 ;; Make a backup copy of the stack
3312 (fluid-set! before-signal-stack
3313 (fluid-ref the-last-stack))
3321 (map (lambda (sig-msg)
3322 (sigaction (car sig-msg)
3323 (make-handler (cdr sig-msg))))
3326 ;; the protected thunk.
3328 (let ((status (start-repl 'scheme)))
3329 (run-hook exit-hook)
3334 (map (lambda (sig-msg old-handler)
3335 (if (not (car old-handler))
3336 ;; restore original C handler.
3337 (sigaction (car sig-msg) #f)
3338 ;; restore Scheme handler, SIG_IGN or SIG_DFL.
3339 (sigaction (car sig-msg)
3341 (cdr old-handler))))
3342 signals old-handlers))))))
3344 ;;; This hook is run at the very end of an interactive session.
3346 (define exit-hook (make-hook))
3350 ;;; {Deprecated stuff}
3354 (define (feature? sym)
3355 (issue-deprecation-warning
3356 "`feature?' is deprecated. Use `provided?' instead.")
3360 (primitive-load-path "ice-9/deprecated"))
3364 ;;; Place the user in the guile-user module.
3367 ;;; FIXME: annotate ?
3368 ;; (define (syncase exp)
3369 ;; (with-fluids ((expansion-eval-closure
3370 ;; (module-eval-closure (current-module))))
3371 ;; (deannotate/source-properties (sc-expand (annotate exp)))))
3373 (define-module (guile-user))
3375 ;;; boot-9.scm ends here