3 ;;;; Copyright (C) 1995,1996,1997,1998,1999,2000,2001,2002,2003,2004,2005,2006,2007
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
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)
54 ;; this is scheme wrapping the C code so the final pred call is a tail call,
56 (define (string-any char_pred s . rest)
57 (let ((start (if (null? rest)
59 (end (if (or (null? rest) (null? (cdr rest)))
60 (string-length s) (cadr rest))))
61 (if (and (procedure? char_pred)
63 (<= end (string-length s))) ;; let c-code handle range error
64 (or (string-any-c-code char_pred s start (1- end))
65 (char_pred (string-ref s (1- end))))
66 (string-any-c-code char_pred s start end))))
68 ;; this is scheme wrapping the C code so the final pred call is a tail call,
70 (define (string-every char_pred s . rest)
71 (let ((start (if (null? rest)
73 (end (if (or (null? rest) (null? (cdr rest)))
74 (string-length s) (cadr rest))))
75 (if (and (procedure? char_pred)
77 (<= end (string-length s))) ;; let c-code handle range error
78 (and (string-every-c-code char_pred s start (1- end))
79 (char_pred (string-ref s (1- end))))
80 (string-every-c-code char_pred s start end))))
82 ;; A variant of string-fill! that we keep for compatability
84 (define (substring-fill! str start end fill)
85 (string-fill! str fill start end))
92 ;; (eval-case ((situation*) forms)* (else forms)?)
94 ;; Evaluate certain code based on the situation that eval-case is used
95 ;; in. The only defined situation right now is `load-toplevel' which
96 ;; triggers for code evaluated at the top-level, for example from the
97 ;; REPL or when loading a file.
100 (procedure->memoizing-macro
102 (define (toplevel-env? env)
103 (or (not (pair? env)) (not (pair? (car env)))))
105 (error "syntax error in eval-case"))
106 (let loop ((clauses (cdr exp)))
110 ((not (list? (car clauses)))
112 ((eq? 'else (caar clauses))
113 (or (null? (cdr clauses))
115 (cons 'begin (cdar clauses)))
116 ((not (list? (caar clauses)))
118 ((and (toplevel-env? env)
119 (memq 'load-toplevel (caar clauses)))
120 (cons 'begin (cdar clauses)))
122 (loop (cdr clauses))))))))
128 ;;; Depends on: features, eval-case
131 (define macro-table (make-weak-key-hash-table 61))
132 (define xformer-table (make-weak-key-hash-table 61))
134 (define (defmacro? m) (hashq-ref macro-table m))
135 (define (assert-defmacro?! m) (hashq-set! macro-table m #t))
136 (define (defmacro-transformer m) (hashq-ref xformer-table m))
137 (define (set-defmacro-transformer! m t) (hashq-set! xformer-table m t))
139 (define defmacro:transformer
141 (let* ((xform (lambda (exp env)
142 (copy-tree (apply f (cdr exp)))))
143 (a (procedure->memoizing-macro xform)))
144 (assert-defmacro?! a)
145 (set-defmacro-transformer! a f)
150 (let ((defmacro-transformer
151 (lambda (name parms . body)
152 (let ((transformer `(lambda ,parms ,@body)))
155 (define ,name (defmacro:transformer ,transformer)))
157 (error "defmacro can only be used at the top level")))))))
158 (defmacro:transformer defmacro-transformer)))
160 (define defmacro:syntax-transformer
164 (copy-tree (apply f (cdr exp)))))))
167 ;; XXX - should the definition of the car really be looked up in the
170 (define (macroexpand-1 e)
172 ((pair? e) (let* ((a (car e))
173 (val (and (symbol? a) (local-ref (list a)))))
175 (apply (defmacro-transformer val) (cdr e))
179 (define (macroexpand e)
181 ((pair? e) (let* ((a (car e))
182 (val (and (symbol? a) (local-ref (list a)))))
184 (macroexpand (apply (defmacro-transformer val) (cdr e)))
194 ;;; Depends on: defmacro
197 (defmacro begin-deprecated forms
198 (if (include-deprecated-features)
204 ;;; {R4RS compliance}
207 (primitive-load-path "ice-9/r4rs.scm")
211 ;;; {Simple Debugging Tools}
214 ;; peek takes any number of arguments, writes them to the
215 ;; current ouput port, and returns the last argument.
216 ;; It is handy to wrap around an expression to look at
217 ;; a value each time is evaluated, e.g.:
219 ;; (+ 10 (troublesome-fn))
220 ;; => (+ 10 (pk 'troublesome-fn-returned (troublesome-fn)))
223 (define (peek . stuff)
228 (car (last-pair stuff)))
232 (define (warn . stuff)
233 (with-output-to-port (current-error-port)
236 (display ";;; WARNING ")
239 (car (last-pair stuff)))))
243 ;;; {Trivial Functions}
246 (define (identity x) x)
247 (define (and=> value procedure) (and value (procedure value)))
248 (define call/cc call-with-current-continuation)
250 ;;; apply-to-args is functionally redundant with apply and, worse,
251 ;;; is less general than apply since it only takes two arguments.
253 ;;; On the other hand, apply-to-args is a syntacticly convenient way to
254 ;;; perform binding in many circumstances when the "let" family of
255 ;;; of forms don't cut it. E.g.:
257 ;;; (apply-to-args (return-3d-mouse-coords)
262 (define (apply-to-args args fn) (apply fn args))
264 (defmacro false-if-exception (expr)
265 `(catch #t (lambda () ,expr)
270 ;;; {General Properties}
273 ;; This is a more modern interface to properties. It will replace all
274 ;; other property-like things eventually.
276 (define (make-object-property)
277 (let ((prop (primitive-make-property #f)))
278 (make-procedure-with-setter
279 (lambda (obj) (primitive-property-ref prop obj))
280 (lambda (obj val) (primitive-property-set! prop obj val)))))
284 ;;; {Symbol Properties}
287 (define (symbol-property sym prop)
288 (let ((pair (assoc prop (symbol-pref sym))))
289 (and pair (cdr pair))))
291 (define (set-symbol-property! sym prop val)
292 (let ((pair (assoc prop (symbol-pref sym))))
295 (symbol-pset! sym (acons prop val (symbol-pref sym))))))
297 (define (symbol-property-remove! sym prop)
298 (let ((pair (assoc prop (symbol-pref sym))))
300 (symbol-pset! sym (delq! pair (symbol-pref sym))))))
307 (define (array-shape a)
308 (map (lambda (ind) (if (number? ind) (list 0 (+ -1 ind)) ind))
309 (array-dimensions a)))
316 (define (kw-arg-ref args kw)
317 (let ((rem (member kw args)))
318 (and rem (pair? (cdr rem)) (cadr rem))))
325 (define (struct-layout s)
326 (struct-ref (struct-vtable s) vtable-index-layout))
333 (define the-environment
338 (define the-root-environment (the-environment))
340 (define (environment-module env)
341 (let ((closure (and (pair? env) (car (last-pair env)))))
342 (and closure (procedure-property closure 'module))))
349 ;; Printing records: by default, records are printed as
351 ;; #<type-name field1: val1 field2: val2 ...>
353 ;; You can change that by giving a custom printing function to
354 ;; MAKE-RECORD-TYPE (after the list of field symbols). This function
355 ;; will be called like
357 ;; (<printer> object port)
359 ;; It should print OBJECT to PORT.
361 (define (inherit-print-state old-port new-port)
362 (if (get-print-state old-port)
363 (port-with-print-state new-port (get-print-state old-port))
366 ;; 0: type-name, 1: fields
367 (define record-type-vtable
368 (make-vtable-vtable "prpr" 0
370 (cond ((eq? s record-type-vtable)
371 (display "#<record-type-vtable>" p))
373 (display "#<record-type " p)
374 (display (record-type-name s) p)
377 (define (record-type? obj)
378 (and (struct? obj) (eq? record-type-vtable (struct-vtable obj))))
380 (define (make-record-type type-name fields . opt)
381 (let ((printer-fn (and (pair? opt) (car opt))))
382 (let ((struct (make-struct record-type-vtable 0
385 (map (lambda (f) "pw") fields)))
389 (display type-name p)
390 (let loop ((fields fields)
393 ((not (null? fields))
395 (display (car fields) p)
397 (display (struct-ref s off) p)
398 (loop (cdr fields) (+ 1 off)))))
401 (copy-tree fields))))
402 ;; Temporary solution: Associate a name to the record type descriptor
403 ;; so that the object system can create a wrapper class for it.
404 (set-struct-vtable-name! struct (if (symbol? type-name)
406 (string->symbol type-name)))
409 (define (record-type-name obj)
410 (if (record-type? obj)
411 (struct-ref obj vtable-offset-user)
412 (error 'not-a-record-type obj)))
414 (define (record-type-fields obj)
415 (if (record-type? obj)
416 (struct-ref obj (+ 1 vtable-offset-user))
417 (error 'not-a-record-type obj)))
419 (define (record-constructor rtd . opt)
420 (let ((field-names (if (pair? opt) (car opt) (record-type-fields rtd))))
421 (local-eval `(lambda ,field-names
422 (make-struct ',rtd 0 ,@(map (lambda (f)
423 (if (memq f field-names)
426 (record-type-fields rtd))))
427 the-root-environment)))
429 (define (record-predicate rtd)
430 (lambda (obj) (and (struct? obj) (eq? rtd (struct-vtable obj)))))
432 (define (%record-type-error rtd obj) ;; private helper
433 (or (eq? rtd (record-type-descriptor obj))
434 (scm-error 'wrong-type-arg "%record-type-check"
435 "Wrong type record (want `~S'): ~S"
436 (list (record-type-name rtd) obj)
439 (define (record-accessor rtd field-name)
440 (let* ((pos (list-index (record-type-fields rtd) field-name)))
442 (error 'no-such-field field-name))
443 (local-eval `(lambda (obj)
444 (if (eq? (struct-vtable obj) ,rtd)
445 (struct-ref obj ,pos)
446 (%record-type-error ,rtd obj)))
447 the-root-environment)))
449 (define (record-modifier rtd field-name)
450 (let* ((pos (list-index (record-type-fields rtd) field-name)))
452 (error 'no-such-field field-name))
453 (local-eval `(lambda (obj val)
454 (if (eq? (struct-vtable obj) ,rtd)
455 (struct-set! obj ,pos val)
456 (%record-type-error ,rtd obj)))
457 the-root-environment)))
460 (define (record? obj)
461 (and (struct? obj) (record-type? (struct-vtable obj))))
463 (define (record-type-descriptor obj)
466 (error 'not-a-record obj)))
475 (define (->bool x) (not (not x)))
482 (define (symbol-append . args)
483 (string->symbol (apply string-append (map symbol->string args))))
485 (define (list->symbol . args)
486 (string->symbol (apply list->string args)))
488 (define (symbol . args)
489 (string->symbol (apply string args)))
496 (define (list-index l k)
502 (loop (+ n 1) (cdr l))))))
506 ;;; {and-map and or-map}
508 ;;; (and-map fn lst) is like (and (fn (car lst)) (fn (cadr lst)) (fn...) ...)
509 ;;; (or-map fn lst) is like (or (fn (car lst)) (fn (cadr lst)) (fn...) ...)
514 ;; Apply f to successive elements of l until exhaustion or f returns #f.
515 ;; If returning early, return #f. Otherwise, return the last value returned
516 ;; by f. If f has never been called because l is empty, return #t.
518 (define (and-map f lst)
519 (let loop ((result #t)
524 (loop (f (car l)) (cdr l))))))
528 ;; Apply f to successive elements of l until exhaustion or while f returns #f.
529 ;; If returning early, return the return value of f.
531 (define (or-map f lst)
532 (let loop ((result #f)
536 (loop (f (car l)) (cdr l))))))
540 (if (provided? 'posix)
541 (primitive-load-path "ice-9/posix.scm"))
543 (if (provided? 'socket)
544 (primitive-load-path "ice-9/networking.scm"))
546 ;; For reference, Emacs file-exists-p uses stat in this same way.
547 ;; ENHANCE-ME: Catching an exception from stat is a bit wasteful, do this in
548 ;; C where all that's needed is to inspect the return from stat().
550 (if (provided? 'posix)
552 (->bool (false-if-exception (stat str))))
554 (let ((port (catch 'system-error (lambda () (open-file str OPEN_READ))
556 (if port (begin (close-port port) #t)
559 (define file-is-directory?
560 (if (provided? 'posix)
562 (eq? (stat:type (stat str)) 'directory))
564 (let ((port (catch 'system-error
565 (lambda () (open-file (string-append str "/.")
568 (if port (begin (close-port port) #t)
571 (define (has-suffix? str suffix)
572 (let ((sufl (string-length suffix))
573 (sl (string-length str)))
575 (string=? (substring str (- sl sufl) sl) suffix))))
577 (define (system-error-errno args)
578 (if (eq? (car args) 'system-error)
579 (car (list-ref args 4))
587 (define (error . args)
590 (scm-error 'misc-error #f "?" #f #f)
591 (let loop ((msg "~A")
593 (if (not (null? rest))
594 (loop (string-append msg " ~S")
596 (scm-error 'misc-error #f msg args #f)))))
598 ;; bad-throw is the hook that is called upon a throw to a an unhandled
599 ;; key (unless the throw has four arguments, in which case
600 ;; it's usually interpreted as an error throw.)
601 ;; If the key has a default handler (a throw-handler-default property),
602 ;; it is applied to the throw.
604 (define (bad-throw key . args)
605 (let ((default (symbol-property key 'throw-handler-default)))
606 (or (and default (apply default key args))
607 (apply error "unhandled-exception:" key args))))
611 (define (tm:sec obj) (vector-ref obj 0))
612 (define (tm:min obj) (vector-ref obj 1))
613 (define (tm:hour obj) (vector-ref obj 2))
614 (define (tm:mday obj) (vector-ref obj 3))
615 (define (tm:mon obj) (vector-ref obj 4))
616 (define (tm:year obj) (vector-ref obj 5))
617 (define (tm:wday obj) (vector-ref obj 6))
618 (define (tm:yday obj) (vector-ref obj 7))
619 (define (tm:isdst obj) (vector-ref obj 8))
620 (define (tm:gmtoff obj) (vector-ref obj 9))
621 (define (tm:zone obj) (vector-ref obj 10))
623 (define (set-tm:sec obj val) (vector-set! obj 0 val))
624 (define (set-tm:min obj val) (vector-set! obj 1 val))
625 (define (set-tm:hour obj val) (vector-set! obj 2 val))
626 (define (set-tm:mday obj val) (vector-set! obj 3 val))
627 (define (set-tm:mon obj val) (vector-set! obj 4 val))
628 (define (set-tm:year obj val) (vector-set! obj 5 val))
629 (define (set-tm:wday obj val) (vector-set! obj 6 val))
630 (define (set-tm:yday obj val) (vector-set! obj 7 val))
631 (define (set-tm:isdst obj val) (vector-set! obj 8 val))
632 (define (set-tm:gmtoff obj val) (vector-set! obj 9 val))
633 (define (set-tm:zone obj val) (vector-set! obj 10 val))
635 (define (tms:clock obj) (vector-ref obj 0))
636 (define (tms:utime obj) (vector-ref obj 1))
637 (define (tms:stime obj) (vector-ref obj 2))
638 (define (tms:cutime obj) (vector-ref obj 3))
639 (define (tms:cstime obj) (vector-ref obj 4))
641 (define file-position ftell)
642 (define (file-set-position port offset . whence)
643 (let ((whence (if (eq? whence '()) SEEK_SET (car whence))))
644 (seek port offset whence)))
646 (define (move->fdes fd/port fd)
647 (cond ((integer? fd/port)
648 (dup->fdes fd/port fd)
652 (primitive-move->fdes fd/port fd)
653 (set-port-revealed! fd/port 1)
656 (define (release-port-handle port)
657 (let ((revealed (port-revealed port)))
659 (set-port-revealed! port (- revealed 1)))))
661 (define (dup->port port/fd mode . maybe-fd)
662 (let ((port (fdopen (apply dup->fdes port/fd maybe-fd)
665 (set-port-revealed! port 1))
668 (define (dup->inport port/fd . maybe-fd)
669 (apply dup->port port/fd "r" maybe-fd))
671 (define (dup->outport port/fd . maybe-fd)
672 (apply dup->port port/fd "w" maybe-fd))
674 (define (dup port/fd . maybe-fd)
675 (if (integer? port/fd)
676 (apply dup->fdes port/fd maybe-fd)
677 (apply dup->port port/fd (port-mode port/fd) maybe-fd)))
679 (define (duplicate-port port modes)
680 (dup->port port modes))
682 (define (fdes->inport fdes)
683 (let loop ((rest-ports (fdes->ports fdes)))
684 (cond ((null? rest-ports)
685 (let ((result (fdopen fdes "r")))
686 (set-port-revealed! result 1)
688 ((input-port? (car rest-ports))
689 (set-port-revealed! (car rest-ports)
690 (+ (port-revealed (car rest-ports)) 1))
693 (loop (cdr rest-ports))))))
695 (define (fdes->outport fdes)
696 (let loop ((rest-ports (fdes->ports fdes)))
697 (cond ((null? rest-ports)
698 (let ((result (fdopen fdes "w")))
699 (set-port-revealed! result 1)
701 ((output-port? (car rest-ports))
702 (set-port-revealed! (car rest-ports)
703 (+ (port-revealed (car rest-ports)) 1))
706 (loop (cdr rest-ports))))))
708 (define (port->fdes port)
709 (set-port-revealed! port (+ (port-revealed port) 1))
712 (define (setenv name value)
714 (putenv (string-append name "=" value))
717 (define (unsetenv name)
718 "Remove the entry for NAME from the environment."
726 ;;; Here for backward compatability
728 (define scheme-file-suffix (lambda () ".scm"))
730 (define (in-vicinity vicinity file)
731 (let ((tail (let ((len (string-length vicinity)))
734 (string-ref vicinity (- len 1))))))
735 (string-append vicinity
744 ;;; {Help for scm_shell}
746 ;;; The argument-processing code used by Guile-based shells generates
747 ;;; Scheme code based on the argument list. This page contains help
748 ;;; functions for the code it generates.
751 (define (command-line) (program-arguments))
753 ;; This is mostly for the internal use of the code generated by
754 ;; scm_compile_shell_switches.
756 (define (turn-on-debugging)
757 (debug-enable 'debug)
758 (debug-enable 'backtrace)
759 (read-enable 'positions))
761 (define (load-user-init)
762 (let* ((home (or (getenv "HOME")
763 (false-if-exception (passwd:dir (getpwuid (getuid))))
764 "/")) ;; fallback for cygwin etc.
765 (init-file (in-vicinity home ".guile")))
766 (if (file-exists? init-file)
767 (primitive-load init-file))))
771 ;;; {Loading by paths}
774 ;;; Load a Scheme source file named NAME, searching for it in the
775 ;;; directories listed in %load-path, and applying each of the file
776 ;;; name extensions listed in %load-extensions.
777 (define (load-from-path name)
778 (start-stack 'load-stack
779 (primitive-load-path name)))
784 ;;; {Transcendental Functions}
786 ;;; Derived from "Transcen.scm", Complex trancendental functions for SCM.
787 ;;; Written by Jerry D. Hedden, (C) FSF.
788 ;;; See the file `COPYING' for terms applying to this program.
792 (let ((integer-expt integer-expt))
794 (cond ((and (exact? z2) (integer? z2))
795 (integer-expt z1 z2))
796 ((and (real? z2) (real? z1) (>= z1 0))
799 (exp (* z2 (log z1))))))))
802 (if (real? z) ($sinh z)
803 (let ((x (real-part z)) (y (imag-part z)))
804 (make-rectangular (* ($sinh x) ($cos y))
805 (* ($cosh x) ($sin y))))))
807 (if (real? z) ($cosh z)
808 (let ((x (real-part z)) (y (imag-part z)))
809 (make-rectangular (* ($cosh x) ($cos y))
810 (* ($sinh x) ($sin y))))))
812 (if (real? z) ($tanh z)
813 (let* ((x (* 2 (real-part z)))
814 (y (* 2 (imag-part z)))
815 (w (+ ($cosh x) ($cos y))))
816 (make-rectangular (/ ($sinh x) w) (/ ($sin y) w)))))
819 (if (real? z) ($asinh z)
820 (log (+ z (sqrt (+ (* z z) 1))))))
823 (if (and (real? z) (>= z 1))
825 (log (+ z (sqrt (- (* z z) 1))))))
828 (if (and (real? z) (> z -1) (< z 1))
830 (/ (log (/ (+ 1 z) (- 1 z))) 2)))
833 (if (real? z) ($sin z)
834 (let ((x (real-part z)) (y (imag-part z)))
835 (make-rectangular (* ($sin x) ($cosh y))
836 (* ($cos x) ($sinh y))))))
838 (if (real? z) ($cos z)
839 (let ((x (real-part z)) (y (imag-part z)))
840 (make-rectangular (* ($cos x) ($cosh y))
841 (- (* ($sin x) ($sinh y)))))))
843 (if (real? z) ($tan z)
844 (let* ((x (* 2 (real-part z)))
845 (y (* 2 (imag-part z)))
846 (w (+ ($cos x) ($cosh y))))
847 (make-rectangular (/ ($sin x) w) (/ ($sinh y) w)))))
850 (if (and (real? z) (>= z -1) (<= z 1))
852 (* -i (asinh (* +i z)))))
855 (if (and (real? z) (>= z -1) (<= z 1))
857 (+ (/ (angle -1) 2) (* +i (asinh (* +i z))))))
861 (if (real? z) ($atan z)
862 (/ (log (/ (- +i z) (+ +i z))) +2i))
867 ;;; {Reader Extensions}
869 ;;; Reader code for various "#c" forms.
872 (read-hash-extend #\' (lambda (c port)
875 (define read-eval? (make-fluid))
876 (fluid-set! read-eval? #f)
877 (read-hash-extend #\.
879 (if (fluid-ref read-eval?)
880 (eval (read port) (interaction-environment))
882 "#. read expansion found and read-eval? is #f."))))
886 ;;; {Command Line Options}
889 (define (get-option argv kw-opts kw-args return)
894 ((or (not (eq? #\- (string-ref (car argv) 0)))
895 (eq? (string-length (car argv)) 1))
896 (return 'normal-arg (car argv) (cdr argv)))
898 ((eq? #\- (string-ref (car argv) 1))
899 (let* ((kw-arg-pos (or (string-index (car argv) #\=)
900 (string-length (car argv))))
901 (kw (symbol->keyword (substring (car argv) 2 kw-arg-pos)))
902 (kw-opt? (member kw kw-opts))
903 (kw-arg? (member kw kw-args))
904 (arg (or (and (not (eq? kw-arg-pos (string-length (car argv))))
905 (substring (car argv)
907 (string-length (car argv))))
909 (begin (set! argv (cdr argv)) (car argv))))))
910 (if (or kw-opt? kw-arg?)
911 (return kw arg (cdr argv))
912 (return 'usage-error kw (cdr argv)))))
915 (let* ((char (substring (car argv) 1 2))
916 (kw (symbol->keyword char)))
920 (let* ((rest-car (substring (car argv) 2 (string-length (car argv))))
921 (new-argv (if (= 0 (string-length rest-car))
923 (cons (string-append "-" rest-car) (cdr argv)))))
924 (return kw #f new-argv)))
927 (let* ((rest-car (substring (car argv) 2 (string-length (car argv))))
928 (arg (if (= 0 (string-length rest-car))
931 (new-argv (if (= 0 (string-length rest-car))
934 (return kw arg new-argv)))
936 (else (return 'usage-error kw argv)))))))
938 (define (for-next-option proc argv kw-opts kw-args)
939 (let loop ((argv argv))
940 (get-option argv kw-opts kw-args
941 (lambda (opt opt-arg argv)
942 (and opt (proc opt opt-arg argv loop))))))
944 (define (display-usage-report kw-desc)
947 (or (eq? (car kw) #t)
950 (help (cadr opt-desc))
951 (opts (car opt-desc))
952 (opts-proper (if (string? (car opts)) (cdr opts) opts))
953 (arg-name (if (string? (car opts))
954 (string-append "<" (car opts) ">")
956 (left-part (string-append
957 (with-output-to-string
959 (map (lambda (x) (display (keyword->symbol x)) (display " "))
962 (middle-part (if (and (< (string-length left-part) 30)
963 (< (string-length help) 40))
964 (make-string (- 30 (string-length left-part)) #\ )
967 (display middle-part)
974 (define (transform-usage-lambda cases)
975 (let* ((raw-usage (delq! 'else (map car cases)))
976 (usage-sans-specials (map (lambda (x)
977 (or (and (not (list? x)) x)
978 (and (symbol? (car x)) #t)
979 (and (boolean? (car x)) #t)
982 (usage-desc (delq! #t usage-sans-specials))
983 (kw-desc (map car usage-desc))
984 (kw-opts (apply append (map (lambda (x) (and (not (string? (car x))) x)) kw-desc)))
985 (kw-args (apply append (map (lambda (x) (and (string? (car x)) (cdr x))) kw-desc)))
986 (transmogrified-cases (map (lambda (case)
987 (cons (let ((opts (car case)))
988 (if (or (boolean? opts) (eq? 'else opts))
991 ((symbol? (car opts)) opts)
992 ((boolean? (car opts)) opts)
993 ((string? (caar opts)) (cdar opts))
997 `(let ((%display-usage (lambda () (display-usage-report ',usage-desc))))
999 (let %next-arg ((%argv %argv))
1003 (lambda (%opt %arg %new-argv)
1005 ,@ transmogrified-cases))))))))
1010 ;;; {Low Level Modules}
1012 ;;; These are the low level data structures for modules.
1014 ;;; Every module object is of the type 'module-type', which is a record
1015 ;;; consisting of the following members:
1017 ;;; - eval-closure: the function that defines for its module the strategy that
1018 ;;; shall be followed when looking up symbols in the module.
1020 ;;; An eval-closure is a function taking two arguments: the symbol to be
1021 ;;; looked up and a boolean value telling whether a binding for the symbol
1022 ;;; should be created if it does not exist yet. If the symbol lookup
1023 ;;; succeeded (either because an existing binding was found or because a new
1024 ;;; binding was created), a variable object representing the binding is
1025 ;;; returned. Otherwise, the value #f is returned. Note that the eval
1026 ;;; closure does not take the module to be searched as an argument: During
1027 ;;; construction of the eval-closure, the eval-closure has to store the
1028 ;;; module it belongs to in its environment. This means, that any
1029 ;;; eval-closure can belong to only one module.
1031 ;;; The eval-closure of a module can be defined arbitrarily. However, three
1032 ;;; special cases of eval-closures are to be distinguished: During startup
1033 ;;; the module system is not yet activated. In this phase, no modules are
1034 ;;; defined and all bindings are automatically stored by the system in the
1035 ;;; pre-modules-obarray. Since no eval-closures exist at this time, the
1036 ;;; functions which require an eval-closure as their argument need to be
1037 ;;; passed the value #f.
1039 ;;; The other two special cases of eval-closures are the
1040 ;;; standard-eval-closure and the standard-interface-eval-closure. Both
1041 ;;; behave equally for the case that no new binding is to be created. The
1042 ;;; difference between the two comes in, when the boolean argument to the
1043 ;;; eval-closure indicates that a new binding shall be created if it is not
1046 ;;; Given that no new binding shall be created, both standard eval-closures
1047 ;;; define the following standard strategy of searching bindings in the
1048 ;;; module: First, the module's obarray is searched for the symbol. Second,
1049 ;;; if no binding for the symbol was found in the module's obarray, the
1050 ;;; module's binder procedure is exececuted. If this procedure did not
1051 ;;; return a binding for the symbol, the modules referenced in the module's
1052 ;;; uses list are recursively searched for a binding of the symbol. If the
1053 ;;; binding can not be found in these modules also, the symbol lookup has
1056 ;;; If a new binding shall be created, the standard-interface-eval-closure
1057 ;;; immediately returns indicating failure. That is, it does not even try
1058 ;;; to look up the symbol. In contrast, the standard-eval-closure would
1059 ;;; first search the obarray, and if no binding was found there, would
1060 ;;; create a new binding in the obarray, therefore not calling the binder
1061 ;;; procedure or searching the modules in the uses list.
1063 ;;; The explanation of the following members obarray, binder and uses
1064 ;;; assumes that the symbol lookup follows the strategy that is defined in
1065 ;;; the standard-eval-closure and the standard-interface-eval-closure.
1067 ;;; - obarray: a hash table that maps symbols to variable objects. In this
1068 ;;; hash table, the definitions are found that are local to the module (that
1069 ;;; is, not imported from other modules). When looking up bindings in the
1070 ;;; module, this hash table is searched first.
1072 ;;; - binder: either #f or a function taking a module and a symbol argument.
1073 ;;; If it is a function it is called after the obarray has been
1074 ;;; unsuccessfully searched for a binding. It then can provide bindings
1075 ;;; that would otherwise not be found locally in the module.
1077 ;;; - uses: a list of modules from which non-local bindings can be inherited.
1078 ;;; These modules are the third place queried for bindings after the obarray
1079 ;;; has been unsuccessfully searched and the binder function did not deliver
1080 ;;; a result either.
1082 ;;; - transformer: either #f or a function taking a scheme expression as
1083 ;;; delivered by read. If it is a function, it will be called to perform
1084 ;;; syntax transformations (e. g. makro expansion) on the given scheme
1085 ;;; expression. The output of the transformer function will then be passed
1086 ;;; to Guile's internal memoizer. This means that the output must be valid
1087 ;;; scheme code. The only exception is, that the output may make use of the
1088 ;;; syntax extensions provided to identify the modules that a binding
1091 ;;; - name: the name of the module. This is used for all kinds of printing
1092 ;;; outputs. In certain places the module name also serves as a way of
1093 ;;; identification. When adding a module to the uses list of another
1094 ;;; module, it is made sure that the new uses list will not contain two
1095 ;;; modules of the same name.
1097 ;;; - kind: classification of the kind of module. The value is (currently?)
1098 ;;; only used for printing. It has no influence on how a module is treated.
1099 ;;; Currently the following values are used when setting the module kind:
1100 ;;; 'module, 'directory, 'interface, 'custom-interface. If no explicit kind
1101 ;;; is set, it defaults to 'module.
1103 ;;; - duplicates-handlers
1105 ;;; - duplicates-interface
1109 ;;; - weak-observers
1113 ;;; In addition, the module may (must?) contain a binding for
1114 ;;; %module-public-interface... More explanations here...
1116 ;;; !!! warning: The interface to lazy binder procedures is going
1117 ;;; to be changed in an incompatible way to permit all the basic
1118 ;;; module ops to be virtualized.
1120 ;;; (make-module size use-list lazy-binding-proc) => module
1121 ;;; module-{obarray,uses,binder}[|-set!]
1122 ;;; (module? obj) => [#t|#f]
1123 ;;; (module-locally-bound? module symbol) => [#t|#f]
1124 ;;; (module-bound? module symbol) => [#t|#f]
1125 ;;; (module-symbol-locally-interned? module symbol) => [#t|#f]
1126 ;;; (module-symbol-interned? module symbol) => [#t|#f]
1127 ;;; (module-local-variable module symbol) => [#<variable ...> | #f]
1128 ;;; (module-variable module symbol) => [#<variable ...> | #f]
1129 ;;; (module-symbol-binding module symbol opt-value)
1130 ;;; => [ <obj> | opt-value | an error occurs ]
1131 ;;; (module-make-local-var! module symbol) => #<variable...>
1132 ;;; (module-add! module symbol var) => unspecified
1133 ;;; (module-remove! module symbol) => unspecified
1134 ;;; (module-for-each proc module) => unspecified
1135 ;;; (make-scm-module) => module ; a lazy copy of the symhash module
1136 ;;; (set-current-module module) => unspecified
1137 ;;; (current-module) => #<module...>
1143 ;;; {Printing Modules}
1146 ;; This is how modules are printed. You can re-define it.
1147 ;; (Redefining is actually more complicated than simply redefining
1148 ;; %print-module because that would only change the binding and not
1149 ;; the value stored in the vtable that determines how record are
1152 (define (%print-module mod port) ; unused args: depth length style table)
1154 (display (or (module-kind mod) "module") port)
1155 (let ((name (module-name mod)))
1159 (display name port))))
1161 (display (number->string (object-address mod) 16) port)
1166 ;; A module is characterized by an obarray in which local symbols
1167 ;; are interned, a list of modules, "uses", from which non-local
1168 ;; bindings can be inherited, and an optional lazy-binder which
1169 ;; is a (CLOSURE module symbol) which, as a last resort, can provide
1170 ;; bindings that would otherwise not be found locally in the module.
1172 ;; NOTE: If you change anything here, you also need to change
1173 ;; libguile/modules.h.
1176 (make-record-type 'module
1177 '(obarray uses binder eval-closure transformer name kind
1178 duplicates-handlers duplicates-interface
1179 observers weak-observers observer-id)
1182 ;; make-module &opt size uses binder
1184 ;; Create a new module, perhaps with a particular size of obarray,
1185 ;; initial uses list, or binding procedure.
1190 (define (parse-arg index default)
1191 (if (> (length args) index)
1192 (list-ref args index)
1195 (if (> (length args) 3)
1196 (error "Too many args to make-module." args))
1198 (let ((size (parse-arg 0 31))
1199 (uses (parse-arg 1 '()))
1200 (binder (parse-arg 2 #f)))
1202 (if (not (integer? size))
1203 (error "Illegal size to make-module." size))
1204 (if (not (and (list? uses)
1205 (and-map module? uses)))
1206 (error "Incorrect use list." uses))
1207 (if (and binder (not (procedure? binder)))
1209 "Lazy-binder expected to be a procedure or #f." binder))
1211 (let ((module (module-constructor (make-hash-table size)
1212 uses binder #f #f #f #f #f #f
1214 (make-weak-value-hash-table 31)
1217 ;; We can't pass this as an argument to module-constructor,
1218 ;; because we need it to close over a pointer to the module
1220 (set-module-eval-closure! module (standard-eval-closure module))
1224 (define module-constructor (record-constructor module-type))
1225 (define module-obarray (record-accessor module-type 'obarray))
1226 (define set-module-obarray! (record-modifier module-type 'obarray))
1227 (define module-uses (record-accessor module-type 'uses))
1228 (define set-module-uses! (record-modifier module-type 'uses))
1229 (define module-binder (record-accessor module-type 'binder))
1230 (define set-module-binder! (record-modifier module-type 'binder))
1232 ;; NOTE: This binding is used in libguile/modules.c.
1233 (define module-eval-closure (record-accessor module-type 'eval-closure))
1235 (define module-transformer (record-accessor module-type 'transformer))
1236 (define set-module-transformer! (record-modifier module-type 'transformer))
1237 (define module-name (record-accessor module-type 'name))
1238 (define set-module-name! (record-modifier module-type 'name))
1239 (define module-kind (record-accessor module-type 'kind))
1240 (define set-module-kind! (record-modifier module-type 'kind))
1241 (define module-duplicates-handlers
1242 (record-accessor module-type 'duplicates-handlers))
1243 (define set-module-duplicates-handlers!
1244 (record-modifier module-type 'duplicates-handlers))
1245 (define module-duplicates-interface
1246 (record-accessor module-type 'duplicates-interface))
1247 (define set-module-duplicates-interface!
1248 (record-modifier module-type 'duplicates-interface))
1249 (define module-observers (record-accessor module-type 'observers))
1250 (define set-module-observers! (record-modifier module-type 'observers))
1251 (define module-weak-observers (record-accessor module-type 'weak-observers))
1252 (define module-observer-id (record-accessor module-type 'observer-id))
1253 (define set-module-observer-id! (record-modifier module-type 'observer-id))
1254 (define module? (record-predicate module-type))
1256 (define set-module-eval-closure!
1257 (let ((setter (record-modifier module-type 'eval-closure)))
1258 (lambda (module closure)
1259 (setter module closure)
1260 ;; Make it possible to lookup the module from the environment.
1261 ;; This implementation is correct since an eval closure can belong
1262 ;; to maximally one module.
1263 (set-procedure-property! closure 'module module))))
1267 ;;; {Observer protocol}
1270 (define (module-observe module proc)
1271 (set-module-observers! module (cons proc (module-observers module)))
1274 (define (module-observe-weak module proc)
1275 (let ((id (module-observer-id module)))
1276 (hash-set! (module-weak-observers module) id proc)
1277 (set-module-observer-id! module (+ 1 id))
1280 (define (module-unobserve token)
1281 (let ((module (car token))
1284 (hash-remove! (module-weak-observers module) id)
1285 (set-module-observers! module (delq1! id (module-observers module)))))
1288 (define module-defer-observers #f)
1289 (define module-defer-observers-mutex (make-mutex))
1290 (define module-defer-observers-table (make-hash-table))
1292 (define (module-modified m)
1293 (if module-defer-observers
1294 (hash-set! module-defer-observers-table m #t)
1295 (module-call-observers m)))
1297 ;;; This function can be used to delay calls to observers so that they
1298 ;;; can be called once only in the face of massive updating of modules.
1300 (define (call-with-deferred-observers thunk)
1303 (lock-mutex module-defer-observers-mutex)
1304 (set! module-defer-observers #t))
1307 (set! module-defer-observers #f)
1308 (hash-for-each (lambda (m dummy)
1309 (module-call-observers m))
1310 module-defer-observers-table)
1311 (hash-clear! module-defer-observers-table)
1312 (unlock-mutex module-defer-observers-mutex))))
1314 (define (module-call-observers m)
1315 (for-each (lambda (proc) (proc m)) (module-observers m))
1316 (hash-fold (lambda (id proc res) (proc m)) #f (module-weak-observers m)))
1320 ;;; {Module Searching in General}
1322 ;;; We sometimes want to look for properties of a symbol
1323 ;;; just within the obarray of one module. If the property
1324 ;;; holds, then it is said to hold ``locally'' as in, ``The symbol
1325 ;;; DISPLAY is locally rebound in the module `safe-guile'.''
1328 ;;; Other times, we want to test for a symbol property in the obarray
1329 ;;; of M and, if it is not found there, try each of the modules in the
1330 ;;; uses list of M. This is the normal way of testing for some
1331 ;;; property, so we state these properties without qualification as
1332 ;;; in: ``The symbol 'fnord is interned in module M because it is
1333 ;;; interned locally in module M2 which is a member of the uses list
1337 ;; module-search fn m
1339 ;; return the first non-#f result of FN applied to M and then to
1340 ;; the modules in the uses of m, and so on recursively. If all applications
1341 ;; return #f, then so does this function.
1343 (define (module-search fn m v)
1346 (or (module-search fn (car pos) v)
1349 (loop (module-uses m))))
1352 ;;; {Is a symbol bound in a module?}
1354 ;;; Symbol S in Module M is bound if S is interned in M and if the binding
1355 ;;; of S in M has been set to some well-defined value.
1358 ;; module-locally-bound? module symbol
1360 ;; Is a symbol bound (interned and defined) locally in a given module?
1362 (define (module-locally-bound? m v)
1363 (let ((var (module-local-variable m v)))
1365 (variable-bound? var))))
1367 ;; module-bound? module symbol
1369 ;; Is a symbol bound (interned and defined) anywhere in a given module
1372 (define (module-bound? m v)
1373 (module-search module-locally-bound? m v))
1375 ;;; {Is a symbol interned in a module?}
1377 ;;; Symbol S in Module M is interned if S occurs in
1378 ;;; of S in M has been set to some well-defined value.
1380 ;;; It is possible to intern a symbol in a module without providing
1381 ;;; an initial binding for the corresponding variable. This is done
1383 ;;; (module-add! module symbol (make-undefined-variable))
1385 ;;; In that case, the symbol is interned in the module, but not
1386 ;;; bound there. The unbound symbol shadows any binding for that
1387 ;;; symbol that might otherwise be inherited from a member of the uses list.
1390 (define (module-obarray-get-handle ob key)
1391 ((if (symbol? key) hashq-get-handle hash-get-handle) ob key))
1393 (define (module-obarray-ref ob key)
1394 ((if (symbol? key) hashq-ref hash-ref) ob key))
1396 (define (module-obarray-set! ob key val)
1397 ((if (symbol? key) hashq-set! hash-set!) ob key val))
1399 (define (module-obarray-remove! ob key)
1400 ((if (symbol? key) hashq-remove! hash-remove!) ob key))
1402 ;; module-symbol-locally-interned? module symbol
1404 ;; is a symbol interned (not neccessarily defined) locally in a given module
1405 ;; or its uses? Interned symbols shadow inherited bindings even if
1406 ;; they are not themselves bound to a defined value.
1408 (define (module-symbol-locally-interned? m v)
1409 (not (not (module-obarray-get-handle (module-obarray m) v))))
1411 ;; module-symbol-interned? module symbol
1413 ;; is a symbol interned (not neccessarily defined) anywhere in a given module
1414 ;; or its uses? Interned symbols shadow inherited bindings even if
1415 ;; they are not themselves bound to a defined value.
1417 (define (module-symbol-interned? m v)
1418 (module-search module-symbol-locally-interned? m v))
1421 ;;; {Mapping modules x symbols --> variables}
1424 ;; module-local-variable module symbol
1425 ;; return the local variable associated with a MODULE and SYMBOL.
1427 ;;; This function is very important. It is the only function that can
1428 ;;; return a variable from a module other than the mutators that store
1429 ;;; new variables in modules. Therefore, this function is the location
1430 ;;; of the "lazy binder" hack.
1432 ;;; If symbol is defined in MODULE, and if the definition binds symbol
1433 ;;; to a variable, return that variable object.
1435 ;;; If the symbols is not found at first, but the module has a lazy binder,
1436 ;;; then try the binder.
1438 ;;; If the symbol is not found at all, return #f.
1440 (define (module-local-variable m v)
1443 (let ((b (module-obarray-ref (module-obarray m) v)))
1444 (or (and (variable? b) b)
1445 (and (module-binder m)
1446 ((module-binder m) m v #f)))))
1449 ;; module-variable module symbol
1451 ;; like module-local-variable, except search the uses in the
1452 ;; case V is not found in M.
1454 ;; NOTE: This function is superseded with C code (see modules.c)
1455 ;;; when using the standard eval closure.
1457 (define (module-variable m v)
1458 (module-search module-local-variable m v))
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 (set-module-uses! module
1695 (not (equal? (module-name m)
1696 (module-name interface))))
1697 (module-uses module))))
1698 (module-modified module))
1700 ;; MODULE-USE-INTERFACES! module interfaces
1702 ;; Same as MODULE-USE! but add multiple interfaces and check for duplicates
1704 (define (module-use-interfaces! module interfaces)
1705 (let* ((duplicates-handlers? (or (module-duplicates-handlers module)
1706 (default-duplicate-binding-procedures)))
1707 (uses (module-uses module)))
1708 ;; remove duplicates-interface
1709 (set! uses (delq! (module-duplicates-interface module) uses))
1710 ;; remove interfaces to be added
1711 (for-each (lambda (interface)
1714 (not (equal? (module-name m)
1715 (module-name interface))))
1718 ;; add interfaces to use list
1719 (set-module-uses! module uses)
1720 (for-each (lambda (interface)
1721 (and duplicates-handlers?
1722 ;; perform duplicate checking
1723 (process-duplicates module interface))
1724 (set! uses (cons interface uses))
1725 (set-module-uses! module uses))
1727 ;; add duplicates interface
1728 (if (module-duplicates-interface module)
1729 (set-module-uses! module
1730 (cons (module-duplicates-interface module) uses)))
1731 (module-modified module)))
1735 ;;; {Recursive Namespaces}
1737 ;;; A hierarchical namespace emerges if we consider some module to be
1738 ;;; root, and variables bound to modules as nested namespaces.
1740 ;;; The routines in this file manage variable names in hierarchical namespace.
1741 ;;; Each variable name is a list of elements, looked up in successively nested
1744 ;;; (nested-ref some-root-module '(foo bar baz))
1745 ;;; => <value of a variable named baz in the module bound to bar in
1746 ;;; the module bound to foo in some-root-module>
1751 ;;; ;; a-root is a module
1752 ;;; ;; name is a list of symbols
1754 ;;; nested-ref a-root name
1755 ;;; nested-set! a-root name val
1756 ;;; nested-define! a-root name val
1757 ;;; nested-remove! a-root name
1760 ;;; (current-module) is a natural choice for a-root so for convenience there are
1763 ;;; local-ref name == nested-ref (current-module) name
1764 ;;; local-set! name val == nested-set! (current-module) name val
1765 ;;; local-define! name val == nested-define! (current-module) name val
1766 ;;; local-remove! name == nested-remove! (current-module) name
1770 (define (nested-ref root names)
1771 (let loop ((cur root)
1775 ((not (module? cur)) #f)
1776 (else (loop (module-ref cur (car elts) #f) (cdr elts))))))
1778 (define (nested-set! root names val)
1779 (let loop ((cur root)
1781 (if (null? (cdr elts))
1782 (module-set! cur (car elts) val)
1783 (loop (module-ref cur (car elts)) (cdr elts)))))
1785 (define (nested-define! root names val)
1786 (let loop ((cur root)
1788 (if (null? (cdr elts))
1789 (module-define! cur (car elts) val)
1790 (loop (module-ref cur (car elts)) (cdr elts)))))
1792 (define (nested-remove! root names)
1793 (let loop ((cur root)
1795 (if (null? (cdr elts))
1796 (module-remove! cur (car elts))
1797 (loop (module-ref cur (car elts)) (cdr elts)))))
1799 (define (local-ref names) (nested-ref (current-module) names))
1800 (define (local-set! names val) (nested-set! (current-module) names val))
1801 (define (local-define names val) (nested-define! (current-module) names val))
1802 (define (local-remove names) (nested-remove! (current-module) names))
1807 ;;; {The (%app) module}
1809 ;;; The root of conventionally named objects not directly in the top level.
1812 ;;; (%app modules guile)
1814 ;;; The directory of all modules and the standard root module.
1817 (define (module-public-interface m)
1818 (module-ref m '%module-public-interface #f))
1819 (define (set-module-public-interface! m i)
1820 (module-define! m '%module-public-interface i))
1821 (define (set-system-module! m s)
1822 (set-procedure-property! (module-eval-closure m) 'system-module s))
1823 (define the-root-module (make-root-module))
1824 (define the-scm-module (make-scm-module))
1825 (set-module-public-interface! the-root-module the-scm-module)
1826 (set-module-name! the-root-module '(guile))
1827 (set-module-name! the-scm-module '(guile))
1828 (set-module-kind! the-scm-module 'interface)
1829 (for-each set-system-module! (list the-root-module the-scm-module) '(#t #t))
1831 ;; NOTE: This binding is used in libguile/modules.c.
1833 (define (make-modules-in module name)
1837 ((module-ref module (car name) #f)
1838 => (lambda (m) (make-modules-in m (cdr name))))
1839 (else (let ((m (make-module 31)))
1840 (set-module-kind! m 'directory)
1841 (set-module-name! m (append (or (module-name module)
1844 (module-define! module (car name) m)
1845 (make-modules-in m (cdr name)))))))
1847 (define (beautify-user-module! module)
1848 (let ((interface (module-public-interface module)))
1849 (if (or (not interface)
1850 (eq? interface module))
1851 (let ((interface (make-module 31)))
1852 (set-module-name! interface (module-name module))
1853 (set-module-kind! interface 'interface)
1854 (set-module-public-interface! module interface))))
1855 (if (and (not (memq the-scm-module (module-uses module)))
1856 (not (eq? module the-root-module)))
1857 (set-module-uses! module
1858 (append (module-uses module) (list the-scm-module)))))
1860 ;; NOTE: This binding is used in libguile/modules.c.
1862 (define (resolve-module name . maybe-autoload)
1863 (let ((full-name (append '(%app modules) name)))
1864 (let ((already (nested-ref the-root-module full-name)))
1866 ;; The module already exists...
1867 (if (and (or (null? maybe-autoload) (car maybe-autoload))
1868 (not (module-public-interface already)))
1869 ;; ...but we are told to load and it doesn't contain source, so
1871 (try-load-module name)
1873 ;; simply return it.
1876 ;; Try to autoload it if we are told so
1877 (if (or (null? maybe-autoload) (car maybe-autoload))
1878 (try-load-module name))
1880 (make-modules-in (current-module) full-name))))))
1882 ;; Cheat. These bindings are needed by modules.c, but we don't want
1883 ;; to move their real definition here because that would be unnatural.
1885 (define try-module-autoload #f)
1886 (define process-define-module #f)
1887 (define process-use-modules #f)
1888 (define module-export! #f)
1890 ;; This boots the module system. All bindings needed by modules.c
1891 ;; must have been defined by now.
1893 (set-current-module the-root-module)
1895 (define %app (make-module 31))
1896 (define app %app) ;; for backwards compatability
1897 (local-define '(%app modules) (make-module 31))
1898 (local-define '(%app modules guile) the-root-module)
1900 ;; (define-special-value '(%app modules new-ws) (lambda () (make-scm-module)))
1902 (define (try-load-module name)
1903 (or (begin-deprecated (try-module-linked name))
1904 (try-module-autoload name)
1905 (begin-deprecated (try-module-dynamic-link name))))
1907 (define (purify-module! module)
1908 "Removes bindings in MODULE which are inherited from the (guile) module."
1909 (let ((use-list (module-uses module)))
1910 (if (and (pair? use-list)
1911 (eq? (car (last-pair use-list)) the-scm-module))
1912 (set-module-uses! module (reverse (cdr (reverse use-list)))))))
1914 ;; Return a module that is an interface to the module designated by
1917 ;; `resolve-interface' takes four keyword arguments:
1919 ;; #:select SELECTION
1921 ;; SELECTION is a list of binding-specs to be imported; A binding-spec
1922 ;; is either a symbol or a pair of symbols (ORIG . SEEN), where ORIG
1923 ;; is the name in the used module and SEEN is the name in the using
1924 ;; module. Note that SEEN is also passed through RENAMER, below. The
1925 ;; default is to select all bindings. If you specify no selection but
1926 ;; a renamer, only the bindings that already exist in the used module
1927 ;; are made available in the interface. Bindings that are added later
1928 ;; are not picked up.
1932 ;; BINDINGS is a list of bindings which should not be imported.
1936 ;; PREFIX is a symbol that will be appended to each exported name.
1937 ;; The default is to not perform any renaming.
1939 ;; #:renamer RENAMER
1941 ;; RENAMER is a procedure that takes a symbol and returns its new
1942 ;; name. The default is not perform any renaming.
1944 ;; Signal "no code for module" error if module name is not resolvable
1945 ;; or its public interface is not available. Signal "no binding"
1946 ;; error if selected binding does not exist in the used module.
1948 (define (resolve-interface name . args)
1950 (define (get-keyword-arg args kw def)
1951 (cond ((memq kw args)
1953 (if (null? (cdr kw-arg))
1954 (error "keyword without value: " kw))
1959 (let* ((select (get-keyword-arg args #:select #f))
1960 (hide (get-keyword-arg args #:hide '()))
1961 (renamer (or (get-keyword-arg args #:renamer #f)
1962 (let ((prefix (get-keyword-arg args #:prefix #f)))
1963 (and prefix (symbol-prefix-proc prefix)))
1965 (module (resolve-module name))
1966 (public-i (and module (module-public-interface module))))
1967 (and (or (not module) (not public-i))
1968 (error "no code for module" name))
1969 (if (and (not select) (null? hide) (eq? renamer identity))
1971 (let ((selection (or select (module-map (lambda (sym var) sym)
1973 (custom-i (make-module 31)))
1974 (set-module-kind! custom-i 'custom-interface)
1975 (set-module-name! custom-i name)
1976 ;; XXX - should use a lazy binder so that changes to the
1977 ;; used module are picked up automatically.
1978 (for-each (lambda (bspec)
1979 (let* ((direct? (symbol? bspec))
1980 (orig (if direct? bspec (car bspec)))
1981 (seen (if direct? bspec (cdr bspec)))
1982 (var (or (module-local-variable public-i orig)
1983 (module-local-variable module orig)
1985 ;; fixme: format manually for now
1987 #f "no binding `~A' in module ~A"
1989 (if (memq orig hide)
1990 (set! hide (delq! orig hide))
1991 (module-add! custom-i
1995 ;; Check that we are not hiding bindings which don't exist
1996 (for-each (lambda (binding)
1997 (if (not (module-local-variable public-i binding))
2000 #f "no binding `~A' to hide in module ~A"
2005 (define (symbol-prefix-proc prefix)
2007 (symbol-append prefix symbol)))
2009 ;; This function is called from "modules.c". If you change it, be
2010 ;; sure to update "modules.c" as well.
2012 (define (process-define-module args)
2013 (let* ((module-id (car args))
2014 (module (resolve-module module-id #f))
2016 (unrecognized (lambda (arg)
2017 (error "unrecognized define-module argument" arg))))
2018 (beautify-user-module! module)
2019 (let loop ((kws kws)
2020 (reversed-interfaces '())
2026 (call-with-deferred-observers
2028 (module-use-interfaces! module (reverse reversed-interfaces))
2029 (module-export! module exports)
2030 (module-replace! module replacements)
2031 (module-re-export! module re-exports)))
2033 ((#:use-module #:use-syntax)
2034 (or (pair? (cdr kws))
2036 (let* ((interface-args (cadr kws))
2037 (interface (apply resolve-interface interface-args)))
2038 (and (eq? (car kws) #:use-syntax)
2039 (or (symbol? (caar interface-args))
2040 (error "invalid module name for use-syntax"
2041 (car interface-args)))
2042 (set-module-transformer!
2044 (module-ref interface
2045 (car (last-pair (car interface-args)))
2048 (cons interface reversed-interfaces)
2053 (or (and (pair? (cdr kws)) (pair? (cddr kws)))
2056 (cons (make-autoload-interface module
2059 reversed-interfaces)
2064 (set-system-module! module #t)
2065 (loop (cdr kws) reversed-interfaces exports re-exports replacements))
2067 (purify-module! module)
2068 (loop (cdr kws) reversed-interfaces exports re-exports replacements))
2070 (if (not (pair? (cdr kws)))
2072 (set-module-duplicates-handlers!
2074 (lookup-duplicates-handlers (cadr kws)))
2075 (loop (cddr kws) reversed-interfaces exports re-exports replacements))
2076 ((#:export #:export-syntax)
2077 (or (pair? (cdr kws))
2081 (append (cadr kws) exports)
2084 ((#:re-export #:re-export-syntax)
2085 (or (pair? (cdr kws))
2090 (append (cadr kws) re-exports)
2092 ((#:replace #:replace-syntax)
2093 (or (pair? (cdr kws))
2099 (append (cadr kws) replacements)))
2101 (unrecognized kws)))))
2102 (run-hook module-defined-hook module)
2105 ;; `module-defined-hook' is a hook that is run whenever a new module
2106 ;; is defined. Its members are called with one argument, the new
2108 (define module-defined-hook (make-hook 1))
2115 (define (make-autoload-interface module name bindings)
2116 (let ((b (lambda (a sym definep)
2117 (and (memq sym bindings)
2118 (let ((i (module-public-interface (resolve-module name))))
2120 (error "missing interface for module" name))
2121 (let ((autoload (memq a (module-uses module))))
2122 ;; Replace autoload-interface with actual interface if
2123 ;; that has not happened yet.
2124 (if (pair? autoload)
2125 (set-car! autoload i)))
2126 (module-local-variable i sym))))))
2127 (module-constructor (make-hash-table 0) '() b #f #f name 'autoload #f #f
2128 '() (make-weak-value-hash-table 31) 0)))
2130 ;;; {Compiled module}
2132 (define load-compiled #f)
2136 ;;; {Autoloading modules}
2139 (define autoloads-in-progress '())
2141 ;; This function is called from "modules.c". If you change it, be
2142 ;; sure to update "modules.c" as well.
2144 (define (try-module-autoload module-name)
2145 (let* ((reverse-name (reverse module-name))
2146 (name (symbol->string (car reverse-name)))
2147 (dir-hint-module-name (reverse (cdr reverse-name)))
2148 (dir-hint (apply string-append
2150 (string-append (symbol->string elt) "/"))
2151 dir-hint-module-name))))
2152 (resolve-module dir-hint-module-name #f)
2153 (and (not (autoload-done-or-in-progress? dir-hint name))
2155 (define (load-file proc file)
2156 (save-module-excursion (lambda () (proc file)))
2159 (lambda () (autoload-in-progress! dir-hint name))
2161 (let ((file (in-vicinity dir-hint name)))
2162 (cond ((and load-compiled
2163 (%search-load-path (string-append file ".go")))
2165 (load-file load-compiled full)))
2166 ((%search-load-path file)
2168 (with-fluids ((current-reader #f))
2169 (load-file primitive-load full)))))))
2170 (lambda () (set-autoloaded! dir-hint name didit)))
2175 ;;; {Dynamic linking of modules}
2178 (define autoloads-done '((guile . guile)))
2180 (define (autoload-done-or-in-progress? p m)
2181 (let ((n (cons p m)))
2182 (->bool (or (member n autoloads-done)
2183 (member n autoloads-in-progress)))))
2185 (define (autoload-done! p m)
2186 (let ((n (cons p m)))
2187 (set! autoloads-in-progress
2188 (delete! n autoloads-in-progress))
2189 (or (member n autoloads-done)
2190 (set! autoloads-done (cons n autoloads-done)))))
2192 (define (autoload-in-progress! p m)
2193 (let ((n (cons p m)))
2194 (set! autoloads-done
2195 (delete! n autoloads-done))
2196 (set! autoloads-in-progress (cons n autoloads-in-progress))))
2198 (define (set-autoloaded! p m done?)
2200 (autoload-done! p m)
2201 (let ((n (cons p m)))
2202 (set! autoloads-done (delete! n autoloads-done))
2203 (set! autoloads-in-progress (delete! n autoloads-in-progress)))))
2207 ;;; {Run-time options}
2210 (define define-option-interface
2211 (let* ((option-name car)
2213 (option-documentation caddr)
2215 (print-option (lambda (option)
2216 (display (option-name option))
2217 (if (< (string-length
2218 (symbol->string (option-name option)))
2222 (display (option-value option))
2224 (display (option-documentation option))
2227 ;; Below follow the macros defining the run-time option interfaces.
2229 (make-options (lambda (interface)
2231 (cond ((null? args) (,interface))
2233 (,interface (car args)) (,interface))
2234 (else (for-each ,print-option
2235 (,interface #t)))))))
2237 (make-enable (lambda (interface)
2239 (,interface (append flags (,interface)))
2242 (make-disable (lambda (interface)
2244 (let ((options (,interface)))
2245 (for-each (lambda (flag)
2246 (set! options (delq! flag options)))
2248 (,interface options)
2250 (procedure->memoizing-macro
2252 (let* ((option-group (cadr exp))
2253 (interface (car option-group))
2254 (options/enable/disable (cadr option-group)))
2256 (define ,(car options/enable/disable)
2257 ,(make-options interface))
2258 (define ,(cadr options/enable/disable)
2259 ,(make-enable interface))
2260 (define ,(caddr options/enable/disable)
2261 ,(make-disable interface))
2262 (defmacro ,(caaddr option-group) (opt val)
2263 `(,,(car options/enable/disable)
2264 (append (,,(car options/enable/disable))
2265 (list ',opt ,val))))))))))
2267 (define-option-interface
2268 (eval-options-interface
2269 (eval-options eval-enable eval-disable)
2272 (define-option-interface
2273 (debug-options-interface
2274 (debug-options debug-enable debug-disable)
2277 (define-option-interface
2278 (evaluator-traps-interface
2279 (traps trap-enable trap-disable)
2282 (define-option-interface
2283 (read-options-interface
2284 (read-options read-enable read-disable)
2287 (define-option-interface
2288 (print-options-interface
2289 (print-options print-enable print-disable)
2297 (define (repl read evaler print)
2298 (let loop ((source (read (current-input-port))))
2299 (print (evaler source))
2300 (loop (read (current-input-port)))))
2302 ;; A provisional repl that acts like the SCM repl:
2304 (define scm-repl-silent #f)
2305 (define (assert-repl-silence v) (set! scm-repl-silent v))
2307 (define *unspecified* (if #f #f))
2308 (define (unspecified? v) (eq? v *unspecified*))
2310 (define scm-repl-print-unspecified #f)
2311 (define (assert-repl-print-unspecified v) (set! scm-repl-print-unspecified v))
2313 (define scm-repl-verbose #f)
2314 (define (assert-repl-verbosity v) (set! scm-repl-verbose v))
2316 (define scm-repl-prompt "guile> ")
2318 (define (set-repl-prompt! v) (set! scm-repl-prompt v))
2320 (define (default-lazy-handler key . args)
2321 (save-stack lazy-handler-dispatch)
2322 (apply throw key args))
2324 (define (lazy-handler-dispatch key . args)
2325 (apply default-lazy-handler key args))
2327 (define abort-hook (make-hook))
2329 ;; these definitions are used if running a script.
2330 ;; otherwise redefined in error-catching-loop.
2331 (define (set-batch-mode?! arg) #t)
2332 (define (batch-mode?) #t)
2334 (define (error-catching-loop thunk)
2337 (define (loop first)
2342 (call-with-unblocked-asyncs
2348 ;; This line is needed because mark
2349 ;; doesn't do closures quite right.
2350 ;; Unreferenced locals should be
2353 (let loop ((v (thunk)))
2357 (lambda (key . args)
2364 (apply throw 'switch-repl args))
2367 ;; This is one of the closures that require
2368 ;; (set! first #f) above
2371 (run-hook abort-hook)
2372 (force-output (current-output-port))
2373 (display "ABORT: " (current-error-port))
2374 (write args (current-error-port))
2375 (newline (current-error-port))
2379 (not has-shown-debugger-hint?)
2380 (not (memq 'backtrace
2381 (debug-options-interface)))
2382 (stack? (fluid-ref the-last-stack)))
2384 (newline (current-error-port))
2386 "Type \"(backtrace)\" to get more information or \"(debug)\" to enter the debugger.\n"
2387 (current-error-port))
2388 (set! has-shown-debugger-hint? #t)))
2389 (force-output (current-error-port)))
2391 (primitive-exit 1)))
2392 (set! stack-saved? #f)))
2395 ;; This is the other cons-leak closure...
2397 (cond ((= (length args) 4)
2398 (apply handle-system-error key args))
2400 (apply bad-throw key args)))))))
2402 ;; Note that having just `lazy-handler-dispatch'
2403 ;; here is connected with the mechanism that
2404 ;; produces a nice backtrace upon error. If, for
2405 ;; example, this is replaced with (lambda args
2406 ;; (apply lazy-handler-dispatch args)), the stack
2407 ;; cutting (in save-stack) goes wrong and ends up
2408 ;; saving no stack at all, so there is no
2410 lazy-handler-dispatch)))
2412 (if next (loop next) status)))
2413 (set! set-batch-mode?! (lambda (arg)
2415 (set! interactive #f)
2418 (error "sorry, not implemented")))))
2419 (set! batch-mode? (lambda () (not interactive)))
2420 (call-with-blocked-asyncs
2421 (lambda () (loop (lambda () #t))))))
2423 ;;(define the-last-stack (make-fluid)) Defined by scm_init_backtrace ()
2424 (define before-signal-stack (make-fluid))
2425 (define stack-saved? #f)
2427 (define (save-stack . narrowing)
2429 (cond ((not (memq 'debug (debug-options-interface)))
2430 (fluid-set! the-last-stack #f)
2431 (set! stack-saved? #t))
2437 (apply make-stack #t save-stack primitive-eval #t 0 narrowing))
2439 (apply make-stack #t save-stack 0 #t 0 narrowing))
2441 (apply make-stack #t save-stack tk-stack-mark #t 0 narrowing))
2443 (apply make-stack #t save-stack 0 1 narrowing))
2445 (let ((id (stack-id #t)))
2446 (and (procedure? id)
2447 (apply make-stack #t save-stack id #t 0 narrowing))))))
2448 (set! stack-saved? #t)))))
2450 (define before-error-hook (make-hook))
2451 (define after-error-hook (make-hook))
2452 (define before-backtrace-hook (make-hook))
2453 (define after-backtrace-hook (make-hook))
2455 (define has-shown-debugger-hint? #f)
2457 (define (handle-system-error key . args)
2458 (let ((cep (current-error-port)))
2459 (cond ((not (stack? (fluid-ref the-last-stack))))
2460 ((memq 'backtrace (debug-options-interface))
2461 (let ((highlights (if (or (eq? key 'wrong-type-arg)
2462 (eq? key 'out-of-range))
2465 (run-hook before-backtrace-hook)
2467 (display "Backtrace:\n")
2468 (display-backtrace (fluid-ref the-last-stack) cep
2471 (run-hook after-backtrace-hook))))
2472 (run-hook before-error-hook)
2473 (apply display-error (fluid-ref the-last-stack) cep args)
2474 (run-hook after-error-hook)
2476 (throw 'abort key)))
2478 (define (quit . args)
2479 (apply throw 'quit args))
2483 ;;(define has-shown-backtrace-hint? #f) Defined by scm_init_backtrace ()
2485 ;; Replaced by C code:
2486 ;;(define (backtrace)
2487 ;; (if (fluid-ref the-last-stack)
2490 ;; (display-backtrace (fluid-ref the-last-stack) (current-output-port))
2492 ;; (if (and (not has-shown-backtrace-hint?)
2493 ;; (not (memq 'backtrace (debug-options-interface))))
2496 ;;"Type \"(debug-enable 'backtrace)\" if you would like a backtrace
2497 ;;automatically if an error occurs in the future.\n")
2498 ;; (set! has-shown-backtrace-hint? #t))))
2499 ;; (display "No backtrace available.\n")))
2501 (define (error-catching-repl r e p)
2502 (error-catching-loop
2504 (call-with-values (lambda () (e (r)))
2505 (lambda the-values (for-each p the-values))))))
2507 (define (gc-run-time)
2508 (cdr (assq 'gc-time-taken (gc-stats))))
2510 (define before-read-hook (make-hook))
2511 (define after-read-hook (make-hook))
2512 (define before-eval-hook (make-hook 1))
2513 (define after-eval-hook (make-hook 1))
2514 (define before-print-hook (make-hook 1))
2515 (define after-print-hook (make-hook 1))
2517 ;;; The default repl-reader function. We may override this if we've
2518 ;;; the readline library.
2523 (run-hook before-read-hook)
2524 ((or (fluid-ref current-reader) read) (current-input-port))))
2526 (define (scm-style-repl)
2531 (repl-report-start-timing (lambda ()
2532 (set! start-gc-rt (gc-run-time))
2533 (set! start-rt (get-internal-run-time))))
2534 (repl-report (lambda ()
2536 (display (inexact->exact
2537 (* 1000 (/ (- (get-internal-run-time) start-rt)
2538 internal-time-units-per-second))))
2540 (display (inexact->exact
2541 (* 1000 (/ (- (gc-run-time) start-gc-rt)
2542 internal-time-units-per-second))))
2543 (display " msec in gc)\n")))
2545 (consume-trailing-whitespace
2547 (let ((ch (peek-char)))
2550 ((or (char=? ch #\space) (char=? ch #\tab))
2552 (consume-trailing-whitespace))
2553 ((char=? ch #\newline)
2557 (let ((prompt (cond ((string? scm-repl-prompt)
2559 ((thunk? scm-repl-prompt)
2561 (scm-repl-prompt "> ")
2563 (repl-reader prompt))))
2565 ;; As described in R4RS, the READ procedure updates the
2566 ;; port to point to the first character past the end of
2567 ;; the external representation of the object. This
2568 ;; means that it doesn't consume the newline typically
2569 ;; found after an expression. This means that, when
2570 ;; debugging Guile with GDB, GDB gets the newline, which
2571 ;; it often interprets as a "continue" command, making
2572 ;; breakpoints kind of useless. So, consume any
2573 ;; trailing newline here, as well as any whitespace
2575 ;; But not if EOF, for control-D.
2576 (if (not (eof-object? val))
2577 (consume-trailing-whitespace))
2578 (run-hook after-read-hook)
2579 (if (eof-object? val)
2581 (repl-report-start-timing)
2582 (if scm-repl-verbose
2585 (display ";;; EOF -- quitting")
2590 (-eval (lambda (sourc)
2591 (repl-report-start-timing)
2592 (run-hook before-eval-hook sourc)
2593 (let ((val (start-stack 'repl-stack
2594 ;; If you change this procedure
2595 ;; (primitive-eval), please also
2596 ;; modify the repl-stack case in
2597 ;; save-stack so that stack cutting
2598 ;; continues to work.
2599 (primitive-eval sourc))))
2600 (run-hook after-eval-hook sourc)
2604 (-print (let ((maybe-print (lambda (result)
2605 (if (or scm-repl-print-unspecified
2606 (not (unspecified? result)))
2611 (if (not scm-repl-silent)
2613 (run-hook before-print-hook result)
2614 (maybe-print result)
2615 (run-hook after-print-hook result)
2616 (if scm-repl-verbose
2620 (-quit (lambda (args)
2621 (if scm-repl-verbose
2623 (display ";;; QUIT executed, repl exitting")
2629 (if scm-repl-verbose
2631 (display ";;; ABORT executed.")
2634 (repl -read -eval -print))))
2636 (let ((status (error-catching-repl -read
2644 ;;; {IOTA functions: generating lists of numbers}
2648 (let loop ((count (1- n)) (result '()))
2649 (if (< count 0) result
2650 (loop (1- count) (cons count result)))))
2656 ;;; Similar to `begin' but returns a list of the results of all constituent
2657 ;;; forms instead of the result of the last form.
2658 ;;; (The definition relies on the current left-to-right
2659 ;;; order of evaluation of operands in applications.)
2662 (defmacro collect forms
2670 ;; with-fluids is a convenience wrapper for the builtin procedure
2671 ;; `with-fluids*'. The syntax is just like `let':
2673 ;; (with-fluids ((fluid val)
2677 (defmacro with-fluids (bindings . body)
2678 (let ((fluids (map car bindings))
2679 (values (map cadr bindings)))
2680 (if (and (= (length fluids) 1) (= (length values) 1))
2681 `(with-fluid* ,(car fluids) ,(car values) (lambda () ,@body))
2682 `(with-fluids* (list ,@fluids) (list ,@values)
2683 (lambda () ,@body)))))
2690 ;; actually....hobbit might be able to hack these with a little
2694 (define (primitive-macro? m)
2696 (not (macro-transformer m))))
2698 (defmacro define-macro (first . rest)
2699 (let ((name (if (symbol? first) first (car first)))
2703 `(lambda ,(cdr first) ,@rest))))
2706 (define ,name (defmacro:transformer ,transformer)))
2708 (error "define-macro can only be used at the top level")))))
2711 (defmacro define-syntax-macro (first . rest)
2712 (let ((name (if (symbol? first) first (car first)))
2716 `(lambda ,(cdr first) ,@rest))))
2719 (define ,name (defmacro:syntax-transformer ,transformer)))
2721 (error "define-syntax-macro can only be used at the top level")))))
2727 ;;; with `continue' and `break'.
2730 ;; The inner `do' loop avoids re-establishing a catch every iteration,
2731 ;; that's only necessary if continue is actually used. A new key is
2732 ;; generated every time, so break and continue apply to their originating
2733 ;; `while' even when recursing. `while-helper' is an easy way to keep the
2734 ;; `key' binding away from the cond and body code.
2736 ;; FIXME: This is supposed to have an `unquote' on the `do' the same used
2737 ;; for lambda and not, so as to protect against any user rebinding of that
2738 ;; symbol, but unfortunately an unquote breaks with ice-9 syncase, eg.
2740 ;; (use-modules (ice-9 syncase))
2742 ;; => ERROR: invalid syntax ()
2744 ;; This is probably a bug in syncase.
2746 (define-macro (while cond . body)
2747 (define (while-helper proc)
2748 (do ((key (make-symbol "while-key")))
2751 (proc (lambda () (throw key #t))
2752 (lambda () (throw key #f))))
2753 (lambda (key arg) arg)))))
2754 `(,while-helper (,lambda (break continue)
2763 ;;; {Module System Macros}
2766 ;; Return a list of expressions that evaluate to the appropriate
2767 ;; arguments for resolve-interface according to SPEC.
2769 (define (compile-interface-spec spec)
2770 (define (make-keyarg sym key quote?)
2771 (cond ((or (memq sym spec)
2775 (list key (list 'quote (cadr rest)))
2776 (list key (cadr rest)))))
2779 (define (map-apply func list)
2780 (map (lambda (args) (apply func args)) list))
2783 '((:select #:select #t)
2785 (:prefix #:prefix #t)
2786 (:renamer #:renamer #f)))
2787 (if (not (pair? (car spec)))
2790 ,@(apply append (map-apply make-keyarg keys)))))
2792 (define (keyword-like-symbol->keyword sym)
2793 (symbol->keyword (string->symbol (substring (symbol->string sym) 1))))
2795 (define (compile-define-module-args args)
2796 ;; Just quote everything except #:use-module and #:use-syntax. We
2797 ;; need to know about all arguments regardless since we want to turn
2798 ;; symbols that look like keywords into real keywords, and the
2799 ;; keyword args in a define-module form are not regular
2800 ;; (i.e. no-backtrace doesn't take a value).
2801 (let loop ((compiled-args `((quote ,(car args))))
2804 (reverse! compiled-args))
2805 ;; symbol in keyword position
2806 ((symbol? (car args))
2808 (cons (keyword-like-symbol->keyword (car args)) (cdr args))))
2809 ((memq (car args) '(#:no-backtrace #:pure))
2810 (loop (cons (car args) compiled-args)
2813 (error "keyword without value:" (car args)))
2814 ((memq (car args) '(#:use-module #:use-syntax))
2815 (loop (cons* `(list ,@(compile-interface-spec (cadr args)))
2819 ((eq? (car args) #:autoload)
2820 (loop (cons* `(quote ,(caddr args))
2821 `(quote ,(cadr args))
2826 (loop (cons* `(quote ,(cadr args))
2831 (defmacro define-module args
2834 (let ((m (process-define-module
2835 (list ,@(compile-define-module-args args)))))
2836 (set-current-module m)
2839 (error "define-module can only be used at the top level"))))
2841 ;; The guts of the use-modules macro. Add the interfaces of the named
2842 ;; modules to the use-list of the current module, in order.
2844 ;; This function is called by "modules.c". If you change it, be sure
2845 ;; to change scm_c_use_module as well.
2847 (define (process-use-modules module-interface-args)
2848 (let ((interfaces (map (lambda (mif-args)
2849 (or (apply resolve-interface mif-args)
2850 (error "no such module" mif-args)))
2851 module-interface-args)))
2852 (call-with-deferred-observers
2854 (module-use-interfaces! (current-module) interfaces)))))
2856 (defmacro use-modules modules
2859 (process-use-modules
2860 (list ,@(map (lambda (m)
2861 `(list ,@(compile-interface-spec m)))
2865 (error "use-modules can only be used at the top level"))))
2867 (defmacro use-syntax (spec)
2871 `((process-use-modules (list
2872 (list ,@(compile-interface-spec spec))))
2873 (set-module-transformer! (current-module)
2874 ,(car (last-pair spec))))
2875 `((set-module-transformer! (current-module) ,spec)))
2878 (error "use-syntax can only be used at the top level"))))
2880 ;; Dirk:FIXME:: This incorrect (according to R5RS) syntax needs to be changed
2881 ;; as soon as guile supports hygienic macros.
2882 (define define-private define)
2884 (defmacro define-public args
2886 (error "bad syntax" (list 'define-public args)))
2887 (define (defined-name n)
2890 ((pair? n) (defined-name (car n)))
2896 (let ((name (defined-name (car args))))
2898 (define-private ,@args)
2899 (eval-case ((load-toplevel) (export ,name))))))))
2901 (defmacro defmacro-public args
2903 (error "bad syntax" (list 'defmacro-public args)))
2904 (define (defined-name n)
2912 (let ((name (defined-name (car args))))
2914 (eval-case ((load-toplevel) (export-syntax ,name)))
2915 (defmacro ,@args))))))
2917 ;; Export a local variable
2919 ;; This function is called from "modules.c". If you change it, be
2920 ;; sure to update "modules.c" as well.
2922 (define (module-export! m names)
2923 (let ((public-i (module-public-interface m)))
2924 (for-each (lambda (name)
2925 (let ((var (module-ensure-local-variable! m name)))
2926 (module-add! public-i name var)))
2929 (define (module-replace! m names)
2930 (let ((public-i (module-public-interface m)))
2931 (for-each (lambda (name)
2932 (let ((var (module-ensure-local-variable! m name)))
2933 (set-object-property! var 'replace #t)
2934 (module-add! public-i name var)))
2937 ;; Re-export a imported variable
2939 (define (module-re-export! m names)
2940 (let ((public-i (module-public-interface m)))
2941 (for-each (lambda (name)
2942 (let ((var (module-variable m name)))
2944 (error "Undefined variable:" name))
2945 ((eq? var (module-local-variable m name))
2946 (error "re-exporting local variable:" name))
2948 (module-add! public-i name var)))))
2951 (defmacro export names
2954 (call-with-deferred-observers
2956 (module-export! (current-module) ',names))))
2958 (error "export can only be used at the top level"))))
2960 (defmacro re-export names
2963 (call-with-deferred-observers
2965 (module-re-export! (current-module) ',names))))
2967 (error "re-export can only be used at the top level"))))
2969 (defmacro export-syntax names
2972 (defmacro re-export-syntax names
2973 `(re-export ,@names))
2975 (define load load-module)
2977 ;; The following macro allows one to write, for example,
2979 ;; (@ (ice-9 pretty-print) pretty-print)
2981 ;; to refer directly to the pretty-print variable in module (ice-9
2982 ;; pretty-print). It works by looking up the variable and inserting
2983 ;; it directly into the code. This is understood by the evaluator.
2984 ;; Indeed, all references to global variables are memoized into such
2985 ;; variable objects.
2987 (define-macro (@ mod-name var-name)
2988 (let ((var (module-variable (resolve-interface mod-name) var-name)))
2990 (error "no such public variable" (list '@ mod-name var-name)))
2993 ;; The '@@' macro is like '@' but it can also access bindings that
2994 ;; have not been explicitely exported.
2996 (define-macro (@@ mod-name var-name)
2997 (let ((var (module-variable (resolve-module mod-name) var-name)))
2999 (error "no such variable" (list '@@ mod-name var-name)))
3007 (define make-mutable-parameter
3008 (let ((make (lambda (fluid converter)
3012 (fluid-set! fluid (converter (car args))))))))
3013 (lambda (init . converter)
3014 (let ((fluid (make-fluid))
3015 (converter (if (null? converter)
3018 (fluid-set! fluid (converter init))
3019 (make fluid converter)))))
3023 ;;; {Handling of duplicate imported bindings}
3026 ;; Duplicate handlers take the following arguments:
3028 ;; module importing module
3029 ;; name conflicting name
3030 ;; int1 old interface where name occurs
3031 ;; val1 value of binding in old interface
3032 ;; int2 new interface where name occurs
3033 ;; val2 value of binding in new interface
3034 ;; var previous resolution or #f
3035 ;; val value of previous resolution
3037 ;; A duplicate handler can take three alternative actions:
3039 ;; 1. return #f => leave responsibility to next handler
3040 ;; 2. exit with an error
3041 ;; 3. return a variable resolving the conflict
3044 (define duplicate-handlers
3045 (let ((m (make-module 7)))
3047 (define (check module name int1 val1 int2 val2 var val)
3048 (scm-error 'misc-error
3050 "~A: `~A' imported from both ~A and ~A"
3051 (list (module-name module)
3057 (define (warn module name int1 val1 int2 val2 var val)
3058 (format (current-error-port)
3059 "WARNING: ~A: `~A' imported from both ~A and ~A\n"
3060 (module-name module)
3066 (define (replace module name int1 val1 int2 val2 var val)
3067 (let ((old (or (and var (object-property var 'replace) var)
3068 (module-variable int1 name)))
3069 (new (module-variable int2 name)))
3070 (if (object-property old 'replace)
3071 (and (or (eq? old new)
3072 (not (object-property new 'replace)))
3074 (and (object-property new 'replace)
3077 (define (warn-override-core module name int1 val1 int2 val2 var val)
3078 (and (eq? int1 the-scm-module)
3080 (format (current-error-port)
3081 "WARNING: ~A: imported module ~A overrides core binding `~A'\n"
3082 (module-name module)
3085 (module-local-variable int2 name))))
3087 (define (first module name int1 val1 int2 val2 var val)
3088 (or var (module-local-variable int1 name)))
3090 (define (last module name int1 val1 int2 val2 var val)
3091 (module-local-variable int2 name))
3093 (define (noop module name int1 val1 int2 val2 var val)
3096 (set-module-name! m 'duplicate-handlers)
3097 (set-module-kind! m 'interface)
3098 (module-define! m 'check check)
3099 (module-define! m 'warn warn)
3100 (module-define! m 'replace replace)
3101 (module-define! m 'warn-override-core warn-override-core)
3102 (module-define! m 'first first)
3103 (module-define! m 'last last)
3104 (module-define! m 'merge-generics noop)
3105 (module-define! m 'merge-accessors noop)
3108 (define (lookup-duplicates-handlers handler-names)
3110 (map (lambda (handler-name)
3111 (or (module-symbol-local-binding
3112 duplicate-handlers handler-name #f)
3113 (error "invalid duplicate handler name:"
3115 (if (list? handler-names)
3117 (list handler-names)))))
3119 (define default-duplicate-binding-procedures
3120 (make-mutable-parameter #f))
3122 (define default-duplicate-binding-handler
3123 (make-mutable-parameter '(replace warn-override-core warn last)
3124 (lambda (handler-names)
3125 (default-duplicate-binding-procedures
3126 (lookup-duplicates-handlers handler-names))
3129 (define (make-duplicates-interface)
3130 (let ((m (make-module)))
3131 (set-module-kind! m 'custom-interface)
3132 (set-module-name! m 'duplicates)
3135 (define (process-duplicates module interface)
3136 (let* ((duplicates-handlers (or (module-duplicates-handlers module)
3137 (default-duplicate-binding-procedures)))
3138 (duplicates-interface (module-duplicates-interface module)))
3141 (cond ((module-import-interface module name)
3143 (lambda (prev-interface)
3144 (let ((var1 (module-local-variable prev-interface name))
3145 (var2 (module-local-variable interface name)))
3146 (if (not (eq? var1 var2))
3148 (if (not duplicates-interface)
3150 (set! duplicates-interface
3151 (make-duplicates-interface))
3152 (set-module-duplicates-interface!
3154 duplicates-interface)))
3155 (let* ((var (module-local-variable duplicates-interface
3158 (variable-bound? var)
3159 (variable-ref var))))
3160 (let loop ((duplicates-handlers duplicates-handlers))
3161 (cond ((null? duplicates-handlers))
3162 (((car duplicates-handlers)
3166 (and (variable-bound? var1)
3167 (variable-ref var1))
3169 (and (variable-bound? var2)
3170 (variable-ref var2))
3175 (module-add! duplicates-interface name var)))
3177 (loop (cdr duplicates-handlers)))))))))))))
3182 ;;; {`cond-expand' for SRFI-0 support.}
3184 ;;; This syntactic form expands into different commands or
3185 ;;; definitions, depending on the features provided by the Scheme
3191 ;;; --> (cond-expand <cond-expand-clause>+)
3192 ;;; | (cond-expand <cond-expand-clause>* (else <command-or-definition>))
3193 ;;; <cond-expand-clause>
3194 ;;; --> (<feature-requirement> <command-or-definition>*)
3195 ;;; <feature-requirement>
3196 ;;; --> <feature-identifier>
3197 ;;; | (and <feature-requirement>*)
3198 ;;; | (or <feature-requirement>*)
3199 ;;; | (not <feature-requirement>)
3200 ;;; <feature-identifier>
3201 ;;; --> <a symbol which is the name or alias of a SRFI>
3203 ;;; Additionally, this implementation provides the
3204 ;;; <feature-identifier>s `guile' and `r5rs', so that programs can
3205 ;;; determine the implementation type and the supported standard.
3207 ;;; Currently, the following feature identifiers are supported:
3209 ;;; guile r5rs srfi-0 srfi-4 srfi-6 srfi-13 srfi-14 srfi-55 srfi-61
3211 ;;; Remember to update the features list when adding more SRFIs.
3214 (define %cond-expand-features
3215 ;; Adjust the above comment when changing this.
3218 srfi-0 ;; cond-expand itself
3219 srfi-4 ;; homogenous numeric vectors
3220 srfi-6 ;; open-input-string etc, in the guile core
3221 srfi-13 ;; string library
3222 srfi-14 ;; character sets
3223 srfi-55 ;; require-extension
3224 srfi-61 ;; general cond clause
3227 ;; This table maps module public interfaces to the list of features.
3229 (define %cond-expand-table (make-hash-table 31))
3231 ;; Add one or more features to the `cond-expand' feature list of the
3234 (define (cond-expand-provide module features)
3235 (let ((mod (module-public-interface module)))
3237 (hashq-set! %cond-expand-table mod
3238 (append (hashq-ref %cond-expand-table mod '())
3242 (procedure->memoizing-macro
3244 (let ((clauses (cdr exp))
3245 (syntax-error (lambda (cl)
3246 (error "invalid clause in `cond-expand'" cl))))
3252 (or (memq clause %cond-expand-features)
3253 (let lp ((uses (module-uses (env-module env))))
3256 (hashq-ref %cond-expand-table
3262 ((eq? 'and (car clause))
3263 (let lp ((l (cdr clause)))
3267 (and (test-clause (car l)) (lp (cdr l))))
3269 (syntax-error clause)))))
3270 ((eq? 'or (car clause))
3271 (let lp ((l (cdr clause)))
3275 (or (test-clause (car l)) (lp (cdr l))))
3277 (syntax-error clause)))))
3278 ((eq? 'not (car clause))
3279 (cond ((not (pair? (cdr clause)))
3280 (syntax-error clause))
3281 ((pair? (cddr clause))
3282 ((syntax-error clause))))
3283 (not (test-clause (cadr clause))))
3285 (syntax-error clause))))
3287 (syntax-error clause))))))
3288 (let lp ((c clauses))
3291 (error "Unfulfilled `cond-expand'"))
3294 ((not (pair? (car c)))
3295 (syntax-error (car c)))
3296 ((test-clause (caar c))
3297 `(begin ,@(cdar c)))
3298 ((eq? (caar c) 'else)
3301 `(begin ,@(cdar c)))
3303 (lp (cdr c))))))))))
3305 ;; This procedure gets called from the startup code with a list of
3306 ;; numbers, which are the numbers of the SRFIs to be loaded on startup.
3308 (define (use-srfis srfis)
3309 (process-use-modules
3311 (list (list 'srfi (string->symbol
3312 (string-append "srfi-" (number->string num))))))
3317 ;;; srfi-55: require-extension
3320 (define-macro (require-extension extension-spec)
3321 ;; This macro only handles the srfi extension, which, at present, is
3322 ;; the only one defined by the standard.
3323 (if (not (pair? extension-spec))
3324 (scm-error 'wrong-type-arg "require-extension"
3325 "Not an extension: ~S" (list extension-spec) #f))
3326 (let ((extension (car extension-spec))
3327 (extension-args (cdr extension-spec)))
3330 (let ((use-list '()))
3333 (if (not (integer? i))
3334 (scm-error 'wrong-type-arg "require-extension"
3335 "Invalid srfi name: ~S" (list i) #f))
3336 (let ((srfi-sym (string->symbol
3337 (string-append "srfi-" (number->string i)))))
3338 (if (not (memq srfi-sym %cond-expand-features))
3339 (set! use-list (cons `(use-modules (srfi ,srfi-sym))
3342 (if (pair? use-list)
3343 ;; i.e. (begin (use-modules x) (use-modules y) (use-modules z))
3344 `(begin ,@(reverse! use-list)))))
3347 'wrong-type-arg "require-extension"
3348 "Not a recognized extension type: ~S" (list extension) #f)))))
3352 ;;; {Load emacs interface support if emacs option is given.}
3355 (define (named-module-use! user usee)
3356 (module-use! (resolve-module user) (resolve-interface usee)))
3358 (define (load-emacs-interface)
3359 (and (provided? 'debug-extensions)
3360 (debug-enable 'backtrace))
3361 (named-module-use! '(guile-user) '(ice-9 emacs)))
3365 (define using-readline?
3366 (let ((using-readline? (make-fluid)))
3367 (make-procedure-with-setter
3368 (lambda () (fluid-ref using-readline?))
3369 (lambda (v) (fluid-set! using-readline? v)))))
3372 (let ((guile-user-module (resolve-module '(guile-user))))
3374 ;; Load emacs interface support if emacs option is given.
3375 (if (and (module-defined? guile-user-module 'use-emacs-interface)
3376 (module-ref guile-user-module 'use-emacs-interface))
3377 (load-emacs-interface))
3379 ;; Use some convenient modules (in reverse order)
3381 (set-current-module guile-user-module)
3382 (process-use-modules
3387 (if (provided? 'regex)
3390 (if (provided? 'threads)
3391 '(((ice-9 threads)))
3393 ;; load debugger on demand
3394 (module-use! guile-user-module
3395 (make-autoload-interface guile-user-module
3396 '(ice-9 debugger) '(debug)))
3399 ;; Note: SIGFPE, SIGSEGV and SIGBUS are actually "query-only" (see
3400 ;; scmsigs.c scm_sigaction_for_thread), so the handlers setup here have
3402 (let ((old-handlers #f)
3403 (signals (if (provided? 'posix)
3404 `((,SIGINT . "User interrupt")
3405 (,SIGFPE . "Arithmetic error")
3407 . "Bad memory access (Segmentation violation)"))
3409 ;; no SIGBUS on mingw
3410 (if (defined? 'SIGBUS)
3411 (set! signals (acons SIGBUS "Bad memory access (bus error)"
3418 (let ((make-handler (lambda (msg)
3420 ;; Make a backup copy of the stack
3421 (fluid-set! before-signal-stack
3422 (fluid-ref the-last-stack))
3430 (map (lambda (sig-msg)
3431 (sigaction (car sig-msg)
3432 (make-handler (cdr sig-msg))))
3435 ;; the protected thunk.
3437 (let ((status (scm-style-repl)))
3438 (run-hook exit-hook)
3443 (map (lambda (sig-msg old-handler)
3444 (if (not (car old-handler))
3445 ;; restore original C handler.
3446 (sigaction (car sig-msg) #f)
3447 ;; restore Scheme handler, SIG_IGN or SIG_DFL.
3448 (sigaction (car sig-msg)
3450 (cdr old-handler))))
3451 signals old-handlers))))))
3453 ;;; This hook is run at the very end of an interactive session.
3455 (define exit-hook (make-hook))
3459 ;;; {Deprecated stuff}
3463 (define (feature? sym)
3464 (issue-deprecation-warning
3465 "`feature?' is deprecated. Use `provided?' instead.")
3469 (primitive-load-path "ice-9/deprecated.scm"))
3473 ;;; Place the user in the guile-user module.
3476 (define-module (guile-user))
3478 ;;; boot-9.scm ends here