3 ;;;; Copyright (C) 1995,1996,1997,1998,1999,2000,2001,2002,2003,2004
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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 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
40 (if (not (memq sym *features*))
41 (set! *features* (cons sym *features*))))
43 ;; Return #t iff FEATURE is available to this Guile interpreter. In SLIB,
44 ;; provided? also checks to see if the module is available. We should do that
47 (define (provided? feature)
48 (and (memq feature *features*) #t))
50 ;; let format alias simple-format until the more complete version is loaded
52 (define format simple-format)
59 ;; (eval-case ((situation*) forms)* (else forms)?)
61 ;; Evaluate certain code based on the situation that eval-case is used
62 ;; in. The only defined situation right now is `load-toplevel' which
63 ;; triggers for code evaluated at the top-level, for example from the
64 ;; REPL or when loading a file.
67 (procedure->memoizing-macro
69 (define (toplevel-env? env)
70 (or (not (pair? env)) (not (pair? (car env)))))
72 (error "syntax error in eval-case"))
73 (let loop ((clauses (cdr exp)))
77 ((not (list? (car clauses)))
79 ((eq? 'else (caar clauses))
80 (or (null? (cdr clauses))
82 (cons 'begin (cdar clauses)))
83 ((not (list? (caar clauses)))
85 ((and (toplevel-env? env)
86 (memq 'load-toplevel (caar clauses)))
87 (cons 'begin (cdar clauses)))
89 (loop (cdr clauses))))))))
95 ;;; Depends on: features, eval-case
98 (define macro-table (make-weak-key-hash-table 61))
99 (define xformer-table (make-weak-key-hash-table 61))
101 (define (defmacro? m) (hashq-ref macro-table m))
102 (define (assert-defmacro?! m) (hashq-set! macro-table m #t))
103 (define (defmacro-transformer m) (hashq-ref xformer-table m))
104 (define (set-defmacro-transformer! m t) (hashq-set! xformer-table m t))
106 (define defmacro:transformer
108 (let* ((xform (lambda (exp env)
109 (copy-tree (apply f (cdr exp)))))
110 (a (procedure->memoizing-macro xform)))
111 (assert-defmacro?! a)
112 (set-defmacro-transformer! a f)
117 (let ((defmacro-transformer
118 (lambda (name parms . body)
119 (let ((transformer `(lambda ,parms ,@body)))
122 (define ,name (defmacro:transformer ,transformer)))
124 (error "defmacro can only be used at the top level")))))))
125 (defmacro:transformer defmacro-transformer)))
127 (define defmacro:syntax-transformer
131 (copy-tree (apply f (cdr exp)))))))
134 ;; XXX - should the definition of the car really be looked up in the
137 (define (macroexpand-1 e)
139 ((pair? e) (let* ((a (car e))
140 (val (and (symbol? a) (local-ref (list a)))))
142 (apply (defmacro-transformer val) (cdr e))
146 (define (macroexpand e)
148 ((pair? e) (let* ((a (car e))
149 (val (and (symbol? a) (local-ref (list a)))))
151 (macroexpand (apply (defmacro-transformer val) (cdr e)))
161 ;;; Depends on: defmacro
164 (defmacro begin-deprecated forms
165 (if (include-deprecated-features)
171 ;;; {R4RS compliance}
174 (primitive-load-path "ice-9/r4rs.scm")
178 ;;; {Simple Debugging Tools}
181 ;; peek takes any number of arguments, writes them to the
182 ;; current ouput port, and returns the last argument.
183 ;; It is handy to wrap around an expression to look at
184 ;; a value each time is evaluated, e.g.:
186 ;; (+ 10 (troublesome-fn))
187 ;; => (+ 10 (pk 'troublesome-fn-returned (troublesome-fn)))
190 (define (peek . stuff)
195 (car (last-pair stuff)))
199 (define (warn . stuff)
200 (with-output-to-port (current-error-port)
203 (display ";;; WARNING ")
206 (car (last-pair stuff)))))
210 ;;; {Trivial Functions}
213 (define (identity x) x)
214 (define (1+ n) (+ n 1))
215 (define (1- n) (+ n -1))
216 (define (and=> value procedure) (and value (procedure value)))
217 (define call/cc call-with-current-continuation)
219 ;;; apply-to-args is functionally redundant with apply and, worse,
220 ;;; is less general than apply since it only takes two arguments.
222 ;;; On the other hand, apply-to-args is a syntacticly convenient way to
223 ;;; perform binding in many circumstances when the "let" family of
224 ;;; of forms don't cut it. E.g.:
226 ;;; (apply-to-args (return-3d-mouse-coords)
231 (define (apply-to-args args fn) (apply fn args))
233 (defmacro false-if-exception (expr)
234 `(catch #t (lambda () ,expr)
239 ;;; {General Properties}
242 ;; This is a more modern interface to properties. It will replace all
243 ;; other property-like things eventually.
245 (define (make-object-property)
246 (let ((prop (primitive-make-property #f)))
247 (make-procedure-with-setter
248 (lambda (obj) (primitive-property-ref prop obj))
249 (lambda (obj val) (primitive-property-set! prop obj val)))))
253 ;;; {Symbol Properties}
256 (define (symbol-property sym prop)
257 (let ((pair (assoc prop (symbol-pref sym))))
258 (and pair (cdr pair))))
260 (define (set-symbol-property! sym prop val)
261 (let ((pair (assoc prop (symbol-pref sym))))
264 (symbol-pset! sym (acons prop val (symbol-pref sym))))))
266 (define (symbol-property-remove! sym prop)
267 (let ((pair (assoc prop (symbol-pref sym))))
269 (symbol-pset! sym (delq! pair (symbol-pref sym))))))
276 (if (provided? 'array)
277 (primitive-load-path "ice-9/arrays.scm"))
284 (define (kw-arg-ref args kw)
285 (let ((rem (member kw args)))
286 (and rem (pair? (cdr rem)) (cadr rem))))
293 (define (struct-layout s)
294 (struct-ref (struct-vtable s) vtable-index-layout))
301 (define the-environment
306 (define the-root-environment (the-environment))
308 (define (environment-module env)
309 (let ((closure (and (pair? env) (car (last-pair env)))))
310 (and closure (procedure-property closure 'module))))
317 ;; Printing records: by default, records are printed as
319 ;; #<type-name field1: val1 field2: val2 ...>
321 ;; You can change that by giving a custom printing function to
322 ;; MAKE-RECORD-TYPE (after the list of field symbols). This function
323 ;; will be called like
325 ;; (<printer> object port)
327 ;; It should print OBJECT to PORT.
329 (define (inherit-print-state old-port new-port)
330 (if (get-print-state old-port)
331 (port-with-print-state new-port (get-print-state old-port))
334 ;; 0: type-name, 1: fields
335 (define record-type-vtable
336 (make-vtable-vtable "prpr" 0
338 (cond ((eq? s record-type-vtable)
339 (display "#<record-type-vtable>" p))
341 (display "#<record-type " p)
342 (display (record-type-name s) p)
345 (define (record-type? obj)
346 (and (struct? obj) (eq? record-type-vtable (struct-vtable obj))))
348 (define (make-record-type type-name fields . opt)
349 (let ((printer-fn (and (pair? opt) (car opt))))
350 (let ((struct (make-struct record-type-vtable 0
353 (map (lambda (f) "pw") fields)))
357 (display type-name p)
358 (let loop ((fields fields)
361 ((not (null? fields))
363 (display (car fields) p)
365 (display (struct-ref s off) p)
366 (loop (cdr fields) (+ 1 off)))))
369 (copy-tree fields))))
370 ;; Temporary solution: Associate a name to the record type descriptor
371 ;; so that the object system can create a wrapper class for it.
372 (set-struct-vtable-name! struct (if (symbol? type-name)
374 (string->symbol type-name)))
377 (define (record-type-name obj)
378 (if (record-type? obj)
379 (struct-ref obj vtable-offset-user)
380 (error 'not-a-record-type obj)))
382 (define (record-type-fields obj)
383 (if (record-type? obj)
384 (struct-ref obj (+ 1 vtable-offset-user))
385 (error 'not-a-record-type obj)))
387 (define (record-constructor rtd . opt)
388 (let ((field-names (if (pair? opt) (car opt) (record-type-fields rtd))))
389 (local-eval `(lambda ,field-names
390 (make-struct ',rtd 0 ,@(map (lambda (f)
391 (if (memq f field-names)
394 (record-type-fields rtd))))
395 the-root-environment)))
397 (define (record-predicate rtd)
398 (lambda (obj) (and (struct? obj) (eq? rtd (struct-vtable obj)))))
400 (define (record-accessor rtd field-name)
401 (let* ((pos (list-index (record-type-fields rtd) field-name)))
403 (error 'no-such-field field-name))
404 (local-eval `(lambda (obj)
405 (and (eq? ',rtd (record-type-descriptor obj))
406 (struct-ref obj ,pos)))
407 the-root-environment)))
409 (define (record-modifier rtd field-name)
410 (let* ((pos (list-index (record-type-fields rtd) field-name)))
412 (error 'no-such-field field-name))
413 (local-eval `(lambda (obj val)
414 (and (eq? ',rtd (record-type-descriptor obj))
415 (struct-set! obj ,pos val)))
416 the-root-environment)))
419 (define (record? obj)
420 (and (struct? obj) (record-type? (struct-vtable obj))))
422 (define (record-type-descriptor obj)
425 (error 'not-a-record obj)))
434 (define (->bool x) (not (not x)))
441 (define (symbol-append . args)
442 (string->symbol (apply string-append (map symbol->string args))))
444 (define (list->symbol . args)
445 (string->symbol (apply list->string args)))
447 (define (symbol . args)
448 (string->symbol (apply string args)))
455 (define (list-index l k)
461 (loop (+ n 1) (cdr l))))))
463 (define (make-list n . init)
464 (if (pair? init) (set! init (car init)))
465 (let loop ((answer '())
469 (loop (cons init answer) (- n 1)))))
473 ;;; {and-map and or-map}
475 ;;; (and-map fn lst) is like (and (fn (car lst)) (fn (cadr lst)) (fn...) ...)
476 ;;; (or-map fn lst) is like (or (fn (car lst)) (fn (cadr lst)) (fn...) ...)
481 ;; Apply f to successive elements of l until exhaustion or f returns #f.
482 ;; If returning early, return #f. Otherwise, return the last value returned
483 ;; by f. If f has never been called because l is empty, return #t.
485 (define (and-map f lst)
486 (let loop ((result #t)
491 (loop (f (car l)) (cdr l))))))
495 ;; Apply f to successive elements of l until exhaustion or while f returns #f.
496 ;; If returning early, return the return value of f.
498 (define (or-map f lst)
499 (let loop ((result #f)
503 (loop (f (car l)) (cdr l))))))
507 (if (provided? 'posix)
508 (primitive-load-path "ice-9/posix.scm"))
510 (if (provided? 'socket)
511 (primitive-load-path "ice-9/networking.scm"))
513 ;; For reference, Emacs file-exists-p uses stat in this same way.
514 ;; ENHANCE-ME: Catching an exception from stat is a bit wasteful, do this in
515 ;; C where all that's needed is to inspect the return from stat().
517 (if (provided? 'posix)
519 (->bool (false-if-exception (stat str))))
521 (let ((port (catch 'system-error (lambda () (open-file str OPEN_READ))
523 (if port (begin (close-port port) #t)
526 (define file-is-directory?
527 (if (provided? 'posix)
529 (eq? (stat:type (stat str)) 'directory))
531 (let ((port (catch 'system-error
532 (lambda () (open-file (string-append str "/.")
535 (if port (begin (close-port port) #t)
538 (define (has-suffix? str suffix)
539 (let ((sufl (string-length suffix))
540 (sl (string-length str)))
542 (string=? (substring str (- sl sufl) sl) suffix))))
544 (define (system-error-errno args)
545 (if (eq? (car args) 'system-error)
546 (car (list-ref args 4))
554 (define (error . args)
557 (scm-error 'misc-error #f "?" #f #f)
558 (let loop ((msg "~A")
560 (if (not (null? rest))
561 (loop (string-append msg " ~S")
563 (scm-error 'misc-error #f msg args #f)))))
565 ;; bad-throw is the hook that is called upon a throw to a an unhandled
566 ;; key (unless the throw has four arguments, in which case
567 ;; it's usually interpreted as an error throw.)
568 ;; If the key has a default handler (a throw-handler-default property),
569 ;; it is applied to the throw.
571 (define (bad-throw key . args)
572 (let ((default (symbol-property key 'throw-handler-default)))
573 (or (and default (apply default key args))
574 (apply error "unhandled-exception:" key args))))
578 (define (tm:sec obj) (vector-ref obj 0))
579 (define (tm:min obj) (vector-ref obj 1))
580 (define (tm:hour obj) (vector-ref obj 2))
581 (define (tm:mday obj) (vector-ref obj 3))
582 (define (tm:mon obj) (vector-ref obj 4))
583 (define (tm:year obj) (vector-ref obj 5))
584 (define (tm:wday obj) (vector-ref obj 6))
585 (define (tm:yday obj) (vector-ref obj 7))
586 (define (tm:isdst obj) (vector-ref obj 8))
587 (define (tm:gmtoff obj) (vector-ref obj 9))
588 (define (tm:zone obj) (vector-ref obj 10))
590 (define (set-tm:sec obj val) (vector-set! obj 0 val))
591 (define (set-tm:min obj val) (vector-set! obj 1 val))
592 (define (set-tm:hour obj val) (vector-set! obj 2 val))
593 (define (set-tm:mday obj val) (vector-set! obj 3 val))
594 (define (set-tm:mon obj val) (vector-set! obj 4 val))
595 (define (set-tm:year obj val) (vector-set! obj 5 val))
596 (define (set-tm:wday obj val) (vector-set! obj 6 val))
597 (define (set-tm:yday obj val) (vector-set! obj 7 val))
598 (define (set-tm:isdst obj val) (vector-set! obj 8 val))
599 (define (set-tm:gmtoff obj val) (vector-set! obj 9 val))
600 (define (set-tm:zone obj val) (vector-set! obj 10 val))
602 (define (tms:clock obj) (vector-ref obj 0))
603 (define (tms:utime obj) (vector-ref obj 1))
604 (define (tms:stime obj) (vector-ref obj 2))
605 (define (tms:cutime obj) (vector-ref obj 3))
606 (define (tms:cstime obj) (vector-ref obj 4))
608 (define file-position ftell)
609 (define (file-set-position port offset . whence)
610 (let ((whence (if (eq? whence '()) SEEK_SET (car whence))))
611 (seek port offset whence)))
613 (define (move->fdes fd/port fd)
614 (cond ((integer? fd/port)
615 (dup->fdes fd/port fd)
619 (primitive-move->fdes fd/port fd)
620 (set-port-revealed! fd/port 1)
623 (define (release-port-handle port)
624 (let ((revealed (port-revealed port)))
626 (set-port-revealed! port (- revealed 1)))))
628 (define (dup->port port/fd mode . maybe-fd)
629 (let ((port (fdopen (apply dup->fdes port/fd maybe-fd)
632 (set-port-revealed! port 1))
635 (define (dup->inport port/fd . maybe-fd)
636 (apply dup->port port/fd "r" maybe-fd))
638 (define (dup->outport port/fd . maybe-fd)
639 (apply dup->port port/fd "w" maybe-fd))
641 (define (dup port/fd . maybe-fd)
642 (if (integer? port/fd)
643 (apply dup->fdes port/fd maybe-fd)
644 (apply dup->port port/fd (port-mode port/fd) maybe-fd)))
646 (define (duplicate-port port modes)
647 (dup->port port modes))
649 (define (fdes->inport fdes)
650 (let loop ((rest-ports (fdes->ports fdes)))
651 (cond ((null? rest-ports)
652 (let ((result (fdopen fdes "r")))
653 (set-port-revealed! result 1)
655 ((input-port? (car rest-ports))
656 (set-port-revealed! (car rest-ports)
657 (+ (port-revealed (car rest-ports)) 1))
660 (loop (cdr rest-ports))))))
662 (define (fdes->outport fdes)
663 (let loop ((rest-ports (fdes->ports fdes)))
664 (cond ((null? rest-ports)
665 (let ((result (fdopen fdes "w")))
666 (set-port-revealed! result 1)
668 ((output-port? (car rest-ports))
669 (set-port-revealed! (car rest-ports)
670 (+ (port-revealed (car rest-ports)) 1))
673 (loop (cdr rest-ports))))))
675 (define (port->fdes port)
676 (set-port-revealed! port (+ (port-revealed port) 1))
679 (define (setenv name value)
681 (putenv (string-append name "=" value))
684 (define (unsetenv name)
685 "Remove the entry for NAME from the environment."
693 ;;; Here for backward compatability
695 (define scheme-file-suffix (lambda () ".scm"))
697 (define (in-vicinity vicinity file)
698 (let ((tail (let ((len (string-length vicinity)))
701 (string-ref vicinity (- len 1))))))
702 (string-append vicinity
711 ;;; {Help for scm_shell}
713 ;;; The argument-processing code used by Guile-based shells generates
714 ;;; Scheme code based on the argument list. This page contains help
715 ;;; functions for the code it generates.
718 (define (command-line) (program-arguments))
720 ;; This is mostly for the internal use of the code generated by
721 ;; scm_compile_shell_switches.
723 (define (turn-on-debugging)
724 (debug-enable 'debug)
725 (debug-enable 'backtrace)
726 (read-enable 'positions))
728 (define (load-user-init)
729 (let* ((home (or (getenv "HOME")
730 (false-if-exception (passwd:dir (getpwuid (getuid))))
731 "/")) ;; fallback for cygwin etc.
732 (init-file (in-vicinity home ".guile")))
733 (if (file-exists? init-file)
734 (primitive-load init-file))))
738 ;;; {Loading by paths}
741 ;;; Load a Scheme source file named NAME, searching for it in the
742 ;;; directories listed in %load-path, and applying each of the file
743 ;;; name extensions listed in %load-extensions.
744 (define (load-from-path name)
745 (start-stack 'load-stack
746 (primitive-load-path name)))
751 ;;; {Transcendental Functions}
753 ;;; Derived from "Transcen.scm", Complex trancendental functions for SCM.
754 ;;; Written by Jerry D. Hedden, (C) FSF.
755 ;;; See the file `COPYING' for terms applying to this program.
759 (if (real? z) ($exp z)
760 (make-polar ($exp (real-part z)) (imag-part z))))
763 (if (and (real? z) (>= z 0))
765 (make-rectangular ($log (magnitude z)) (angle z))))
769 (if (negative? z) (make-rectangular 0 ($sqrt (- z)))
771 (make-polar ($sqrt (magnitude z)) (/ (angle z) 2))))
774 (let ((integer-expt integer-expt))
776 (cond ((and (exact? z2) (integer? z2))
777 (integer-expt z1 z2))
778 ((and (real? z2) (real? z1) (>= z1 0))
781 (exp (* z2 (log z1))))))))
784 (if (real? z) ($sinh z)
785 (let ((x (real-part z)) (y (imag-part z)))
786 (make-rectangular (* ($sinh x) ($cos y))
787 (* ($cosh x) ($sin y))))))
789 (if (real? z) ($cosh z)
790 (let ((x (real-part z)) (y (imag-part z)))
791 (make-rectangular (* ($cosh x) ($cos y))
792 (* ($sinh x) ($sin y))))))
794 (if (real? z) ($tanh z)
795 (let* ((x (* 2 (real-part z)))
796 (y (* 2 (imag-part z)))
797 (w (+ ($cosh x) ($cos y))))
798 (make-rectangular (/ ($sinh x) w) (/ ($sin y) w)))))
801 (if (real? z) ($asinh z)
802 (log (+ z (sqrt (+ (* z z) 1))))))
805 (if (and (real? z) (>= z 1))
807 (log (+ z (sqrt (- (* z z) 1))))))
810 (if (and (real? z) (> z -1) (< z 1))
812 (/ (log (/ (+ 1 z) (- 1 z))) 2)))
815 (if (real? z) ($sin z)
816 (let ((x (real-part z)) (y (imag-part z)))
817 (make-rectangular (* ($sin x) ($cosh y))
818 (* ($cos x) ($sinh y))))))
820 (if (real? z) ($cos z)
821 (let ((x (real-part z)) (y (imag-part z)))
822 (make-rectangular (* ($cos x) ($cosh y))
823 (- (* ($sin x) ($sinh y)))))))
825 (if (real? z) ($tan z)
826 (let* ((x (* 2 (real-part z)))
827 (y (* 2 (imag-part z)))
828 (w (+ ($cos x) ($cosh y))))
829 (make-rectangular (/ ($sin x) w) (/ ($sinh y) w)))))
832 (if (and (real? z) (>= z -1) (<= z 1))
834 (* -i (asinh (* +i z)))))
837 (if (and (real? z) (>= z -1) (<= z 1))
839 (+ (/ (angle -1) 2) (* +i (asinh (* +i z))))))
843 (if (real? z) ($atan z)
844 (/ (log (/ (- +i z) (+ +i z))) +2i))
848 (/ (log arg) (log 10)))
852 ;;; {Reader Extensions}
854 ;;; Reader code for various "#c" forms.
857 (read-hash-extend #\' (lambda (c port)
860 (define read-eval? (make-fluid))
861 (fluid-set! read-eval? #f)
862 (read-hash-extend #\.
864 (if (fluid-ref read-eval?)
865 (eval (read port) (interaction-environment))
867 "#. read expansion found and read-eval? is #f."))))
871 ;;; {Command Line Options}
874 (define (get-option argv kw-opts kw-args return)
879 ((or (not (eq? #\- (string-ref (car argv) 0)))
880 (eq? (string-length (car argv)) 1))
881 (return 'normal-arg (car argv) (cdr argv)))
883 ((eq? #\- (string-ref (car argv) 1))
884 (let* ((kw-arg-pos (or (string-index (car argv) #\=)
885 (string-length (car argv))))
886 (kw (symbol->keyword (substring (car argv) 2 kw-arg-pos)))
887 (kw-opt? (member kw kw-opts))
888 (kw-arg? (member kw kw-args))
889 (arg (or (and (not (eq? kw-arg-pos (string-length (car argv))))
890 (substring (car argv)
892 (string-length (car argv))))
894 (begin (set! argv (cdr argv)) (car argv))))))
895 (if (or kw-opt? kw-arg?)
896 (return kw arg (cdr argv))
897 (return 'usage-error kw (cdr argv)))))
900 (let* ((char (substring (car argv) 1 2))
901 (kw (symbol->keyword char)))
905 (let* ((rest-car (substring (car argv) 2 (string-length (car argv))))
906 (new-argv (if (= 0 (string-length rest-car))
908 (cons (string-append "-" rest-car) (cdr argv)))))
909 (return kw #f new-argv)))
912 (let* ((rest-car (substring (car argv) 2 (string-length (car argv))))
913 (arg (if (= 0 (string-length rest-car))
916 (new-argv (if (= 0 (string-length rest-car))
919 (return kw arg new-argv)))
921 (else (return 'usage-error kw argv)))))))
923 (define (for-next-option proc argv kw-opts kw-args)
924 (let loop ((argv argv))
925 (get-option argv kw-opts kw-args
926 (lambda (opt opt-arg argv)
927 (and opt (proc opt opt-arg argv loop))))))
929 (define (display-usage-report kw-desc)
932 (or (eq? (car kw) #t)
935 (help (cadr opt-desc))
936 (opts (car opt-desc))
937 (opts-proper (if (string? (car opts)) (cdr opts) opts))
938 (arg-name (if (string? (car opts))
939 (string-append "<" (car opts) ">")
941 (left-part (string-append
942 (with-output-to-string
944 (map (lambda (x) (display (keyword->symbol x)) (display " "))
947 (middle-part (if (and (< (string-length left-part) 30)
948 (< (string-length help) 40))
949 (make-string (- 30 (string-length left-part)) #\ )
952 (display middle-part)
959 (define (transform-usage-lambda cases)
960 (let* ((raw-usage (delq! 'else (map car cases)))
961 (usage-sans-specials (map (lambda (x)
962 (or (and (not (list? x)) x)
963 (and (symbol? (car x)) #t)
964 (and (boolean? (car x)) #t)
967 (usage-desc (delq! #t usage-sans-specials))
968 (kw-desc (map car usage-desc))
969 (kw-opts (apply append (map (lambda (x) (and (not (string? (car x))) x)) kw-desc)))
970 (kw-args (apply append (map (lambda (x) (and (string? (car x)) (cdr x))) kw-desc)))
971 (transmogrified-cases (map (lambda (case)
972 (cons (let ((opts (car case)))
973 (if (or (boolean? opts) (eq? 'else opts))
976 ((symbol? (car opts)) opts)
977 ((boolean? (car opts)) opts)
978 ((string? (caar opts)) (cdar opts))
982 `(let ((%display-usage (lambda () (display-usage-report ',usage-desc))))
984 (let %next-arg ((%argv %argv))
988 (lambda (%opt %arg %new-argv)
990 ,@ transmogrified-cases))))))))
995 ;;; {Low Level Modules}
997 ;;; These are the low level data structures for modules.
999 ;;; Every module object is of the type 'module-type', which is a record
1000 ;;; consisting of the following members:
1002 ;;; - eval-closure: the function that defines for its module the strategy that
1003 ;;; shall be followed when looking up symbols in the module.
1005 ;;; An eval-closure is a function taking two arguments: the symbol to be
1006 ;;; looked up and a boolean value telling whether a binding for the symbol
1007 ;;; should be created if it does not exist yet. If the symbol lookup
1008 ;;; succeeded (either because an existing binding was found or because a new
1009 ;;; binding was created), a variable object representing the binding is
1010 ;;; returned. Otherwise, the value #f is returned. Note that the eval
1011 ;;; closure does not take the module to be searched as an argument: During
1012 ;;; construction of the eval-closure, the eval-closure has to store the
1013 ;;; module it belongs to in its environment. This means, that any
1014 ;;; eval-closure can belong to only one module.
1016 ;;; The eval-closure of a module can be defined arbitrarily. However, three
1017 ;;; special cases of eval-closures are to be distinguished: During startup
1018 ;;; the module system is not yet activated. In this phase, no modules are
1019 ;;; defined and all bindings are automatically stored by the system in the
1020 ;;; pre-modules-obarray. Since no eval-closures exist at this time, the
1021 ;;; functions which require an eval-closure as their argument need to be
1022 ;;; passed the value #f.
1024 ;;; The other two special cases of eval-closures are the
1025 ;;; standard-eval-closure and the standard-interface-eval-closure. Both
1026 ;;; behave equally for the case that no new binding is to be created. The
1027 ;;; difference between the two comes in, when the boolean argument to the
1028 ;;; eval-closure indicates that a new binding shall be created if it is not
1031 ;;; Given that no new binding shall be created, both standard eval-closures
1032 ;;; define the following standard strategy of searching bindings in the
1033 ;;; module: First, the module's obarray is searched for the symbol. Second,
1034 ;;; if no binding for the symbol was found in the module's obarray, the
1035 ;;; module's binder procedure is exececuted. If this procedure did not
1036 ;;; return a binding for the symbol, the modules referenced in the module's
1037 ;;; uses list are recursively searched for a binding of the symbol. If the
1038 ;;; binding can not be found in these modules also, the symbol lookup has
1041 ;;; If a new binding shall be created, the standard-interface-eval-closure
1042 ;;; immediately returns indicating failure. That is, it does not even try
1043 ;;; to look up the symbol. In contrast, the standard-eval-closure would
1044 ;;; first search the obarray, and if no binding was found there, would
1045 ;;; create a new binding in the obarray, therefore not calling the binder
1046 ;;; procedure or searching the modules in the uses list.
1048 ;;; The explanation of the following members obarray, binder and uses
1049 ;;; assumes that the symbol lookup follows the strategy that is defined in
1050 ;;; the standard-eval-closure and the standard-interface-eval-closure.
1052 ;;; - obarray: a hash table that maps symbols to variable objects. In this
1053 ;;; hash table, the definitions are found that are local to the module (that
1054 ;;; is, not imported from other modules). When looking up bindings in the
1055 ;;; module, this hash table is searched first.
1057 ;;; - binder: either #f or a function taking a module and a symbol argument.
1058 ;;; If it is a function it is called after the obarray has been
1059 ;;; unsuccessfully searched for a binding. It then can provide bindings
1060 ;;; that would otherwise not be found locally in the module.
1062 ;;; - uses: a list of modules from which non-local bindings can be inherited.
1063 ;;; These modules are the third place queried for bindings after the obarray
1064 ;;; has been unsuccessfully searched and the binder function did not deliver
1065 ;;; a result either.
1067 ;;; - transformer: either #f or a function taking a scheme expression as
1068 ;;; delivered by read. If it is a function, it will be called to perform
1069 ;;; syntax transformations (e. g. makro expansion) on the given scheme
1070 ;;; expression. The output of the transformer function will then be passed
1071 ;;; to Guile's internal memoizer. This means that the output must be valid
1072 ;;; scheme code. The only exception is, that the output may make use of the
1073 ;;; syntax extensions provided to identify the modules that a binding
1076 ;;; - name: the name of the module. This is used for all kinds of printing
1077 ;;; outputs. In certain places the module name also serves as a way of
1078 ;;; identification. When adding a module to the uses list of another
1079 ;;; module, it is made sure that the new uses list will not contain two
1080 ;;; modules of the same name.
1082 ;;; - kind: classification of the kind of module. The value is (currently?)
1083 ;;; only used for printing. It has no influence on how a module is treated.
1084 ;;; Currently the following values are used when setting the module kind:
1085 ;;; 'module, 'directory, 'interface, 'custom-interface. If no explicit kind
1086 ;;; is set, it defaults to 'module.
1088 ;;; - duplicates-handlers
1090 ;;; - duplicates-interface
1094 ;;; - weak-observers
1098 ;;; In addition, the module may (must?) contain a binding for
1099 ;;; %module-public-interface... More explanations here...
1101 ;;; !!! warning: The interface to lazy binder procedures is going
1102 ;;; to be changed in an incompatible way to permit all the basic
1103 ;;; module ops to be virtualized.
1105 ;;; (make-module size use-list lazy-binding-proc) => module
1106 ;;; module-{obarray,uses,binder}[|-set!]
1107 ;;; (module? obj) => [#t|#f]
1108 ;;; (module-locally-bound? module symbol) => [#t|#f]
1109 ;;; (module-bound? module symbol) => [#t|#f]
1110 ;;; (module-symbol-locally-interned? module symbol) => [#t|#f]
1111 ;;; (module-symbol-interned? module symbol) => [#t|#f]
1112 ;;; (module-local-variable module symbol) => [#<variable ...> | #f]
1113 ;;; (module-variable module symbol) => [#<variable ...> | #f]
1114 ;;; (module-symbol-binding module symbol opt-value)
1115 ;;; => [ <obj> | opt-value | an error occurs ]
1116 ;;; (module-make-local-var! module symbol) => #<variable...>
1117 ;;; (module-add! module symbol var) => unspecified
1118 ;;; (module-remove! module symbol) => unspecified
1119 ;;; (module-for-each proc module) => unspecified
1120 ;;; (make-scm-module) => module ; a lazy copy of the symhash module
1121 ;;; (set-current-module module) => unspecified
1122 ;;; (current-module) => #<module...>
1128 ;;; {Printing Modules}
1131 ;; This is how modules are printed. You can re-define it.
1132 ;; (Redefining is actually more complicated than simply redefining
1133 ;; %print-module because that would only change the binding and not
1134 ;; the value stored in the vtable that determines how record are
1137 (define (%print-module mod port) ; unused args: depth length style table)
1139 (display (or (module-kind mod) "module") port)
1140 (let ((name (module-name mod)))
1144 (display name port))))
1146 (display (number->string (object-address mod) 16) port)
1151 ;; A module is characterized by an obarray in which local symbols
1152 ;; are interned, a list of modules, "uses", from which non-local
1153 ;; bindings can be inherited, and an optional lazy-binder which
1154 ;; is a (CLOSURE module symbol) which, as a last resort, can provide
1155 ;; bindings that would otherwise not be found locally in the module.
1157 ;; NOTE: If you change anything here, you also need to change
1158 ;; libguile/modules.h.
1161 (make-record-type 'module
1162 '(obarray uses binder eval-closure transformer name kind
1163 duplicates-handlers duplicates-interface
1164 observers weak-observers observer-id)
1167 ;; make-module &opt size uses binder
1169 ;; Create a new module, perhaps with a particular size of obarray,
1170 ;; initial uses list, or binding procedure.
1175 (define (parse-arg index default)
1176 (if (> (length args) index)
1177 (list-ref args index)
1180 (if (> (length args) 3)
1181 (error "Too many args to make-module." args))
1183 (let ((size (parse-arg 0 31))
1184 (uses (parse-arg 1 '()))
1185 (binder (parse-arg 2 #f)))
1187 (if (not (integer? size))
1188 (error "Illegal size to make-module." size))
1189 (if (not (and (list? uses)
1190 (and-map module? uses)))
1191 (error "Incorrect use list." uses))
1192 (if (and binder (not (procedure? binder)))
1194 "Lazy-binder expected to be a procedure or #f." binder))
1196 (let ((module (module-constructor (make-hash-table size)
1197 uses binder #f #f #f #f #f #f
1199 (make-weak-value-hash-table 31)
1202 ;; We can't pass this as an argument to module-constructor,
1203 ;; because we need it to close over a pointer to the module
1205 (set-module-eval-closure! module (standard-eval-closure module))
1209 (define module-constructor (record-constructor module-type))
1210 (define module-obarray (record-accessor module-type 'obarray))
1211 (define set-module-obarray! (record-modifier module-type 'obarray))
1212 (define module-uses (record-accessor module-type 'uses))
1213 (define set-module-uses! (record-modifier module-type 'uses))
1214 (define module-binder (record-accessor module-type 'binder))
1215 (define set-module-binder! (record-modifier module-type 'binder))
1217 ;; NOTE: This binding is used in libguile/modules.c.
1218 (define module-eval-closure (record-accessor module-type 'eval-closure))
1220 (define module-transformer (record-accessor module-type 'transformer))
1221 (define set-module-transformer! (record-modifier module-type 'transformer))
1222 (define module-name (record-accessor module-type 'name))
1223 (define set-module-name! (record-modifier module-type 'name))
1224 (define module-kind (record-accessor module-type 'kind))
1225 (define set-module-kind! (record-modifier module-type 'kind))
1226 (define module-duplicates-handlers
1227 (record-accessor module-type 'duplicates-handlers))
1228 (define set-module-duplicates-handlers!
1229 (record-modifier module-type 'duplicates-handlers))
1230 (define module-duplicates-interface
1231 (record-accessor module-type 'duplicates-interface))
1232 (define set-module-duplicates-interface!
1233 (record-modifier module-type 'duplicates-interface))
1234 (define module-observers (record-accessor module-type 'observers))
1235 (define set-module-observers! (record-modifier module-type 'observers))
1236 (define module-weak-observers (record-accessor module-type 'weak-observers))
1237 (define module-observer-id (record-accessor module-type 'observer-id))
1238 (define set-module-observer-id! (record-modifier module-type 'observer-id))
1239 (define module? (record-predicate module-type))
1241 (define set-module-eval-closure!
1242 (let ((setter (record-modifier module-type 'eval-closure)))
1243 (lambda (module closure)
1244 (setter module closure)
1245 ;; Make it possible to lookup the module from the environment.
1246 ;; This implementation is correct since an eval closure can belong
1247 ;; to maximally one module.
1248 (set-procedure-property! closure 'module module))))
1252 ;;; {Observer protocol}
1255 (define (module-observe module proc)
1256 (set-module-observers! module (cons proc (module-observers module)))
1259 (define (module-observe-weak module proc)
1260 (let ((id (module-observer-id module)))
1261 (hash-set! (module-weak-observers module) id proc)
1262 (set-module-observer-id! module (+ 1 id))
1265 (define (module-unobserve token)
1266 (let ((module (car token))
1269 (hash-remove! (module-weak-observers module) id)
1270 (set-module-observers! module (delq1! id (module-observers module)))))
1273 (define module-defer-observers #f)
1274 (define module-defer-observers-mutex (make-mutex))
1275 (define module-defer-observers-table (make-hash-table))
1277 (define (module-modified m)
1278 (if module-defer-observers
1279 (hash-set! module-defer-observers-table m #t)
1280 (module-call-observers m)))
1282 ;;; This function can be used to delay calls to observers so that they
1283 ;;; can be called once only in the face of massive updating of modules.
1285 (define (call-with-deferred-observers thunk)
1288 (lock-mutex module-defer-observers-mutex)
1289 (set! module-defer-observers #t))
1292 (set! module-defer-observers #f)
1293 (hash-for-each (lambda (m dummy)
1294 (module-call-observers m))
1295 module-defer-observers-table)
1296 (hash-clear! module-defer-observers-table)
1297 (unlock-mutex module-defer-observers-mutex))))
1299 (define (module-call-observers m)
1300 (for-each (lambda (proc) (proc m)) (module-observers m))
1301 (hash-fold (lambda (id proc res) (proc m)) #f (module-weak-observers m)))
1305 ;;; {Module Searching in General}
1307 ;;; We sometimes want to look for properties of a symbol
1308 ;;; just within the obarray of one module. If the property
1309 ;;; holds, then it is said to hold ``locally'' as in, ``The symbol
1310 ;;; DISPLAY is locally rebound in the module `safe-guile'.''
1313 ;;; Other times, we want to test for a symbol property in the obarray
1314 ;;; of M and, if it is not found there, try each of the modules in the
1315 ;;; uses list of M. This is the normal way of testing for some
1316 ;;; property, so we state these properties without qualification as
1317 ;;; in: ``The symbol 'fnord is interned in module M because it is
1318 ;;; interned locally in module M2 which is a member of the uses list
1322 ;; module-search fn m
1324 ;; return the first non-#f result of FN applied to M and then to
1325 ;; the modules in the uses of m, and so on recursively. If all applications
1326 ;; return #f, then so does this function.
1328 (define (module-search fn m v)
1331 (or (module-search fn (car pos) v)
1334 (loop (module-uses m))))
1337 ;;; {Is a symbol bound in a module?}
1339 ;;; Symbol S in Module M is bound if S is interned in M and if the binding
1340 ;;; of S in M has been set to some well-defined value.
1343 ;; module-locally-bound? module symbol
1345 ;; Is a symbol bound (interned and defined) locally in a given module?
1347 (define (module-locally-bound? m v)
1348 (let ((var (module-local-variable m v)))
1350 (variable-bound? var))))
1352 ;; module-bound? module symbol
1354 ;; Is a symbol bound (interned and defined) anywhere in a given module
1357 (define (module-bound? m v)
1358 (module-search module-locally-bound? m v))
1360 ;;; {Is a symbol interned in a module?}
1362 ;;; Symbol S in Module M is interned if S occurs in
1363 ;;; of S in M has been set to some well-defined value.
1365 ;;; It is possible to intern a symbol in a module without providing
1366 ;;; an initial binding for the corresponding variable. This is done
1368 ;;; (module-add! module symbol (make-undefined-variable))
1370 ;;; In that case, the symbol is interned in the module, but not
1371 ;;; bound there. The unbound symbol shadows any binding for that
1372 ;;; symbol that might otherwise be inherited from a member of the uses list.
1375 (define (module-obarray-get-handle ob key)
1376 ((if (symbol? key) hashq-get-handle hash-get-handle) ob key))
1378 (define (module-obarray-ref ob key)
1379 ((if (symbol? key) hashq-ref hash-ref) ob key))
1381 (define (module-obarray-set! ob key val)
1382 ((if (symbol? key) hashq-set! hash-set!) ob key val))
1384 (define (module-obarray-remove! ob key)
1385 ((if (symbol? key) hashq-remove! hash-remove!) ob key))
1387 ;; module-symbol-locally-interned? module symbol
1389 ;; is a symbol interned (not neccessarily defined) locally in a given module
1390 ;; or its uses? Interned symbols shadow inherited bindings even if
1391 ;; they are not themselves bound to a defined value.
1393 (define (module-symbol-locally-interned? m v)
1394 (not (not (module-obarray-get-handle (module-obarray m) v))))
1396 ;; module-symbol-interned? module symbol
1398 ;; is a symbol interned (not neccessarily defined) anywhere in a given module
1399 ;; or its uses? Interned symbols shadow inherited bindings even if
1400 ;; they are not themselves bound to a defined value.
1402 (define (module-symbol-interned? m v)
1403 (module-search module-symbol-locally-interned? m v))
1406 ;;; {Mapping modules x symbols --> variables}
1409 ;; module-local-variable module symbol
1410 ;; return the local variable associated with a MODULE and SYMBOL.
1412 ;;; This function is very important. It is the only function that can
1413 ;;; return a variable from a module other than the mutators that store
1414 ;;; new variables in modules. Therefore, this function is the location
1415 ;;; of the "lazy binder" hack.
1417 ;;; If symbol is defined in MODULE, and if the definition binds symbol
1418 ;;; to a variable, return that variable object.
1420 ;;; If the symbols is not found at first, but the module has a lazy binder,
1421 ;;; then try the binder.
1423 ;;; If the symbol is not found at all, return #f.
1425 (define (module-local-variable m v)
1428 (let ((b (module-obarray-ref (module-obarray m) v)))
1429 (or (and (variable? b) b)
1430 (and (module-binder m)
1431 ((module-binder m) m v #f)))))
1434 ;; module-variable module symbol
1436 ;; like module-local-variable, except search the uses in the
1437 ;; case V is not found in M.
1439 ;; NOTE: This function is superseded with C code (see modules.c)
1440 ;;; when using the standard eval closure.
1442 (define (module-variable m v)
1443 (module-search module-local-variable m v))
1446 ;;; {Mapping modules x symbols --> bindings}
1448 ;;; These are similar to the mapping to variables, except that the
1449 ;;; variable is dereferenced.
1452 ;; module-symbol-binding module symbol opt-value
1454 ;; return the binding of a variable specified by name within
1455 ;; a given module, signalling an error if the variable is unbound.
1456 ;; If the OPT-VALUE is passed, then instead of signalling an error,
1457 ;; return OPT-VALUE.
1459 (define (module-symbol-local-binding m v . opt-val)
1460 (let ((var (module-local-variable m v)))
1461 (if (and var (variable-bound? var))
1463 (if (not (null? opt-val))
1465 (error "Locally unbound variable." v)))))
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-binding m v . opt-val)
1475 (let ((var (module-variable m v)))
1476 (if (and var (variable-bound? var))
1478 (if (not (null? opt-val))
1480 (error "Unbound variable." v)))))
1485 ;;; {Adding Variables to Modules}
1488 ;; module-make-local-var! module symbol
1490 ;; ensure a variable for V in the local namespace of M.
1491 ;; If no variable was already there, then create a new and uninitialzied
1494 ;; This function is used in modules.c.
1496 (define (module-make-local-var! m v)
1497 (or (let ((b (module-obarray-ref (module-obarray m) v)))
1500 ;; Mark as modified since this function is called when
1501 ;; the standard eval closure defines a binding
1504 (and (module-binder m)
1505 ((module-binder m) m v #t))
1507 (let ((answer (make-undefined-variable)))
1508 (module-add! m v answer)
1511 ;; module-ensure-local-variable! module symbol
1513 ;; Ensure that there is a local variable in MODULE for SYMBOL. If
1514 ;; there is no binding for SYMBOL, create a new uninitialized
1515 ;; variable. Return the local variable.
1517 (define (module-ensure-local-variable! module symbol)
1518 (or (module-local-variable module symbol)
1519 (let ((var (make-undefined-variable)))
1520 (module-add! module symbol var)
1523 ;; module-add! module symbol var
1525 ;; ensure a particular variable for V in the local namespace of M.
1527 (define (module-add! m v var)
1528 (if (not (variable? var))
1529 (error "Bad variable to module-add!" var))
1530 (module-obarray-set! (module-obarray m) v var)
1531 (module-modified m))
1535 ;; make sure that a symbol is undefined in the local namespace of M.
1537 (define (module-remove! m v)
1538 (module-obarray-remove! (module-obarray m) v)
1539 (module-modified m))
1541 (define (module-clear! m)
1542 (hash-clear! (module-obarray m))
1543 (module-modified m))
1545 ;; MODULE-FOR-EACH -- exported
1547 ;; Call PROC on each symbol in MODULE, with arguments of (SYMBOL VARIABLE).
1549 (define (module-for-each proc module)
1550 (hash-for-each proc (module-obarray module)))
1552 (define (module-map proc module)
1553 (hash-map->list proc (module-obarray module)))
1557 ;;; {Low Level Bootstrapping}
1562 ;; A root module uses the pre-modules-obarray as its obarray. This
1563 ;; special obarray accumulates all bindings that have been established
1564 ;; before the module system is fully booted.
1566 ;; (The obarray continues to be used by code that has been closed over
1567 ;; before the module system has been booted.)
1569 (define (make-root-module)
1570 (let ((m (make-module 0)))
1571 (set-module-obarray! m (%get-pre-modules-obarray))
1576 ;; The root interface is a module that uses the same obarray as the
1577 ;; root module. It does not allow new definitions, tho.
1579 (define (make-scm-module)
1580 (let ((m (make-module 0)))
1581 (set-module-obarray! m (%get-pre-modules-obarray))
1582 (set-module-eval-closure! m (standard-interface-eval-closure m))
1588 ;;; {Module-based Loading}
1591 (define (save-module-excursion thunk)
1592 (let ((inner-module (current-module))
1594 (dynamic-wind (lambda ()
1595 (set! outer-module (current-module))
1596 (set-current-module inner-module)
1597 (set! inner-module #f))
1600 (set! inner-module (current-module))
1601 (set-current-module outer-module)
1602 (set! outer-module #f)))))
1604 (define basic-load load)
1606 (define (load-module filename)
1607 (save-module-excursion
1609 (let ((oldname (and (current-load-port)
1610 (port-filename (current-load-port)))))
1611 (basic-load (if (and oldname
1612 (> (string-length filename) 0)
1613 (not (char=? (string-ref filename 0) #\/))
1614 (not (string=? (dirname oldname) ".")))
1615 (string-append (dirname oldname) "/" filename)
1621 ;;; {MODULE-REF -- exported}
1624 ;; Returns the value of a variable called NAME in MODULE or any of its
1625 ;; used modules. If there is no such variable, then if the optional third
1626 ;; argument DEFAULT is present, it is returned; otherwise an error is signaled.
1628 (define (module-ref module name . rest)
1629 (let ((variable (module-variable module name)))
1630 (if (and variable (variable-bound? variable))
1631 (variable-ref variable)
1633 (error "No variable named" name 'in module)
1634 (car rest) ; default value
1637 ;; MODULE-SET! -- exported
1639 ;; Sets the variable called NAME in MODULE (or in a module that MODULE uses)
1640 ;; to VALUE; if there is no such variable, an error is signaled.
1642 (define (module-set! module name value)
1643 (let ((variable (module-variable module name)))
1645 (variable-set! variable value)
1646 (error "No variable named" name 'in module))))
1648 ;; MODULE-DEFINE! -- exported
1650 ;; Sets the variable called NAME in MODULE to VALUE; if there is no such
1651 ;; variable, it is added first.
1653 (define (module-define! module name value)
1654 (let ((variable (module-local-variable module name)))
1657 (variable-set! variable value)
1658 (module-modified module))
1659 (let ((variable (make-variable value)))
1660 (module-add! module name variable)))))
1662 ;; MODULE-DEFINED? -- exported
1664 ;; Return #t iff NAME is defined in MODULE (or in a module that MODULE
1667 (define (module-defined? module name)
1668 (let ((variable (module-variable module name)))
1669 (and variable (variable-bound? variable))))
1671 ;; MODULE-USE! module interface
1673 ;; Add INTERFACE to the list of interfaces used by MODULE.
1675 (define (module-use! module interface)
1676 (set-module-uses! module
1679 (not (equal? (module-name m)
1680 (module-name interface))))
1681 (module-uses module))))
1682 (module-modified module))
1684 ;; MODULE-USE-INTERFACES! module interfaces
1686 ;; Same as MODULE-USE! but add multiple interfaces and check for duplicates
1688 (define (module-use-interfaces! module interfaces)
1689 (let* ((duplicates-handlers? (or (module-duplicates-handlers module)
1690 (default-duplicate-binding-procedures)))
1691 (uses (module-uses module)))
1692 ;; remove duplicates-interface
1693 (set! uses (delq! (module-duplicates-interface module) uses))
1694 ;; remove interfaces to be added
1695 (for-each (lambda (interface)
1698 (not (equal? (module-name m)
1699 (module-name interface))))
1702 ;; add interfaces to use list
1703 (set-module-uses! module uses)
1704 (for-each (lambda (interface)
1705 (and duplicates-handlers?
1706 ;; perform duplicate checking
1707 (process-duplicates module interface))
1708 (set! uses (cons interface uses))
1709 (set-module-uses! module uses))
1711 ;; add duplicates interface
1712 (if (module-duplicates-interface module)
1713 (set-module-uses! module
1714 (cons (module-duplicates-interface module) uses)))
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 (define (module-public-interface m)
1802 (module-ref m '%module-public-interface #f))
1803 (define (set-module-public-interface! m i)
1804 (module-define! m '%module-public-interface i))
1805 (define (set-system-module! m s)
1806 (set-procedure-property! (module-eval-closure m) 'system-module s))
1807 (define the-root-module (make-root-module))
1808 (define the-scm-module (make-scm-module))
1809 (set-module-public-interface! the-root-module the-scm-module)
1810 (set-module-name! the-root-module '(guile))
1811 (set-module-name! the-scm-module '(guile))
1812 (set-module-kind! the-scm-module 'interface)
1813 (for-each set-system-module! (list the-root-module the-scm-module) '(#t #t))
1815 ;; NOTE: This binding is used in libguile/modules.c.
1817 (define (make-modules-in module name)
1821 ((module-ref module (car name) #f)
1822 => (lambda (m) (make-modules-in m (cdr name))))
1823 (else (let ((m (make-module 31)))
1824 (set-module-kind! m 'directory)
1825 (set-module-name! m (append (or (module-name module)
1828 (module-define! module (car name) m)
1829 (make-modules-in m (cdr name)))))))
1831 (define (beautify-user-module! module)
1832 (let ((interface (module-public-interface module)))
1833 (if (or (not interface)
1834 (eq? interface module))
1835 (let ((interface (make-module 31)))
1836 (set-module-name! interface (module-name module))
1837 (set-module-kind! interface 'interface)
1838 (set-module-public-interface! module interface))))
1839 (if (and (not (memq the-scm-module (module-uses module)))
1840 (not (eq? module the-root-module)))
1841 (set-module-uses! module
1842 (append (module-uses module) (list the-scm-module)))))
1844 ;; NOTE: This binding is used in libguile/modules.c.
1846 (define (resolve-module name . maybe-autoload)
1847 (let ((full-name (append '(app modules) name)))
1848 (let ((already (nested-ref the-root-module full-name)))
1850 ;; The module already exists...
1851 (if (and (or (null? maybe-autoload) (car maybe-autoload))
1852 (not (module-public-interface already)))
1853 ;; ...but we are told to load and it doesn't contain source, so
1855 (try-load-module name)
1857 ;; simply return it.
1860 ;; Try to autoload it if we are told so
1861 (if (or (null? maybe-autoload) (car maybe-autoload))
1862 (try-load-module name))
1864 (make-modules-in (current-module) full-name))))))
1866 ;; Cheat. These bindings are needed by modules.c, but we don't want
1867 ;; to move their real definition here because that would be unnatural.
1869 (define try-module-autoload #f)
1870 (define process-define-module #f)
1871 (define process-use-modules #f)
1872 (define module-export! #f)
1874 ;; This boots the module system. All bindings needed by modules.c
1875 ;; must have been defined by now.
1877 (set-current-module the-root-module)
1879 (define app (make-module 31))
1880 (local-define '(app modules) (make-module 31))
1881 (local-define '(app modules guile) the-root-module)
1883 ;; (define-special-value '(app modules new-ws) (lambda () (make-scm-module)))
1885 (define (try-load-module name)
1886 (or (begin-deprecated (try-module-linked name))
1887 (try-module-autoload name)
1888 (begin-deprecated (try-module-dynamic-link name))))
1890 (define (purify-module! module)
1891 "Removes bindings in MODULE which are inherited from the (guile) module."
1892 (let ((use-list (module-uses module)))
1893 (if (and (pair? use-list)
1894 (eq? (car (last-pair use-list)) the-scm-module))
1895 (set-module-uses! module (reverse (cdr (reverse use-list)))))))
1897 ;; Return a module that is an interface to the module designated by
1900 ;; `resolve-interface' takes four keyword arguments:
1902 ;; #:select SELECTION
1904 ;; SELECTION is a list of binding-specs to be imported; A binding-spec
1905 ;; is either a symbol or a pair of symbols (ORIG . SEEN), where ORIG
1906 ;; is the name in the used module and SEEN is the name in the using
1907 ;; module. Note that SEEN is also passed through RENAMER, below. The
1908 ;; default is to select all bindings. If you specify no selection but
1909 ;; a renamer, only the bindings that already exist in the used module
1910 ;; are made available in the interface. Bindings that are added later
1911 ;; are not picked up.
1915 ;; BINDINGS is a list of bindings which should not be imported.
1919 ;; PREFIX is a symbol that will be appended to each exported name.
1920 ;; The default is to not perform any renaming.
1922 ;; #:renamer RENAMER
1924 ;; RENAMER is a procedure that takes a symbol and returns its new
1925 ;; name. The default is not perform any renaming.
1927 ;; Signal "no code for module" error if module name is not resolvable
1928 ;; or its public interface is not available. Signal "no binding"
1929 ;; error if selected binding does not exist in the used module.
1931 (define (resolve-interface name . args)
1933 (define (get-keyword-arg args kw def)
1934 (cond ((memq kw args)
1936 (if (null? (cdr kw-arg))
1937 (error "keyword without value: " kw))
1942 (let* ((select (get-keyword-arg args #:select #f))
1943 (hide (get-keyword-arg args #:hide '()))
1944 (renamer (or (get-keyword-arg args #:renamer #f)
1945 (let ((prefix (get-keyword-arg args #:prefix #f)))
1946 (and prefix (symbol-prefix-proc prefix)))
1948 (module (resolve-module name))
1949 (public-i (and module (module-public-interface module))))
1950 (and (or (not module) (not public-i))
1951 (error "no code for module" name))
1952 (if (and (not select) (null? hide) (eq? renamer identity))
1954 (let ((selection (or select (module-map (lambda (sym var) sym)
1956 (custom-i (make-module 31)))
1957 (set-module-kind! custom-i 'custom-interface)
1958 (set-module-name! custom-i name)
1959 ;; XXX - should use a lazy binder so that changes to the
1960 ;; used module are picked up automatically.
1961 (for-each (lambda (bspec)
1962 (let* ((direct? (symbol? bspec))
1963 (orig (if direct? bspec (car bspec)))
1964 (seen (if direct? bspec (cdr bspec)))
1965 (var (or (module-local-variable public-i orig)
1966 (module-local-variable module orig)
1968 ;; fixme: format manually for now
1970 #f "no binding `~A' in module ~A"
1972 (if (memq orig hide)
1973 (set! hide (delq! orig hide))
1974 (module-add! custom-i
1978 ;; Check that we are not hiding bindings which don't exist
1979 (for-each (lambda (binding)
1980 (if (not (module-local-variable public-i binding))
1983 #f "no binding `~A' to hide in module ~A"
1988 (define (symbol-prefix-proc prefix)
1990 (symbol-append prefix symbol)))
1992 ;; This function is called from "modules.c". If you change it, be
1993 ;; sure to update "modules.c" as well.
1995 (define (process-define-module args)
1996 (let* ((module-id (car args))
1997 (module (resolve-module module-id #f))
1999 (unrecognized (lambda (arg)
2000 (error "unrecognized define-module argument" arg))))
2001 (beautify-user-module! module)
2002 (let loop ((kws kws)
2003 (reversed-interfaces '())
2008 (call-with-deferred-observers
2010 (module-use-interfaces! module (reverse reversed-interfaces))
2011 (module-export! module exports)
2012 (module-replace! module replacements)
2013 (module-re-export! module re-exports)))
2015 ((#:use-module #:use-syntax)
2016 (or (pair? (cdr kws))
2018 (let* ((interface-args (cadr kws))
2019 (interface (apply resolve-interface interface-args)))
2020 (and (eq? (car kws) #:use-syntax)
2021 (or (symbol? (caar interface-args))
2022 (error "invalid module name for use-syntax"
2023 (car interface-args)))
2024 (set-module-transformer!
2026 (module-ref interface
2027 (car (last-pair (car interface-args)))
2030 (cons interface reversed-interfaces)
2035 (or (and (pair? (cdr kws)) (pair? (cddr kws)))
2038 (cons (make-autoload-interface module
2041 reversed-interfaces)
2046 (set-system-module! module #t)
2047 (loop (cdr kws) reversed-interfaces exports re-exports replacements))
2049 (purify-module! module)
2050 (loop (cdr kws) reversed-interfaces exports re-exports replacements))
2052 (if (not (pair? (cdr kws)))
2054 (set-module-duplicates-handlers!
2056 (lookup-duplicates-handlers (cadr kws)))
2057 (loop (cddr kws) reversed-interfaces exports re-exports replacements))
2058 ((#:export #:export-syntax)
2059 (or (pair? (cdr kws))
2063 (append (cadr kws) exports)
2066 ((#:re-export #:re-export-syntax)
2067 (or (pair? (cdr kws))
2072 (append (cadr kws) re-exports)
2074 ((#:replace #:replace-syntax)
2075 (or (pair? (cdr kws))
2081 (append (cadr kws) replacements)))
2083 (unrecognized kws)))))
2084 (run-hook module-defined-hook module)
2087 ;; `module-defined-hook' is a hook that is run whenever a new module
2088 ;; is defined. Its members are called with one argument, the new
2090 (define module-defined-hook (make-hook 1))
2097 (define (make-autoload-interface module name bindings)
2098 (let ((b (lambda (a sym definep)
2099 (and (memq sym bindings)
2100 (let ((i (module-public-interface (resolve-module name))))
2102 (error "missing interface for module" name))
2103 ;; Replace autoload-interface with interface
2104 (set-car! (memq a (module-uses module)) i)
2105 (module-local-variable i sym))))))
2106 (module-constructor (make-hash-table 0) '() b #f #f name 'autoload #f #f
2107 '() (make-weak-value-hash-table 31) 0)))
2109 ;;; {Compiled module}
2111 (define load-compiled #f)
2115 ;;; {Autoloading modules}
2118 (define autoloads-in-progress '())
2120 ;; This function is called from "modules.c". If you change it, be
2121 ;; sure to update "modules.c" as well.
2123 (define (try-module-autoload module-name)
2124 (let* ((reverse-name (reverse module-name))
2125 (name (symbol->string (car reverse-name)))
2126 (dir-hint-module-name (reverse (cdr reverse-name)))
2127 (dir-hint (apply string-append
2129 (string-append (symbol->string elt) "/"))
2130 dir-hint-module-name))))
2131 (resolve-module dir-hint-module-name #f)
2132 (and (not (autoload-done-or-in-progress? dir-hint name))
2134 (define (load-file proc file)
2135 (save-module-excursion (lambda () (proc file)))
2138 (lambda () (autoload-in-progress! dir-hint name))
2140 (let ((file (in-vicinity dir-hint name)))
2141 (cond ((and load-compiled
2142 (%search-load-path (string-append file ".go")))
2144 (load-file load-compiled full)))
2145 ((%search-load-path file)
2147 (load-file primitive-load full))))))
2148 (lambda () (set-autoloaded! dir-hint name didit)))
2153 ;;; {Dynamic linking of modules}
2156 (define autoloads-done '((guile . guile)))
2158 (define (autoload-done-or-in-progress? p m)
2159 (let ((n (cons p m)))
2160 (->bool (or (member n autoloads-done)
2161 (member n autoloads-in-progress)))))
2163 (define (autoload-done! p m)
2164 (let ((n (cons p m)))
2165 (set! autoloads-in-progress
2166 (delete! n autoloads-in-progress))
2167 (or (member n autoloads-done)
2168 (set! autoloads-done (cons n autoloads-done)))))
2170 (define (autoload-in-progress! p m)
2171 (let ((n (cons p m)))
2172 (set! autoloads-done
2173 (delete! n autoloads-done))
2174 (set! autoloads-in-progress (cons n autoloads-in-progress))))
2176 (define (set-autoloaded! p m done?)
2178 (autoload-done! p m)
2179 (let ((n (cons p m)))
2180 (set! autoloads-done (delete! n autoloads-done))
2181 (set! autoloads-in-progress (delete! n autoloads-in-progress)))))
2185 ;;; {Run-time options}
2188 (define define-option-interface
2189 (let* ((option-name car)
2191 (option-documentation caddr)
2193 (print-option (lambda (option)
2194 (display (option-name option))
2195 (if (< (string-length
2196 (symbol->string (option-name option)))
2200 (display (option-value option))
2202 (display (option-documentation option))
2205 ;; Below follow the macros defining the run-time option interfaces.
2207 (make-options (lambda (interface)
2209 (cond ((null? args) (,interface))
2211 (,interface (car args)) (,interface))
2212 (else (for-each ,print-option
2213 (,interface #t)))))))
2215 (make-enable (lambda (interface)
2217 (,interface (append flags (,interface)))
2220 (make-disable (lambda (interface)
2222 (let ((options (,interface)))
2223 (for-each (lambda (flag)
2224 (set! options (delq! flag options)))
2226 (,interface options)
2228 (procedure->memoizing-macro
2230 (let* ((option-group (cadr exp))
2231 (interface (car option-group))
2232 (options/enable/disable (cadr option-group)))
2234 (define ,(car options/enable/disable)
2235 ,(make-options interface))
2236 (define ,(cadr options/enable/disable)
2237 ,(make-enable interface))
2238 (define ,(caddr options/enable/disable)
2239 ,(make-disable interface))
2240 (defmacro ,(caaddr option-group) (opt val)
2241 `(,,(car options/enable/disable)
2242 (append (,,(car options/enable/disable))
2243 (list ',opt ,val))))))))))
2245 (define-option-interface
2246 (eval-options-interface
2247 (eval-options eval-enable eval-disable)
2250 (define-option-interface
2251 (debug-options-interface
2252 (debug-options debug-enable debug-disable)
2255 (define-option-interface
2256 (evaluator-traps-interface
2257 (traps trap-enable trap-disable)
2260 (define-option-interface
2261 (read-options-interface
2262 (read-options read-enable read-disable)
2265 (define-option-interface
2266 (print-options-interface
2267 (print-options print-enable print-disable)
2275 (define (repl read evaler print)
2276 (let loop ((source (read (current-input-port))))
2277 (print (evaler source))
2278 (loop (read (current-input-port)))))
2280 ;; A provisional repl that acts like the SCM repl:
2282 (define scm-repl-silent #f)
2283 (define (assert-repl-silence v) (set! scm-repl-silent v))
2285 (define *unspecified* (if #f #f))
2286 (define (unspecified? v) (eq? v *unspecified*))
2288 (define scm-repl-print-unspecified #f)
2289 (define (assert-repl-print-unspecified v) (set! scm-repl-print-unspecified v))
2291 (define scm-repl-verbose #f)
2292 (define (assert-repl-verbosity v) (set! scm-repl-verbose v))
2294 (define scm-repl-prompt "guile> ")
2296 (define (set-repl-prompt! v) (set! scm-repl-prompt v))
2298 (define (default-lazy-handler key . args)
2299 (save-stack lazy-handler-dispatch)
2300 (apply throw key args))
2302 (define (lazy-handler-dispatch key . args)
2303 (apply default-lazy-handler key args))
2305 (define abort-hook (make-hook))
2307 ;; these definitions are used if running a script.
2308 ;; otherwise redefined in error-catching-loop.
2309 (define (set-batch-mode?! arg) #t)
2310 (define (batch-mode?) #t)
2312 (define (error-catching-loop thunk)
2315 (define (loop first)
2322 (call-with-unblocked-asyncs
2328 ;; This line is needed because mark
2329 ;; doesn't do closures quite right.
2330 ;; Unreferenced locals should be
2334 (let loop ((v (thunk)))
2338 ;; Note that having just
2339 ;; `lazy-handler-dispatch' here is
2340 ;; connected with the mechanism that
2341 ;; produces a nice backtrace upon
2342 ;; error. If, for example, this is
2343 ;; replaced with (lambda args (apply
2344 ;; lazy-handler-dispatch args)), the
2345 ;; stack cutting (in save-stack)
2346 ;; goes wrong and ends up saving no
2347 ;; stack at all, so there is no
2349 lazy-handler-dispatch))
2351 (lambda (key . args)
2358 (apply throw 'switch-repl args))
2361 ;; This is one of the closures that require
2362 ;; (set! first #f) above
2365 (run-hook abort-hook)
2366 (force-output (current-output-port))
2367 (display "ABORT: " (current-error-port))
2368 (write args (current-error-port))
2369 (newline (current-error-port))
2373 (not has-shown-debugger-hint?)
2374 (not (memq 'backtrace
2375 (debug-options-interface)))
2376 (stack? (fluid-ref the-last-stack)))
2378 (newline (current-error-port))
2380 "Type \"(backtrace)\" to get more information or \"(debug)\" to enter the debugger.\n"
2381 (current-error-port))
2382 (set! has-shown-debugger-hint? #t)))
2383 (force-output (current-error-port)))
2385 (primitive-exit 1)))
2386 (set! stack-saved? #f)))
2389 ;; This is the other cons-leak closure...
2391 (cond ((= (length args) 4)
2392 (apply handle-system-error key args))
2394 (apply bad-throw key args))))))))))
2395 (if next (loop next) status)))
2396 (set! set-batch-mode?! (lambda (arg)
2398 (set! interactive #f)
2401 (error "sorry, not implemented")))))
2402 (set! batch-mode? (lambda () (not interactive)))
2403 (call-with-blocked-asyncs
2404 (lambda () (loop (lambda () #t))))))
2406 ;;(define the-last-stack (make-fluid)) Defined by scm_init_backtrace ()
2407 (define before-signal-stack (make-fluid))
2408 (define stack-saved? #f)
2410 (define (save-stack . narrowing)
2412 (cond ((not (memq 'debug (debug-options-interface)))
2413 (fluid-set! the-last-stack #f)
2414 (set! stack-saved? #t))
2420 (apply make-stack #t save-stack primitive-eval #t 0 narrowing))
2422 (apply make-stack #t save-stack 0 #t 0 narrowing))
2424 (apply make-stack #t save-stack tk-stack-mark #t 0 narrowing))
2426 (apply make-stack #t save-stack 0 1 narrowing))
2428 (let ((id (stack-id #t)))
2429 (and (procedure? id)
2430 (apply make-stack #t save-stack id #t 0 narrowing))))))
2431 (set! stack-saved? #t)))))
2433 (define before-error-hook (make-hook))
2434 (define after-error-hook (make-hook))
2435 (define before-backtrace-hook (make-hook))
2436 (define after-backtrace-hook (make-hook))
2438 (define has-shown-debugger-hint? #f)
2440 (define (handle-system-error key . args)
2441 (let ((cep (current-error-port)))
2442 (cond ((not (stack? (fluid-ref the-last-stack))))
2443 ((memq 'backtrace (debug-options-interface))
2444 (let ((highlights (if (or (eq? key 'wrong-type-arg)
2445 (eq? key 'out-of-range))
2448 (run-hook before-backtrace-hook)
2450 (display "Backtrace:\n")
2451 (display-backtrace (fluid-ref the-last-stack) cep
2454 (run-hook after-backtrace-hook))))
2455 (run-hook before-error-hook)
2456 (apply display-error (fluid-ref the-last-stack) cep args)
2457 (run-hook after-error-hook)
2459 (throw 'abort key)))
2461 (define (quit . args)
2462 (apply throw 'quit args))
2466 ;;(define has-shown-backtrace-hint? #f) Defined by scm_init_backtrace ()
2468 ;; Replaced by C code:
2469 ;;(define (backtrace)
2470 ;; (if (fluid-ref the-last-stack)
2473 ;; (display-backtrace (fluid-ref the-last-stack) (current-output-port))
2475 ;; (if (and (not has-shown-backtrace-hint?)
2476 ;; (not (memq 'backtrace (debug-options-interface))))
2479 ;;"Type \"(debug-enable 'backtrace)\" if you would like a backtrace
2480 ;;automatically if an error occurs in the future.\n")
2481 ;; (set! has-shown-backtrace-hint? #t))))
2482 ;; (display "No backtrace available.\n")))
2484 (define (error-catching-repl r e p)
2485 (error-catching-loop
2487 (call-with-values (lambda () (e (r)))
2488 (lambda the-values (for-each p the-values))))))
2490 (define (gc-run-time)
2491 (cdr (assq 'gc-time-taken (gc-stats))))
2493 (define before-read-hook (make-hook))
2494 (define after-read-hook (make-hook))
2495 (define before-eval-hook (make-hook 1))
2496 (define after-eval-hook (make-hook 1))
2497 (define before-print-hook (make-hook 1))
2498 (define after-print-hook (make-hook 1))
2500 ;;; The default repl-reader function. We may override this if we've
2501 ;;; the readline library.
2506 (run-hook before-read-hook)
2507 (read (current-input-port))))
2509 (define (scm-style-repl)
2514 (repl-report-start-timing (lambda ()
2515 (set! start-gc-rt (gc-run-time))
2516 (set! start-rt (get-internal-run-time))))
2517 (repl-report (lambda ()
2519 (display (inexact->exact
2520 (* 1000 (/ (- (get-internal-run-time) start-rt)
2521 internal-time-units-per-second))))
2523 (display (inexact->exact
2524 (* 1000 (/ (- (gc-run-time) start-gc-rt)
2525 internal-time-units-per-second))))
2526 (display " msec in gc)\n")))
2528 (consume-trailing-whitespace
2530 (let ((ch (peek-char)))
2533 ((or (char=? ch #\space) (char=? ch #\tab))
2535 (consume-trailing-whitespace))
2536 ((char=? ch #\newline)
2540 (let ((prompt (cond ((string? scm-repl-prompt)
2542 ((thunk? scm-repl-prompt)
2544 (scm-repl-prompt "> ")
2546 (repl-reader prompt))))
2548 ;; As described in R4RS, the READ procedure updates the
2549 ;; port to point to the first character past the end of
2550 ;; the external representation of the object. This
2551 ;; means that it doesn't consume the newline typically
2552 ;; found after an expression. This means that, when
2553 ;; debugging Guile with GDB, GDB gets the newline, which
2554 ;; it often interprets as a "continue" command, making
2555 ;; breakpoints kind of useless. So, consume any
2556 ;; trailing newline here, as well as any whitespace
2558 ;; But not if EOF, for control-D.
2559 (if (not (eof-object? val))
2560 (consume-trailing-whitespace))
2561 (run-hook after-read-hook)
2562 (if (eof-object? val)
2564 (repl-report-start-timing)
2565 (if scm-repl-verbose
2568 (display ";;; EOF -- quitting")
2573 (-eval (lambda (sourc)
2574 (repl-report-start-timing)
2575 (run-hook before-eval-hook sourc)
2576 (let ((val (start-stack 'repl-stack
2577 ;; If you change this procedure
2578 ;; (primitive-eval), please also
2579 ;; modify the repl-stack case in
2580 ;; save-stack so that stack cutting
2581 ;; continues to work.
2582 (primitive-eval sourc))))
2583 (run-hook after-eval-hook sourc)
2587 (-print (let ((maybe-print (lambda (result)
2588 (if (or scm-repl-print-unspecified
2589 (not (unspecified? result)))
2594 (if (not scm-repl-silent)
2596 (run-hook before-print-hook result)
2597 (maybe-print result)
2598 (run-hook after-print-hook result)
2599 (if scm-repl-verbose
2603 (-quit (lambda (args)
2604 (if scm-repl-verbose
2606 (display ";;; QUIT executed, repl exitting")
2612 (if scm-repl-verbose
2614 (display ";;; ABORT executed.")
2617 (repl -read -eval -print))))
2619 (let ((status (error-catching-repl -read
2627 ;;; {IOTA functions: generating lists of numbers}
2631 (let loop ((count (1- n)) (result '()))
2632 (if (< count 0) result
2633 (loop (1- count) (cons count result)))))
2639 ;;; Similar to `begin' but returns a list of the results of all constituent
2640 ;;; forms instead of the result of the last form.
2641 ;;; (The definition relies on the current left-to-right
2642 ;;; order of evaluation of operands in applications.)
2645 (defmacro collect forms
2653 ;; with-fluids is a convenience wrapper for the builtin procedure
2654 ;; `with-fluids*'. The syntax is just like `let':
2656 ;; (with-fluids ((fluid val)
2660 (defmacro with-fluids (bindings . body)
2661 (let ((fluids (map car bindings))
2662 (values (map cadr bindings)))
2663 (if (and (= (length fluids) 1) (= (length values) 1))
2664 `(with-fluid* ,(car fluids) ,(car values) (lambda () ,@body))
2665 `(with-fluids* (list ,@fluids) (list ,@values)
2666 (lambda () ,@body)))))
2673 ;; actually....hobbit might be able to hack these with a little
2677 (define (primitive-macro? m)
2679 (not (macro-transformer m))))
2681 (defmacro define-macro (first . rest)
2682 (let ((name (if (symbol? first) first (car first)))
2686 `(lambda ,(cdr first) ,@rest))))
2689 (define ,name (defmacro:transformer ,transformer)))
2691 (error "define-macro can only be used at the top level")))))
2694 (defmacro define-syntax-macro (first . rest)
2695 (let ((name (if (symbol? first) first (car first)))
2699 `(lambda ,(cdr first) ,@rest))))
2702 (define ,name (defmacro:syntax-transformer ,transformer)))
2704 (error "define-syntax-macro can only be used at the top level")))))
2710 ;;; with `continue' and `break'.
2713 ;; The inner `do' loop avoids re-establishing a catch every iteration,
2714 ;; that's only necessary if continue is actually used. A new key is
2715 ;; generated every time, so break and continue apply to their originating
2716 ;; `while' even when recursing. `while-helper' is an easy way to keep the
2717 ;; `key' binding away from the cond and body code.
2719 (define-macro (while cond . body)
2720 (define (while-helper proc)
2721 (do ((key (make-symbol "while-key")))
2724 (proc (lambda () (throw key #t))
2725 (lambda () (throw key #f))))
2726 (lambda (key arg) arg)))))
2727 `(,while-helper (,lambda (break continue)
2736 ;;; {Module System Macros}
2739 ;; Return a list of expressions that evaluate to the appropriate
2740 ;; arguments for resolve-interface according to SPEC.
2742 (define (compile-interface-spec spec)
2743 (define (make-keyarg sym key quote?)
2744 (cond ((or (memq sym spec)
2748 (list key (list 'quote (cadr rest)))
2749 (list key (cadr rest)))))
2752 (define (map-apply func list)
2753 (map (lambda (args) (apply func args)) list))
2756 '((:select #:select #t)
2758 (:prefix #:prefix #t)
2759 (:renamer #:renamer #f)))
2760 (if (not (pair? (car spec)))
2763 ,@(apply append (map-apply make-keyarg keys)))))
2765 (define (keyword-like-symbol->keyword sym)
2766 (symbol->keyword (string->symbol (substring (symbol->string sym) 1))))
2768 (define (compile-define-module-args args)
2769 ;; Just quote everything except #:use-module and #:use-syntax. We
2770 ;; need to know about all arguments regardless since we want to turn
2771 ;; symbols that look like keywords into real keywords, and the
2772 ;; keyword args in a define-module form are not regular
2773 ;; (i.e. no-backtrace doesn't take a value).
2774 (let loop ((compiled-args `((quote ,(car args))))
2777 (reverse! compiled-args))
2778 ;; symbol in keyword position
2779 ((symbol? (car args))
2781 (cons (keyword-like-symbol->keyword (car args)) (cdr args))))
2782 ((memq (car args) '(#:no-backtrace #:pure))
2783 (loop (cons (car args) compiled-args)
2786 (error "keyword without value:" (car args)))
2787 ((memq (car args) '(#:use-module #:use-syntax))
2788 (loop (cons* `(list ,@(compile-interface-spec (cadr args)))
2792 ((eq? (car args) #:autoload)
2793 (loop (cons* `(quote ,(caddr args))
2794 `(quote ,(cadr args))
2799 (loop (cons* `(quote ,(cadr args))
2804 (defmacro define-module args
2807 (let ((m (process-define-module
2808 (list ,@(compile-define-module-args args)))))
2809 (set-current-module m)
2812 (error "define-module can only be used at the top level"))))
2814 ;; The guts of the use-modules macro. Add the interfaces of the named
2815 ;; modules to the use-list of the current module, in order.
2817 ;; This function is called by "modules.c". If you change it, be sure
2818 ;; to change scm_c_use_module as well.
2820 (define (process-use-modules module-interface-args)
2821 (let ((interfaces (map (lambda (mif-args)
2822 (or (apply resolve-interface mif-args)
2823 (error "no such module" mif-args)))
2824 module-interface-args)))
2825 (call-with-deferred-observers
2827 (module-use-interfaces! (current-module) interfaces)))))
2829 (defmacro use-modules modules
2832 (process-use-modules
2833 (list ,@(map (lambda (m)
2834 `(list ,@(compile-interface-spec m)))
2838 (error "use-modules can only be used at the top level"))))
2840 (defmacro use-syntax (spec)
2844 `((process-use-modules (list
2845 (list ,@(compile-interface-spec spec))))
2846 (set-module-transformer! (current-module)
2847 ,(car (last-pair spec))))
2848 `((set-module-transformer! (current-module) ,spec)))
2851 (error "use-syntax can only be used at the top level"))))
2853 ;; Dirk:FIXME:: This incorrect (according to R5RS) syntax needs to be changed
2854 ;; as soon as guile supports hygienic macros.
2855 (define define-private define)
2857 (defmacro define-public args
2859 (error "bad syntax" (list 'define-public args)))
2860 (define (defined-name n)
2863 ((pair? n) (defined-name (car n)))
2869 (let ((name (defined-name (car args))))
2871 (define-private ,@args)
2872 (eval-case ((load-toplevel) (export ,name))))))))
2874 (defmacro defmacro-public args
2876 (error "bad syntax" (list 'defmacro-public args)))
2877 (define (defined-name n)
2885 (let ((name (defined-name (car args))))
2887 (eval-case ((load-toplevel) (export-syntax ,name)))
2888 (defmacro ,@args))))))
2890 ;; Export a local variable
2892 ;; This function is called from "modules.c". If you change it, be
2893 ;; sure to update "modules.c" as well.
2895 (define (module-export! m names)
2896 (let ((public-i (module-public-interface m)))
2897 (for-each (lambda (name)
2898 (let ((var (module-ensure-local-variable! m name)))
2899 (module-add! public-i name var)))
2902 (define (module-replace! m names)
2903 (let ((public-i (module-public-interface m)))
2904 (for-each (lambda (name)
2905 (let ((var (module-ensure-local-variable! m name)))
2906 (set-object-property! var 'replace #t)
2907 (module-add! public-i name var)))
2910 ;; Re-export a imported variable
2912 (define (module-re-export! m names)
2913 (let ((public-i (module-public-interface m)))
2914 (for-each (lambda (name)
2915 (let ((var (module-variable m name)))
2917 (error "Undefined variable:" name))
2918 ((eq? var (module-local-variable m name))
2919 (error "re-exporting local variable:" name))
2921 (module-add! public-i name var)))))
2924 (defmacro export names
2927 (call-with-deferred-observers
2929 (module-export! (current-module) ',names))))
2931 (error "export can only be used at the top level"))))
2933 (defmacro re-export names
2936 (call-with-deferred-observers
2938 (module-re-export! (current-module) ',names))))
2940 (error "re-export can only be used at the top level"))))
2942 (defmacro export-syntax names
2945 (defmacro re-export-syntax names
2946 `(re-export ,@names))
2948 (define load load-module)
2950 ;; The following macro allows one to write, for example,
2952 ;; (@ (ice-9 pretty-print) pretty-print)
2954 ;; to refer directly to the pretty-print variable in module (ice-9
2955 ;; pretty-print). It works by looking up the variable and inserting
2956 ;; it directly into the code. This is understood by the evaluator.
2957 ;; Indeed, all references to global variables are memoized into such
2958 ;; variable objects.
2960 (define-macro (@ mod-name var-name)
2961 (let ((var (module-variable (resolve-interface mod-name) var-name)))
2963 (error "no such public variable" (list '@ mod-name var-name)))
2966 ;; The '@@' macro is like '@' but it can also access bindings that
2967 ;; have not been explicitely exported.
2969 (define-macro (@@ mod-name var-name)
2970 (let ((var (module-variable (resolve-module mod-name) var-name)))
2972 (error "no such variable" (list '@@ mod-name var-name)))
2980 (define make-mutable-parameter
2981 (let ((make (lambda (fluid converter)
2985 (fluid-set! fluid (converter (car args))))))))
2986 (lambda (init . converter)
2987 (let ((fluid (make-fluid))
2988 (converter (if (null? converter)
2991 (fluid-set! fluid (converter init))
2992 (make fluid converter)))))
2996 ;;; {Handling of duplicate imported bindings}
2999 ;; Duplicate handlers take the following arguments:
3001 ;; module importing module
3002 ;; name conflicting name
3003 ;; int1 old interface where name occurs
3004 ;; val1 value of binding in old interface
3005 ;; int2 new interface where name occurs
3006 ;; val2 value of binding in new interface
3007 ;; var previous resolution or #f
3008 ;; val value of previous resolution
3010 ;; A duplicate handler can take three alternative actions:
3012 ;; 1. return #f => leave responsibility to next handler
3013 ;; 2. exit with an error
3014 ;; 3. return a variable resolving the conflict
3017 (define duplicate-handlers
3018 (let ((m (make-module 7)))
3020 (define (check module name int1 val1 int2 val2 var val)
3021 (scm-error 'misc-error
3023 "~A: `~A' imported from both ~A and ~A"
3024 (list (module-name module)
3030 (define (warn module name int1 val1 int2 val2 var val)
3032 "WARNING: ~A: `~A' imported from both ~A and ~A\n"
3033 (module-name module)
3039 (define (replace module name int1 val1 int2 val2 var val)
3040 (let ((old (or (and var (object-property var 'replace) var)
3041 (module-variable int1 name)))
3042 (new (module-variable int2 name)))
3043 (if (object-property old 'replace)
3044 (and (or (eq? old new)
3045 (not (object-property new 'replace)))
3047 (and (object-property new 'replace)
3050 (define (warn-override-core module name int1 val1 int2 val2 var val)
3051 (and (eq? int1 the-scm-module)
3054 "WARNING: ~A: imported module ~A overrides core binding `~A'\n"
3055 (module-name module)
3058 (module-local-variable int2 name))))
3060 (define (first module name int1 val1 int2 val2 var val)
3061 (or var (module-local-variable int1 name)))
3063 (define (last module name int1 val1 int2 val2 var val)
3064 (module-local-variable int2 name))
3066 (define (noop module name int1 val1 int2 val2 var val)
3069 (set-module-name! m 'duplicate-handlers)
3070 (set-module-kind! m 'interface)
3071 (module-define! m 'check check)
3072 (module-define! m 'warn warn)
3073 (module-define! m 'replace replace)
3074 (module-define! m 'warn-override-core warn-override-core)
3075 (module-define! m 'first first)
3076 (module-define! m 'last last)
3077 (module-define! m 'merge-generics noop)
3078 (module-define! m 'merge-accessors noop)
3081 (define (lookup-duplicates-handlers handler-names)
3083 (map (lambda (handler-name)
3084 (or (module-symbol-local-binding
3085 duplicate-handlers handler-name #f)
3086 (error "invalid duplicate handler name:"
3088 (if (list? handler-names)
3090 (list handler-names)))))
3092 (define default-duplicate-binding-procedures
3093 (make-mutable-parameter #f))
3095 (define default-duplicate-binding-handler
3096 (make-mutable-parameter '(replace warn-override-core warn last)
3097 (lambda (handler-names)
3098 (default-duplicate-binding-procedures
3099 (lookup-duplicates-handlers handler-names))
3102 (define (make-duplicates-interface)
3103 (let ((m (make-module)))
3104 (set-module-kind! m 'custom-interface)
3105 (set-module-name! m 'duplicates)
3108 (define (process-duplicates module interface)
3109 (let* ((duplicates-handlers (or (module-duplicates-handlers module)
3110 (default-duplicate-binding-procedures)))
3111 (duplicates-interface (module-duplicates-interface module)))
3114 (cond ((module-import-interface module name)
3116 (lambda (prev-interface)
3117 (let ((var1 (module-local-variable prev-interface name))
3118 (var2 (module-local-variable interface name)))
3119 (if (not (eq? var1 var2))
3121 (if (not duplicates-interface)
3123 (set! duplicates-interface
3124 (make-duplicates-interface))
3125 (set-module-duplicates-interface!
3127 duplicates-interface)))
3128 (let* ((var (module-local-variable duplicates-interface
3131 (variable-bound? var)
3132 (variable-ref var))))
3133 (let loop ((duplicates-handlers duplicates-handlers))
3134 (cond ((null? duplicates-handlers))
3135 (((car duplicates-handlers)
3139 (and (variable-bound? var1)
3140 (variable-ref var1))
3142 (and (variable-bound? var2)
3143 (variable-ref var2))
3148 (module-add! duplicates-interface name var)))
3150 (loop (cdr duplicates-handlers)))))))))))))
3155 ;;; {`cond-expand' for SRFI-0 support.}
3157 ;;; This syntactic form expands into different commands or
3158 ;;; definitions, depending on the features provided by the Scheme
3164 ;;; --> (cond-expand <cond-expand-clause>+)
3165 ;;; | (cond-expand <cond-expand-clause>* (else <command-or-definition>))
3166 ;;; <cond-expand-clause>
3167 ;;; --> (<feature-requirement> <command-or-definition>*)
3168 ;;; <feature-requirement>
3169 ;;; --> <feature-identifier>
3170 ;;; | (and <feature-requirement>*)
3171 ;;; | (or <feature-requirement>*)
3172 ;;; | (not <feature-requirement>)
3173 ;;; <feature-identifier>
3174 ;;; --> <a symbol which is the name or alias of a SRFI>
3176 ;;; Additionally, this implementation provides the
3177 ;;; <feature-identifier>s `guile' and `r5rs', so that programs can
3178 ;;; determine the implementation type and the supported standard.
3180 ;;; Currently, the following feature identifiers are supported:
3182 ;;; guile r5rs srfi-0 srfi-4 srfi-6 srfi-13 srfi-14
3184 ;;; Remember to update the features list when adding more SRFIs.
3187 (define %cond-expand-features
3188 ;; Adjust the above comment when changing this.
3191 srfi-0 ;; cond-expand itself
3192 srfi-4 ;; homogenous numeric vectors
3193 srfi-6 ;; open-input-string etc, in the guile core
3194 srfi-13 ;; string library
3195 srfi-14 ;; character sets
3198 ;; This table maps module public interfaces to the list of features.
3200 (define %cond-expand-table (make-hash-table 31))
3202 ;; Add one or more features to the `cond-expand' feature list of the
3205 (define (cond-expand-provide module features)
3206 (let ((mod (module-public-interface module)))
3208 (hashq-set! %cond-expand-table mod
3209 (append (hashq-ref %cond-expand-table mod '())
3213 (procedure->memoizing-macro
3215 (let ((clauses (cdr exp))
3216 (syntax-error (lambda (cl)
3217 (error "invalid clause in `cond-expand'" cl))))
3223 (or (memq clause %cond-expand-features)
3224 (let lp ((uses (module-uses (env-module env))))
3227 (hashq-ref %cond-expand-table
3233 ((eq? 'and (car clause))
3234 (let lp ((l (cdr clause)))
3238 (and (test-clause (car l)) (lp (cdr l))))
3240 (syntax-error clause)))))
3241 ((eq? 'or (car clause))
3242 (let lp ((l (cdr clause)))
3246 (or (test-clause (car l)) (lp (cdr l))))
3248 (syntax-error clause)))))
3249 ((eq? 'not (car clause))
3250 (cond ((not (pair? (cdr clause)))
3251 (syntax-error clause))
3252 ((pair? (cddr clause))
3253 ((syntax-error clause))))
3254 (not (test-clause (cadr clause))))
3256 (syntax-error clause))))
3258 (syntax-error clause))))))
3259 (let lp ((c clauses))
3262 (error "Unfulfilled `cond-expand'"))
3265 ((not (pair? (car c)))
3266 (syntax-error (car c)))
3267 ((test-clause (caar c))
3268 `(begin ,@(cdar c)))
3269 ((eq? (caar c) 'else)
3272 `(begin ,@(cdar c)))
3274 (lp (cdr c))))))))))
3276 ;; This procedure gets called from the startup code with a list of
3277 ;; numbers, which are the numbers of the SRFIs to be loaded on startup.
3279 (define (use-srfis srfis)
3282 (let* ((srfi (string->symbol
3283 (string-append "srfi-" (number->string (car s)))))
3284 (mod-i (resolve-interface (list 'srfi srfi))))
3285 (module-use! (current-module) mod-i)
3290 ;;; {Load emacs interface support if emacs option is given.}
3293 (define (named-module-use! user usee)
3294 (module-use! (resolve-module user) (resolve-interface usee)))
3296 (define (load-emacs-interface)
3297 (and (provided? 'debug-extensions)
3298 (debug-enable 'backtrace))
3299 (named-module-use! '(guile-user) '(ice-9 emacs)))
3303 (define using-readline?
3304 (let ((using-readline? (make-fluid)))
3305 (make-procedure-with-setter
3306 (lambda () (fluid-ref using-readline?))
3307 (lambda (v) (fluid-set! using-readline? v)))))
3310 (let ((guile-user-module (resolve-module '(guile-user))))
3312 ;; Load emacs interface support if emacs option is given.
3313 (if (and (module-defined? guile-user-module 'use-emacs-interface)
3314 (module-ref guile-user-module 'use-emacs-interface))
3315 (load-emacs-interface))
3317 ;; Use some convenient modules (in reverse order)
3319 (if (provided? 'regex)
3320 (module-use! guile-user-module (resolve-interface '(ice-9 regex))))
3321 (if (provided? 'threads)
3322 (module-use! guile-user-module (resolve-interface '(ice-9 threads))))
3323 ;; load debugger on demand
3324 (module-use! guile-user-module
3325 (make-autoload-interface guile-user-module
3326 '(ice-9 debugger) '(debug)))
3327 (module-use! guile-user-module (resolve-interface '(ice-9 session)))
3328 (module-use! guile-user-module (resolve-interface '(ice-9 debug)))
3329 ;; so that builtin bindings will be checked first
3330 (module-use! guile-user-module (resolve-interface '(ice-9 r5rs)))
3331 (module-use! guile-user-module (resolve-interface '(guile)))
3333 (set-current-module guile-user-module)
3335 (let ((old-handlers #f)
3336 (signals (if (provided? 'posix)
3337 `((,SIGINT . "User interrupt")
3338 (,SIGFPE . "Arithmetic error")
3339 (,SIGBUS . "Bad memory access (bus error)")
3341 . "Bad memory access (Segmentation violation)"))
3348 (let ((make-handler (lambda (msg)
3350 ;; Make a backup copy of the stack
3351 (fluid-set! before-signal-stack
3352 (fluid-ref the-last-stack))
3360 (map (lambda (sig-msg)
3361 (sigaction (car sig-msg)
3362 (make-handler (cdr sig-msg))))
3365 ;; the protected thunk.
3367 (let ((status (scm-style-repl)))
3368 (run-hook exit-hook)
3373 (map (lambda (sig-msg old-handler)
3374 (if (not (car old-handler))
3375 ;; restore original C handler.
3376 (sigaction (car sig-msg) #f)
3377 ;; restore Scheme handler, SIG_IGN or SIG_DFL.
3378 (sigaction (car sig-msg)
3380 (cdr old-handler))))
3381 signals old-handlers))))))
3383 ;;; This hook is run at the very end of an interactive session.
3385 (define exit-hook (make-hook))
3389 ;;; {Deprecated stuff}
3393 (define (feature? sym)
3394 (issue-deprecation-warning
3395 "`feature?' is deprecated. Use `provided?' instead.")
3399 (primitive-load-path "ice-9/deprecated.scm"))
3403 ;;; Place the user in the guile-user module.
3406 (define-module (guile-user))
3408 ;;; boot-9.scm ends here