3 ;;;; Copyright (C) 1995,1996,1997,1998,1999,2000,2001,2002,2003,2004,2005
4 ;;;; Free Software Foundation, Inc.
6 ;;;; This library is free software; you can redistribute it and/or
7 ;;;; modify it under the terms of the GNU Lesser General Public
8 ;;;; License as published by the Free Software Foundation; either
9 ;;;; version 2.1 of the License, or (at your option) any later version.
11 ;;;; This library is distributed in the hope that it will be useful,
12 ;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
13 ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 ;;;; Lesser General Public License for more details.
16 ;;;; You should have received a copy of the GNU Lesser General Public
17 ;;;; License along with this library; if not, write to the Free Software
18 ;;;; Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
25 ;;; This file is the first thing loaded into Guile. It adds many mundane
26 ;;; definitions and a few that are interesting.
28 ;;; The module system (hence the hierarchical namespace) are defined in this
40 (if (not (memq sym *features*))
41 (set! *features* (cons sym *features*))))
43 ;; Return #t iff FEATURE is available to this Guile interpreter. In SLIB,
44 ;; provided? also checks to see if the module is available. We should do that
47 (define (provided? feature)
48 (and (memq feature *features*) #t))
50 ;; let format alias simple-format until the more complete version is loaded
52 (define format simple-format)
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))))
87 ;; (eval-case ((situation*) forms)* (else forms)?)
89 ;; Evaluate certain code based on the situation that eval-case is used
90 ;; in. The only defined situation right now is `load-toplevel' which
91 ;; triggers for code evaluated at the top-level, for example from the
92 ;; REPL or when loading a file.
95 (procedure->memoizing-macro
97 (define (toplevel-env? env)
98 (or (not (pair? env)) (not (pair? (car env)))))
100 (error "syntax error in eval-case"))
101 (let loop ((clauses (cdr exp)))
105 ((not (list? (car clauses)))
107 ((eq? 'else (caar clauses))
108 (or (null? (cdr clauses))
110 (cons 'begin (cdar clauses)))
111 ((not (list? (caar clauses)))
113 ((and (toplevel-env? env)
114 (memq 'load-toplevel (caar clauses)))
115 (cons 'begin (cdar clauses)))
117 (loop (cdr clauses))))))))
123 ;;; Depends on: features, eval-case
126 (define macro-table (make-weak-key-hash-table 61))
127 (define xformer-table (make-weak-key-hash-table 61))
129 (define (defmacro? m) (hashq-ref macro-table m))
130 (define (assert-defmacro?! m) (hashq-set! macro-table m #t))
131 (define (defmacro-transformer m) (hashq-ref xformer-table m))
132 (define (set-defmacro-transformer! m t) (hashq-set! xformer-table m t))
134 (define defmacro:transformer
136 (let* ((xform (lambda (exp env)
137 (copy-tree (apply f (cdr exp)))))
138 (a (procedure->memoizing-macro xform)))
139 (assert-defmacro?! a)
140 (set-defmacro-transformer! a f)
145 (let ((defmacro-transformer
146 (lambda (name parms . body)
147 (let ((transformer `(lambda ,parms ,@body)))
150 (define ,name (defmacro:transformer ,transformer)))
152 (error "defmacro can only be used at the top level")))))))
153 (defmacro:transformer defmacro-transformer)))
155 (define defmacro:syntax-transformer
159 (copy-tree (apply f (cdr exp)))))))
162 ;; XXX - should the definition of the car really be looked up in the
165 (define (macroexpand-1 e)
167 ((pair? e) (let* ((a (car e))
168 (val (and (symbol? a) (local-ref (list a)))))
170 (apply (defmacro-transformer val) (cdr e))
174 (define (macroexpand e)
176 ((pair? e) (let* ((a (car e))
177 (val (and (symbol? a) (local-ref (list a)))))
179 (macroexpand (apply (defmacro-transformer val) (cdr e)))
189 ;;; Depends on: defmacro
192 (defmacro begin-deprecated forms
193 (if (include-deprecated-features)
199 ;;; {R4RS compliance}
202 (primitive-load-path "ice-9/r4rs.scm")
206 ;;; {Simple Debugging Tools}
209 ;; peek takes any number of arguments, writes them to the
210 ;; current ouput port, and returns the last argument.
211 ;; It is handy to wrap around an expression to look at
212 ;; a value each time is evaluated, e.g.:
214 ;; (+ 10 (troublesome-fn))
215 ;; => (+ 10 (pk 'troublesome-fn-returned (troublesome-fn)))
218 (define (peek . stuff)
223 (car (last-pair stuff)))
227 (define (warn . stuff)
228 (with-output-to-port (current-error-port)
231 (display ";;; WARNING ")
234 (car (last-pair stuff)))))
238 ;;; {Trivial Functions}
241 (define (identity x) x)
242 (define (1+ n) (+ n 1))
243 (define (1- n) (+ n -1))
244 (define (and=> value procedure) (and value (procedure value)))
245 (define call/cc call-with-current-continuation)
247 ;;; apply-to-args is functionally redundant with apply and, worse,
248 ;;; is less general than apply since it only takes two arguments.
250 ;;; On the other hand, apply-to-args is a syntacticly convenient way to
251 ;;; perform binding in many circumstances when the "let" family of
252 ;;; of forms don't cut it. E.g.:
254 ;;; (apply-to-args (return-3d-mouse-coords)
259 (define (apply-to-args args fn) (apply fn args))
261 (defmacro false-if-exception (expr)
262 `(catch #t (lambda () ,expr)
267 ;;; {General Properties}
270 ;; This is a more modern interface to properties. It will replace all
271 ;; other property-like things eventually.
273 (define (make-object-property)
274 (let ((prop (primitive-make-property #f)))
275 (make-procedure-with-setter
276 (lambda (obj) (primitive-property-ref prop obj))
277 (lambda (obj val) (primitive-property-set! prop obj val)))))
281 ;;; {Symbol Properties}
284 (define (symbol-property sym prop)
285 (let ((pair (assoc prop (symbol-pref sym))))
286 (and pair (cdr pair))))
288 (define (set-symbol-property! sym prop val)
289 (let ((pair (assoc prop (symbol-pref sym))))
292 (symbol-pset! sym (acons prop val (symbol-pref sym))))))
294 (define (symbol-property-remove! sym prop)
295 (let ((pair (assoc prop (symbol-pref sym))))
297 (symbol-pset! sym (delq! pair (symbol-pref sym))))))
304 (define (array-shape a)
305 (map (lambda (ind) (if (number? ind) (list 0 (+ -1 ind)) ind))
306 (array-dimensions a)))
313 (define (kw-arg-ref args kw)
314 (let ((rem (member kw args)))
315 (and rem (pair? (cdr rem)) (cadr rem))))
322 (define (struct-layout s)
323 (struct-ref (struct-vtable s) vtable-index-layout))
330 (define the-environment
335 (define the-root-environment (the-environment))
337 (define (environment-module env)
338 (let ((closure (and (pair? env) (car (last-pair env)))))
339 (and closure (procedure-property closure 'module))))
346 ;; Printing records: by default, records are printed as
348 ;; #<type-name field1: val1 field2: val2 ...>
350 ;; You can change that by giving a custom printing function to
351 ;; MAKE-RECORD-TYPE (after the list of field symbols). This function
352 ;; will be called like
354 ;; (<printer> object port)
356 ;; It should print OBJECT to PORT.
358 (define (inherit-print-state old-port new-port)
359 (if (get-print-state old-port)
360 (port-with-print-state new-port (get-print-state old-port))
363 ;; 0: type-name, 1: fields
364 (define record-type-vtable
365 (make-vtable-vtable "prpr" 0
367 (cond ((eq? s record-type-vtable)
368 (display "#<record-type-vtable>" p))
370 (display "#<record-type " p)
371 (display (record-type-name s) p)
374 (define (record-type? obj)
375 (and (struct? obj) (eq? record-type-vtable (struct-vtable obj))))
377 (define (make-record-type type-name fields . opt)
378 (let ((printer-fn (and (pair? opt) (car opt))))
379 (let ((struct (make-struct record-type-vtable 0
382 (map (lambda (f) "pw") fields)))
386 (display type-name p)
387 (let loop ((fields fields)
390 ((not (null? fields))
392 (display (car fields) p)
394 (display (struct-ref s off) p)
395 (loop (cdr fields) (+ 1 off)))))
398 (copy-tree fields))))
399 ;; Temporary solution: Associate a name to the record type descriptor
400 ;; so that the object system can create a wrapper class for it.
401 (set-struct-vtable-name! struct (if (symbol? type-name)
403 (string->symbol type-name)))
406 (define (record-type-name obj)
407 (if (record-type? obj)
408 (struct-ref obj vtable-offset-user)
409 (error 'not-a-record-type obj)))
411 (define (record-type-fields obj)
412 (if (record-type? obj)
413 (struct-ref obj (+ 1 vtable-offset-user))
414 (error 'not-a-record-type obj)))
416 (define (record-constructor rtd . opt)
417 (let ((field-names (if (pair? opt) (car opt) (record-type-fields rtd))))
418 (local-eval `(lambda ,field-names
419 (make-struct ',rtd 0 ,@(map (lambda (f)
420 (if (memq f field-names)
423 (record-type-fields rtd))))
424 the-root-environment)))
426 (define (record-predicate rtd)
427 (lambda (obj) (and (struct? obj) (eq? rtd (struct-vtable obj)))))
429 (define (record-accessor rtd field-name)
430 (let* ((pos (list-index (record-type-fields rtd) field-name)))
432 (error 'no-such-field field-name))
433 (local-eval `(lambda (obj)
434 (and (eq? ',rtd (record-type-descriptor obj))
435 (struct-ref obj ,pos)))
436 the-root-environment)))
438 (define (record-modifier rtd field-name)
439 (let* ((pos (list-index (record-type-fields rtd) field-name)))
441 (error 'no-such-field field-name))
442 (local-eval `(lambda (obj val)
443 (and (eq? ',rtd (record-type-descriptor obj))
444 (struct-set! obj ,pos val)))
445 the-root-environment)))
448 (define (record? obj)
449 (and (struct? obj) (record-type? (struct-vtable obj))))
451 (define (record-type-descriptor obj)
454 (error 'not-a-record obj)))
463 (define (->bool x) (not (not x)))
470 (define (symbol-append . args)
471 (string->symbol (apply string-append (map symbol->string args))))
473 (define (list->symbol . args)
474 (string->symbol (apply list->string args)))
476 (define (symbol . args)
477 (string->symbol (apply string args)))
484 (define (list-index l k)
490 (loop (+ n 1) (cdr l))))))
492 (define (make-list n . init)
493 (if (pair? init) (set! init (car init)))
494 (let loop ((answer '())
498 (loop (cons init answer) (- n 1)))))
502 ;;; {and-map and or-map}
504 ;;; (and-map fn lst) is like (and (fn (car lst)) (fn (cadr lst)) (fn...) ...)
505 ;;; (or-map fn lst) is like (or (fn (car lst)) (fn (cadr lst)) (fn...) ...)
510 ;; Apply f to successive elements of l until exhaustion or f returns #f.
511 ;; If returning early, return #f. Otherwise, return the last value returned
512 ;; by f. If f has never been called because l is empty, return #t.
514 (define (and-map f lst)
515 (let loop ((result #t)
520 (loop (f (car l)) (cdr l))))))
524 ;; Apply f to successive elements of l until exhaustion or while f returns #f.
525 ;; If returning early, return the return value of f.
527 (define (or-map f lst)
528 (let loop ((result #f)
532 (loop (f (car l)) (cdr l))))))
536 (if (provided? 'posix)
537 (primitive-load-path "ice-9/posix.scm"))
539 (if (provided? 'socket)
540 (primitive-load-path "ice-9/networking.scm"))
542 ;; For reference, Emacs file-exists-p uses stat in this same way.
543 ;; ENHANCE-ME: Catching an exception from stat is a bit wasteful, do this in
544 ;; C where all that's needed is to inspect the return from stat().
546 (if (provided? 'posix)
548 (->bool (false-if-exception (stat str))))
550 (let ((port (catch 'system-error (lambda () (open-file str OPEN_READ))
552 (if port (begin (close-port port) #t)
555 (define file-is-directory?
556 (if (provided? 'posix)
558 (eq? (stat:type (stat str)) 'directory))
560 (let ((port (catch 'system-error
561 (lambda () (open-file (string-append str "/.")
564 (if port (begin (close-port port) #t)
567 (define (has-suffix? str suffix)
568 (let ((sufl (string-length suffix))
569 (sl (string-length str)))
571 (string=? (substring str (- sl sufl) sl) suffix))))
573 (define (system-error-errno args)
574 (if (eq? (car args) 'system-error)
575 (car (list-ref args 4))
583 (define (error . args)
586 (scm-error 'misc-error #f "?" #f #f)
587 (let loop ((msg "~A")
589 (if (not (null? rest))
590 (loop (string-append msg " ~S")
592 (scm-error 'misc-error #f msg args #f)))))
594 ;; bad-throw is the hook that is called upon a throw to a an unhandled
595 ;; key (unless the throw has four arguments, in which case
596 ;; it's usually interpreted as an error throw.)
597 ;; If the key has a default handler (a throw-handler-default property),
598 ;; it is applied to the throw.
600 (define (bad-throw key . args)
601 (let ((default (symbol-property key 'throw-handler-default)))
602 (or (and default (apply default key args))
603 (apply error "unhandled-exception:" key args))))
607 (define (tm:sec obj) (vector-ref obj 0))
608 (define (tm:min obj) (vector-ref obj 1))
609 (define (tm:hour obj) (vector-ref obj 2))
610 (define (tm:mday obj) (vector-ref obj 3))
611 (define (tm:mon obj) (vector-ref obj 4))
612 (define (tm:year obj) (vector-ref obj 5))
613 (define (tm:wday obj) (vector-ref obj 6))
614 (define (tm:yday obj) (vector-ref obj 7))
615 (define (tm:isdst obj) (vector-ref obj 8))
616 (define (tm:gmtoff obj) (vector-ref obj 9))
617 (define (tm:zone obj) (vector-ref obj 10))
619 (define (set-tm:sec obj val) (vector-set! obj 0 val))
620 (define (set-tm:min obj val) (vector-set! obj 1 val))
621 (define (set-tm:hour obj val) (vector-set! obj 2 val))
622 (define (set-tm:mday obj val) (vector-set! obj 3 val))
623 (define (set-tm:mon obj val) (vector-set! obj 4 val))
624 (define (set-tm:year obj val) (vector-set! obj 5 val))
625 (define (set-tm:wday obj val) (vector-set! obj 6 val))
626 (define (set-tm:yday obj val) (vector-set! obj 7 val))
627 (define (set-tm:isdst obj val) (vector-set! obj 8 val))
628 (define (set-tm:gmtoff obj val) (vector-set! obj 9 val))
629 (define (set-tm:zone obj val) (vector-set! obj 10 val))
631 (define (tms:clock obj) (vector-ref obj 0))
632 (define (tms:utime obj) (vector-ref obj 1))
633 (define (tms:stime obj) (vector-ref obj 2))
634 (define (tms:cutime obj) (vector-ref obj 3))
635 (define (tms:cstime obj) (vector-ref obj 4))
637 (define file-position ftell)
638 (define (file-set-position port offset . whence)
639 (let ((whence (if (eq? whence '()) SEEK_SET (car whence))))
640 (seek port offset whence)))
642 (define (move->fdes fd/port fd)
643 (cond ((integer? fd/port)
644 (dup->fdes fd/port fd)
648 (primitive-move->fdes fd/port fd)
649 (set-port-revealed! fd/port 1)
652 (define (release-port-handle port)
653 (let ((revealed (port-revealed port)))
655 (set-port-revealed! port (- revealed 1)))))
657 (define (dup->port port/fd mode . maybe-fd)
658 (let ((port (fdopen (apply dup->fdes port/fd maybe-fd)
661 (set-port-revealed! port 1))
664 (define (dup->inport port/fd . maybe-fd)
665 (apply dup->port port/fd "r" maybe-fd))
667 (define (dup->outport port/fd . maybe-fd)
668 (apply dup->port port/fd "w" maybe-fd))
670 (define (dup port/fd . maybe-fd)
671 (if (integer? port/fd)
672 (apply dup->fdes port/fd maybe-fd)
673 (apply dup->port port/fd (port-mode port/fd) maybe-fd)))
675 (define (duplicate-port port modes)
676 (dup->port port modes))
678 (define (fdes->inport fdes)
679 (let loop ((rest-ports (fdes->ports fdes)))
680 (cond ((null? rest-ports)
681 (let ((result (fdopen fdes "r")))
682 (set-port-revealed! result 1)
684 ((input-port? (car rest-ports))
685 (set-port-revealed! (car rest-ports)
686 (+ (port-revealed (car rest-ports)) 1))
689 (loop (cdr rest-ports))))))
691 (define (fdes->outport fdes)
692 (let loop ((rest-ports (fdes->ports fdes)))
693 (cond ((null? rest-ports)
694 (let ((result (fdopen fdes "w")))
695 (set-port-revealed! result 1)
697 ((output-port? (car rest-ports))
698 (set-port-revealed! (car rest-ports)
699 (+ (port-revealed (car rest-ports)) 1))
702 (loop (cdr rest-ports))))))
704 (define (port->fdes port)
705 (set-port-revealed! port (+ (port-revealed port) 1))
708 (define (setenv name value)
710 (putenv (string-append name "=" value))
713 (define (unsetenv name)
714 "Remove the entry for NAME from the environment."
722 ;;; Here for backward compatability
724 (define scheme-file-suffix (lambda () ".scm"))
726 (define (in-vicinity vicinity file)
727 (let ((tail (let ((len (string-length vicinity)))
730 (string-ref vicinity (- len 1))))))
731 (string-append vicinity
740 ;;; {Help for scm_shell}
742 ;;; The argument-processing code used by Guile-based shells generates
743 ;;; Scheme code based on the argument list. This page contains help
744 ;;; functions for the code it generates.
747 (define (command-line) (program-arguments))
749 ;; This is mostly for the internal use of the code generated by
750 ;; scm_compile_shell_switches.
752 (define (turn-on-debugging)
753 (debug-enable 'debug)
754 (debug-enable 'backtrace)
755 (read-enable 'positions))
757 (define (load-user-init)
758 (let* ((home (or (getenv "HOME")
759 (false-if-exception (passwd:dir (getpwuid (getuid))))
760 "/")) ;; fallback for cygwin etc.
761 (init-file (in-vicinity home ".guile")))
762 (if (file-exists? init-file)
763 (primitive-load init-file))))
767 ;;; {Loading by paths}
770 ;;; Load a Scheme source file named NAME, searching for it in the
771 ;;; directories listed in %load-path, and applying each of the file
772 ;;; name extensions listed in %load-extensions.
773 (define (load-from-path name)
774 (start-stack 'load-stack
775 (primitive-load-path name)))
780 ;;; {Transcendental Functions}
782 ;;; Derived from "Transcen.scm", Complex trancendental functions for SCM.
783 ;;; Written by Jerry D. Hedden, (C) FSF.
784 ;;; See the file `COPYING' for terms applying to this program.
788 (if (real? z) ($exp z)
789 (make-polar ($exp (real-part z)) (imag-part z))))
792 (if (and (real? z) (>= z 0))
794 (make-rectangular ($log (magnitude z)) (angle z))))
798 (if (negative? z) (make-rectangular 0 ($sqrt (- z)))
800 (make-polar ($sqrt (magnitude z)) (/ (angle z) 2))))
803 (let ((integer-expt integer-expt))
805 (cond ((and (exact? z2) (integer? z2))
806 (integer-expt z1 z2))
807 ((and (real? z2) (real? z1) (>= z1 0))
810 (exp (* z2 (log z1))))))))
813 (if (real? z) ($sinh z)
814 (let ((x (real-part z)) (y (imag-part z)))
815 (make-rectangular (* ($sinh x) ($cos y))
816 (* ($cosh x) ($sin y))))))
818 (if (real? z) ($cosh z)
819 (let ((x (real-part z)) (y (imag-part z)))
820 (make-rectangular (* ($cosh x) ($cos y))
821 (* ($sinh x) ($sin y))))))
823 (if (real? z) ($tanh z)
824 (let* ((x (* 2 (real-part z)))
825 (y (* 2 (imag-part z)))
826 (w (+ ($cosh x) ($cos y))))
827 (make-rectangular (/ ($sinh x) w) (/ ($sin y) w)))))
830 (if (real? z) ($asinh z)
831 (log (+ z (sqrt (+ (* z z) 1))))))
834 (if (and (real? z) (>= z 1))
836 (log (+ z (sqrt (- (* z z) 1))))))
839 (if (and (real? z) (> z -1) (< z 1))
841 (/ (log (/ (+ 1 z) (- 1 z))) 2)))
844 (if (real? z) ($sin z)
845 (let ((x (real-part z)) (y (imag-part z)))
846 (make-rectangular (* ($sin x) ($cosh y))
847 (* ($cos x) ($sinh y))))))
849 (if (real? z) ($cos z)
850 (let ((x (real-part z)) (y (imag-part z)))
851 (make-rectangular (* ($cos x) ($cosh y))
852 (- (* ($sin x) ($sinh y)))))))
854 (if (real? z) ($tan z)
855 (let* ((x (* 2 (real-part z)))
856 (y (* 2 (imag-part z)))
857 (w (+ ($cos x) ($cosh y))))
858 (make-rectangular (/ ($sin x) w) (/ ($sinh y) w)))))
861 (if (and (real? z) (>= z -1) (<= z 1))
863 (* -i (asinh (* +i z)))))
866 (if (and (real? z) (>= z -1) (<= z 1))
868 (+ (/ (angle -1) 2) (* +i (asinh (* +i z))))))
872 (if (real? z) ($atan z)
873 (/ (log (/ (- +i z) (+ +i z))) +2i))
877 (/ (log arg) (log 10)))
881 ;;; {Reader Extensions}
883 ;;; Reader code for various "#c" forms.
886 (read-hash-extend #\' (lambda (c port)
889 (define read-eval? (make-fluid))
890 (fluid-set! read-eval? #f)
891 (read-hash-extend #\.
893 (if (fluid-ref read-eval?)
894 (eval (read port) (interaction-environment))
896 "#. read expansion found and read-eval? is #f."))))
900 ;;; {Command Line Options}
903 (define (get-option argv kw-opts kw-args return)
908 ((or (not (eq? #\- (string-ref (car argv) 0)))
909 (eq? (string-length (car argv)) 1))
910 (return 'normal-arg (car argv) (cdr argv)))
912 ((eq? #\- (string-ref (car argv) 1))
913 (let* ((kw-arg-pos (or (string-index (car argv) #\=)
914 (string-length (car argv))))
915 (kw (symbol->keyword (substring (car argv) 2 kw-arg-pos)))
916 (kw-opt? (member kw kw-opts))
917 (kw-arg? (member kw kw-args))
918 (arg (or (and (not (eq? kw-arg-pos (string-length (car argv))))
919 (substring (car argv)
921 (string-length (car argv))))
923 (begin (set! argv (cdr argv)) (car argv))))))
924 (if (or kw-opt? kw-arg?)
925 (return kw arg (cdr argv))
926 (return 'usage-error kw (cdr argv)))))
929 (let* ((char (substring (car argv) 1 2))
930 (kw (symbol->keyword char)))
934 (let* ((rest-car (substring (car argv) 2 (string-length (car argv))))
935 (new-argv (if (= 0 (string-length rest-car))
937 (cons (string-append "-" rest-car) (cdr argv)))))
938 (return kw #f new-argv)))
941 (let* ((rest-car (substring (car argv) 2 (string-length (car argv))))
942 (arg (if (= 0 (string-length rest-car))
945 (new-argv (if (= 0 (string-length rest-car))
948 (return kw arg new-argv)))
950 (else (return 'usage-error kw argv)))))))
952 (define (for-next-option proc argv kw-opts kw-args)
953 (let loop ((argv argv))
954 (get-option argv kw-opts kw-args
955 (lambda (opt opt-arg argv)
956 (and opt (proc opt opt-arg argv loop))))))
958 (define (display-usage-report kw-desc)
961 (or (eq? (car kw) #t)
964 (help (cadr opt-desc))
965 (opts (car opt-desc))
966 (opts-proper (if (string? (car opts)) (cdr opts) opts))
967 (arg-name (if (string? (car opts))
968 (string-append "<" (car opts) ">")
970 (left-part (string-append
971 (with-output-to-string
973 (map (lambda (x) (display (keyword->symbol x)) (display " "))
976 (middle-part (if (and (< (string-length left-part) 30)
977 (< (string-length help) 40))
978 (make-string (- 30 (string-length left-part)) #\ )
981 (display middle-part)
988 (define (transform-usage-lambda cases)
989 (let* ((raw-usage (delq! 'else (map car cases)))
990 (usage-sans-specials (map (lambda (x)
991 (or (and (not (list? x)) x)
992 (and (symbol? (car x)) #t)
993 (and (boolean? (car x)) #t)
996 (usage-desc (delq! #t usage-sans-specials))
997 (kw-desc (map car usage-desc))
998 (kw-opts (apply append (map (lambda (x) (and (not (string? (car x))) x)) kw-desc)))
999 (kw-args (apply append (map (lambda (x) (and (string? (car x)) (cdr x))) kw-desc)))
1000 (transmogrified-cases (map (lambda (case)
1001 (cons (let ((opts (car case)))
1002 (if (or (boolean? opts) (eq? 'else opts))
1005 ((symbol? (car opts)) opts)
1006 ((boolean? (car opts)) opts)
1007 ((string? (caar opts)) (cdar opts))
1008 (else (car opts)))))
1011 `(let ((%display-usage (lambda () (display-usage-report ',usage-desc))))
1013 (let %next-arg ((%argv %argv))
1017 (lambda (%opt %arg %new-argv)
1019 ,@ transmogrified-cases))))))))
1024 ;;; {Low Level Modules}
1026 ;;; These are the low level data structures for modules.
1028 ;;; Every module object is of the type 'module-type', which is a record
1029 ;;; consisting of the following members:
1031 ;;; - eval-closure: the function that defines for its module the strategy that
1032 ;;; shall be followed when looking up symbols in the module.
1034 ;;; An eval-closure is a function taking two arguments: the symbol to be
1035 ;;; looked up and a boolean value telling whether a binding for the symbol
1036 ;;; should be created if it does not exist yet. If the symbol lookup
1037 ;;; succeeded (either because an existing binding was found or because a new
1038 ;;; binding was created), a variable object representing the binding is
1039 ;;; returned. Otherwise, the value #f is returned. Note that the eval
1040 ;;; closure does not take the module to be searched as an argument: During
1041 ;;; construction of the eval-closure, the eval-closure has to store the
1042 ;;; module it belongs to in its environment. This means, that any
1043 ;;; eval-closure can belong to only one module.
1045 ;;; The eval-closure of a module can be defined arbitrarily. However, three
1046 ;;; special cases of eval-closures are to be distinguished: During startup
1047 ;;; the module system is not yet activated. In this phase, no modules are
1048 ;;; defined and all bindings are automatically stored by the system in the
1049 ;;; pre-modules-obarray. Since no eval-closures exist at this time, the
1050 ;;; functions which require an eval-closure as their argument need to be
1051 ;;; passed the value #f.
1053 ;;; The other two special cases of eval-closures are the
1054 ;;; standard-eval-closure and the standard-interface-eval-closure. Both
1055 ;;; behave equally for the case that no new binding is to be created. The
1056 ;;; difference between the two comes in, when the boolean argument to the
1057 ;;; eval-closure indicates that a new binding shall be created if it is not
1060 ;;; Given that no new binding shall be created, both standard eval-closures
1061 ;;; define the following standard strategy of searching bindings in the
1062 ;;; module: First, the module's obarray is searched for the symbol. Second,
1063 ;;; if no binding for the symbol was found in the module's obarray, the
1064 ;;; module's binder procedure is exececuted. If this procedure did not
1065 ;;; return a binding for the symbol, the modules referenced in the module's
1066 ;;; uses list are recursively searched for a binding of the symbol. If the
1067 ;;; binding can not be found in these modules also, the symbol lookup has
1070 ;;; If a new binding shall be created, the standard-interface-eval-closure
1071 ;;; immediately returns indicating failure. That is, it does not even try
1072 ;;; to look up the symbol. In contrast, the standard-eval-closure would
1073 ;;; first search the obarray, and if no binding was found there, would
1074 ;;; create a new binding in the obarray, therefore not calling the binder
1075 ;;; procedure or searching the modules in the uses list.
1077 ;;; The explanation of the following members obarray, binder and uses
1078 ;;; assumes that the symbol lookup follows the strategy that is defined in
1079 ;;; the standard-eval-closure and the standard-interface-eval-closure.
1081 ;;; - obarray: a hash table that maps symbols to variable objects. In this
1082 ;;; hash table, the definitions are found that are local to the module (that
1083 ;;; is, not imported from other modules). When looking up bindings in the
1084 ;;; module, this hash table is searched first.
1086 ;;; - binder: either #f or a function taking a module and a symbol argument.
1087 ;;; If it is a function it is called after the obarray has been
1088 ;;; unsuccessfully searched for a binding. It then can provide bindings
1089 ;;; that would otherwise not be found locally in the module.
1091 ;;; - uses: a list of modules from which non-local bindings can be inherited.
1092 ;;; These modules are the third place queried for bindings after the obarray
1093 ;;; has been unsuccessfully searched and the binder function did not deliver
1094 ;;; a result either.
1096 ;;; - transformer: either #f or a function taking a scheme expression as
1097 ;;; delivered by read. If it is a function, it will be called to perform
1098 ;;; syntax transformations (e. g. makro expansion) on the given scheme
1099 ;;; expression. The output of the transformer function will then be passed
1100 ;;; to Guile's internal memoizer. This means that the output must be valid
1101 ;;; scheme code. The only exception is, that the output may make use of the
1102 ;;; syntax extensions provided to identify the modules that a binding
1105 ;;; - name: the name of the module. This is used for all kinds of printing
1106 ;;; outputs. In certain places the module name also serves as a way of
1107 ;;; identification. When adding a module to the uses list of another
1108 ;;; module, it is made sure that the new uses list will not contain two
1109 ;;; modules of the same name.
1111 ;;; - kind: classification of the kind of module. The value is (currently?)
1112 ;;; only used for printing. It has no influence on how a module is treated.
1113 ;;; Currently the following values are used when setting the module kind:
1114 ;;; 'module, 'directory, 'interface, 'custom-interface. If no explicit kind
1115 ;;; is set, it defaults to 'module.
1117 ;;; - duplicates-handlers
1119 ;;; - duplicates-interface
1123 ;;; - weak-observers
1127 ;;; In addition, the module may (must?) contain a binding for
1128 ;;; %module-public-interface... More explanations here...
1130 ;;; !!! warning: The interface to lazy binder procedures is going
1131 ;;; to be changed in an incompatible way to permit all the basic
1132 ;;; module ops to be virtualized.
1134 ;;; (make-module size use-list lazy-binding-proc) => module
1135 ;;; module-{obarray,uses,binder}[|-set!]
1136 ;;; (module? obj) => [#t|#f]
1137 ;;; (module-locally-bound? module symbol) => [#t|#f]
1138 ;;; (module-bound? module symbol) => [#t|#f]
1139 ;;; (module-symbol-locally-interned? module symbol) => [#t|#f]
1140 ;;; (module-symbol-interned? module symbol) => [#t|#f]
1141 ;;; (module-local-variable module symbol) => [#<variable ...> | #f]
1142 ;;; (module-variable module symbol) => [#<variable ...> | #f]
1143 ;;; (module-symbol-binding module symbol opt-value)
1144 ;;; => [ <obj> | opt-value | an error occurs ]
1145 ;;; (module-make-local-var! module symbol) => #<variable...>
1146 ;;; (module-add! module symbol var) => unspecified
1147 ;;; (module-remove! module symbol) => unspecified
1148 ;;; (module-for-each proc module) => unspecified
1149 ;;; (make-scm-module) => module ; a lazy copy of the symhash module
1150 ;;; (set-current-module module) => unspecified
1151 ;;; (current-module) => #<module...>
1157 ;;; {Printing Modules}
1160 ;; This is how modules are printed. You can re-define it.
1161 ;; (Redefining is actually more complicated than simply redefining
1162 ;; %print-module because that would only change the binding and not
1163 ;; the value stored in the vtable that determines how record are
1166 (define (%print-module mod port) ; unused args: depth length style table)
1168 (display (or (module-kind mod) "module") port)
1169 (let ((name (module-name mod)))
1173 (display name port))))
1175 (display (number->string (object-address mod) 16) port)
1180 ;; A module is characterized by an obarray in which local symbols
1181 ;; are interned, a list of modules, "uses", from which non-local
1182 ;; bindings can be inherited, and an optional lazy-binder which
1183 ;; is a (CLOSURE module symbol) which, as a last resort, can provide
1184 ;; bindings that would otherwise not be found locally in the module.
1186 ;; NOTE: If you change anything here, you also need to change
1187 ;; libguile/modules.h.
1190 (make-record-type 'module
1191 '(obarray uses binder eval-closure transformer name kind
1192 duplicates-handlers duplicates-interface
1193 observers weak-observers observer-id)
1196 ;; make-module &opt size uses binder
1198 ;; Create a new module, perhaps with a particular size of obarray,
1199 ;; initial uses list, or binding procedure.
1204 (define (parse-arg index default)
1205 (if (> (length args) index)
1206 (list-ref args index)
1209 (if (> (length args) 3)
1210 (error "Too many args to make-module." args))
1212 (let ((size (parse-arg 0 31))
1213 (uses (parse-arg 1 '()))
1214 (binder (parse-arg 2 #f)))
1216 (if (not (integer? size))
1217 (error "Illegal size to make-module." size))
1218 (if (not (and (list? uses)
1219 (and-map module? uses)))
1220 (error "Incorrect use list." uses))
1221 (if (and binder (not (procedure? binder)))
1223 "Lazy-binder expected to be a procedure or #f." binder))
1225 (let ((module (module-constructor (make-hash-table size)
1226 uses binder #f #f #f #f #f #f
1228 (make-weak-value-hash-table 31)
1231 ;; We can't pass this as an argument to module-constructor,
1232 ;; because we need it to close over a pointer to the module
1234 (set-module-eval-closure! module (standard-eval-closure module))
1238 (define module-constructor (record-constructor module-type))
1239 (define module-obarray (record-accessor module-type 'obarray))
1240 (define set-module-obarray! (record-modifier module-type 'obarray))
1241 (define module-uses (record-accessor module-type 'uses))
1242 (define set-module-uses! (record-modifier module-type 'uses))
1243 (define module-binder (record-accessor module-type 'binder))
1244 (define set-module-binder! (record-modifier module-type 'binder))
1246 ;; NOTE: This binding is used in libguile/modules.c.
1247 (define module-eval-closure (record-accessor module-type 'eval-closure))
1249 (define module-transformer (record-accessor module-type 'transformer))
1250 (define set-module-transformer! (record-modifier module-type 'transformer))
1251 (define module-name (record-accessor module-type 'name))
1252 (define set-module-name! (record-modifier module-type 'name))
1253 (define module-kind (record-accessor module-type 'kind))
1254 (define set-module-kind! (record-modifier module-type 'kind))
1255 (define module-duplicates-handlers
1256 (record-accessor module-type 'duplicates-handlers))
1257 (define set-module-duplicates-handlers!
1258 (record-modifier module-type 'duplicates-handlers))
1259 (define module-duplicates-interface
1260 (record-accessor module-type 'duplicates-interface))
1261 (define set-module-duplicates-interface!
1262 (record-modifier module-type 'duplicates-interface))
1263 (define module-observers (record-accessor module-type 'observers))
1264 (define set-module-observers! (record-modifier module-type 'observers))
1265 (define module-weak-observers (record-accessor module-type 'weak-observers))
1266 (define module-observer-id (record-accessor module-type 'observer-id))
1267 (define set-module-observer-id! (record-modifier module-type 'observer-id))
1268 (define module? (record-predicate module-type))
1270 (define set-module-eval-closure!
1271 (let ((setter (record-modifier module-type 'eval-closure)))
1272 (lambda (module closure)
1273 (setter module closure)
1274 ;; Make it possible to lookup the module from the environment.
1275 ;; This implementation is correct since an eval closure can belong
1276 ;; to maximally one module.
1277 (set-procedure-property! closure 'module module))))
1281 ;;; {Observer protocol}
1284 (define (module-observe module proc)
1285 (set-module-observers! module (cons proc (module-observers module)))
1288 (define (module-observe-weak module proc)
1289 (let ((id (module-observer-id module)))
1290 (hash-set! (module-weak-observers module) id proc)
1291 (set-module-observer-id! module (+ 1 id))
1294 (define (module-unobserve token)
1295 (let ((module (car token))
1298 (hash-remove! (module-weak-observers module) id)
1299 (set-module-observers! module (delq1! id (module-observers module)))))
1302 (define module-defer-observers #f)
1303 (define module-defer-observers-mutex (make-mutex))
1304 (define module-defer-observers-table (make-hash-table))
1306 (define (module-modified m)
1307 (if module-defer-observers
1308 (hash-set! module-defer-observers-table m #t)
1309 (module-call-observers m)))
1311 ;;; This function can be used to delay calls to observers so that they
1312 ;;; can be called once only in the face of massive updating of modules.
1314 (define (call-with-deferred-observers thunk)
1317 (lock-mutex module-defer-observers-mutex)
1318 (set! module-defer-observers #t))
1321 (set! module-defer-observers #f)
1322 (hash-for-each (lambda (m dummy)
1323 (module-call-observers m))
1324 module-defer-observers-table)
1325 (hash-clear! module-defer-observers-table)
1326 (unlock-mutex module-defer-observers-mutex))))
1328 (define (module-call-observers m)
1329 (for-each (lambda (proc) (proc m)) (module-observers m))
1330 (hash-fold (lambda (id proc res) (proc m)) #f (module-weak-observers m)))
1334 ;;; {Module Searching in General}
1336 ;;; We sometimes want to look for properties of a symbol
1337 ;;; just within the obarray of one module. If the property
1338 ;;; holds, then it is said to hold ``locally'' as in, ``The symbol
1339 ;;; DISPLAY is locally rebound in the module `safe-guile'.''
1342 ;;; Other times, we want to test for a symbol property in the obarray
1343 ;;; of M and, if it is not found there, try each of the modules in the
1344 ;;; uses list of M. This is the normal way of testing for some
1345 ;;; property, so we state these properties without qualification as
1346 ;;; in: ``The symbol 'fnord is interned in module M because it is
1347 ;;; interned locally in module M2 which is a member of the uses list
1351 ;; module-search fn m
1353 ;; return the first non-#f result of FN applied to M and then to
1354 ;; the modules in the uses of m, and so on recursively. If all applications
1355 ;; return #f, then so does this function.
1357 (define (module-search fn m v)
1360 (or (module-search fn (car pos) v)
1363 (loop (module-uses m))))
1366 ;;; {Is a symbol bound in a module?}
1368 ;;; Symbol S in Module M is bound if S is interned in M and if the binding
1369 ;;; of S in M has been set to some well-defined value.
1372 ;; module-locally-bound? module symbol
1374 ;; Is a symbol bound (interned and defined) locally in a given module?
1376 (define (module-locally-bound? m v)
1377 (let ((var (module-local-variable m v)))
1379 (variable-bound? var))))
1381 ;; module-bound? module symbol
1383 ;; Is a symbol bound (interned and defined) anywhere in a given module
1386 (define (module-bound? m v)
1387 (module-search module-locally-bound? m v))
1389 ;;; {Is a symbol interned in a module?}
1391 ;;; Symbol S in Module M is interned if S occurs in
1392 ;;; of S in M has been set to some well-defined value.
1394 ;;; It is possible to intern a symbol in a module without providing
1395 ;;; an initial binding for the corresponding variable. This is done
1397 ;;; (module-add! module symbol (make-undefined-variable))
1399 ;;; In that case, the symbol is interned in the module, but not
1400 ;;; bound there. The unbound symbol shadows any binding for that
1401 ;;; symbol that might otherwise be inherited from a member of the uses list.
1404 (define (module-obarray-get-handle ob key)
1405 ((if (symbol? key) hashq-get-handle hash-get-handle) ob key))
1407 (define (module-obarray-ref ob key)
1408 ((if (symbol? key) hashq-ref hash-ref) ob key))
1410 (define (module-obarray-set! ob key val)
1411 ((if (symbol? key) hashq-set! hash-set!) ob key val))
1413 (define (module-obarray-remove! ob key)
1414 ((if (symbol? key) hashq-remove! hash-remove!) ob key))
1416 ;; module-symbol-locally-interned? module symbol
1418 ;; is a symbol interned (not neccessarily defined) locally in a given module
1419 ;; or its uses? Interned symbols shadow inherited bindings even if
1420 ;; they are not themselves bound to a defined value.
1422 (define (module-symbol-locally-interned? m v)
1423 (not (not (module-obarray-get-handle (module-obarray m) v))))
1425 ;; module-symbol-interned? module symbol
1427 ;; is a symbol interned (not neccessarily defined) anywhere in a given module
1428 ;; or its uses? Interned symbols shadow inherited bindings even if
1429 ;; they are not themselves bound to a defined value.
1431 (define (module-symbol-interned? m v)
1432 (module-search module-symbol-locally-interned? m v))
1435 ;;; {Mapping modules x symbols --> variables}
1438 ;; module-local-variable module symbol
1439 ;; return the local variable associated with a MODULE and SYMBOL.
1441 ;;; This function is very important. It is the only function that can
1442 ;;; return a variable from a module other than the mutators that store
1443 ;;; new variables in modules. Therefore, this function is the location
1444 ;;; of the "lazy binder" hack.
1446 ;;; If symbol is defined in MODULE, and if the definition binds symbol
1447 ;;; to a variable, return that variable object.
1449 ;;; If the symbols is not found at first, but the module has a lazy binder,
1450 ;;; then try the binder.
1452 ;;; If the symbol is not found at all, return #f.
1454 (define (module-local-variable m v)
1457 (let ((b (module-obarray-ref (module-obarray m) v)))
1458 (or (and (variable? b) b)
1459 (and (module-binder m)
1460 ((module-binder m) m v #f)))))
1463 ;; module-variable module symbol
1465 ;; like module-local-variable, except search the uses in the
1466 ;; case V is not found in M.
1468 ;; NOTE: This function is superseded with C code (see modules.c)
1469 ;;; when using the standard eval closure.
1471 (define (module-variable m v)
1472 (module-search module-local-variable m v))
1475 ;;; {Mapping modules x symbols --> bindings}
1477 ;;; These are similar to the mapping to variables, except that the
1478 ;;; variable is dereferenced.
1481 ;; module-symbol-binding module symbol opt-value
1483 ;; return the binding of a variable specified by name within
1484 ;; a given module, signalling an error if the variable is unbound.
1485 ;; If the OPT-VALUE is passed, then instead of signalling an error,
1486 ;; return OPT-VALUE.
1488 (define (module-symbol-local-binding m v . opt-val)
1489 (let ((var (module-local-variable m v)))
1490 (if (and var (variable-bound? var))
1492 (if (not (null? opt-val))
1494 (error "Locally unbound variable." v)))))
1496 ;; module-symbol-binding module symbol opt-value
1498 ;; return the binding of a variable specified by name within
1499 ;; a given module, signalling an error if the variable is unbound.
1500 ;; If the OPT-VALUE is passed, then instead of signalling an error,
1501 ;; return OPT-VALUE.
1503 (define (module-symbol-binding m v . opt-val)
1504 (let ((var (module-variable m v)))
1505 (if (and var (variable-bound? var))
1507 (if (not (null? opt-val))
1509 (error "Unbound variable." v)))))
1514 ;;; {Adding Variables to Modules}
1517 ;; module-make-local-var! module symbol
1519 ;; ensure a variable for V in the local namespace of M.
1520 ;; If no variable was already there, then create a new and uninitialzied
1523 ;; This function is used in modules.c.
1525 (define (module-make-local-var! m v)
1526 (or (let ((b (module-obarray-ref (module-obarray m) v)))
1529 ;; Mark as modified since this function is called when
1530 ;; the standard eval closure defines a binding
1534 ;; No local variable yet, so we need to create a new one. That
1535 ;; new variable is initialized with the old imported value of V,
1537 (let ((imported-var (module-variable m v))
1538 (local-var (or (and (module-binder m)
1539 ((module-binder m) m v #t))
1541 (let ((answer (make-undefined-variable)))
1542 (module-add! m v answer)
1544 (if (and imported-var (not (variable-bound? local-var)))
1545 (variable-set! local-var (variable-ref imported-var)))
1548 ;; module-ensure-local-variable! module symbol
1550 ;; Ensure that there is a local variable in MODULE for SYMBOL. If
1551 ;; there is no binding for SYMBOL, create a new uninitialized
1552 ;; variable. Return the local variable.
1554 (define (module-ensure-local-variable! module symbol)
1555 (or (module-local-variable module symbol)
1556 (let ((var (make-undefined-variable)))
1557 (module-add! module symbol var)
1560 ;; module-add! module symbol var
1562 ;; ensure a particular variable for V in the local namespace of M.
1564 (define (module-add! m v var)
1565 (if (not (variable? var))
1566 (error "Bad variable to module-add!" var))
1567 (module-obarray-set! (module-obarray m) v var)
1568 (module-modified m))
1572 ;; make sure that a symbol is undefined in the local namespace of M.
1574 (define (module-remove! m v)
1575 (module-obarray-remove! (module-obarray m) v)
1576 (module-modified m))
1578 (define (module-clear! m)
1579 (hash-clear! (module-obarray m))
1580 (module-modified m))
1582 ;; MODULE-FOR-EACH -- exported
1584 ;; Call PROC on each symbol in MODULE, with arguments of (SYMBOL VARIABLE).
1586 (define (module-for-each proc module)
1587 (hash-for-each proc (module-obarray module)))
1589 (define (module-map proc module)
1590 (hash-map->list proc (module-obarray module)))
1594 ;;; {Low Level Bootstrapping}
1599 ;; A root module uses the pre-modules-obarray as its obarray. This
1600 ;; special obarray accumulates all bindings that have been established
1601 ;; before the module system is fully booted.
1603 ;; (The obarray continues to be used by code that has been closed over
1604 ;; before the module system has been booted.)
1606 (define (make-root-module)
1607 (let ((m (make-module 0)))
1608 (set-module-obarray! m (%get-pre-modules-obarray))
1613 ;; The root interface is a module that uses the same obarray as the
1614 ;; root module. It does not allow new definitions, tho.
1616 (define (make-scm-module)
1617 (let ((m (make-module 0)))
1618 (set-module-obarray! m (%get-pre-modules-obarray))
1619 (set-module-eval-closure! m (standard-interface-eval-closure m))
1625 ;;; {Module-based Loading}
1628 (define (save-module-excursion thunk)
1629 (let ((inner-module (current-module))
1631 (dynamic-wind (lambda ()
1632 (set! outer-module (current-module))
1633 (set-current-module inner-module)
1634 (set! inner-module #f))
1637 (set! inner-module (current-module))
1638 (set-current-module outer-module)
1639 (set! outer-module #f)))))
1641 (define basic-load load)
1643 (define (load-module filename)
1644 (save-module-excursion
1646 (let ((oldname (and (current-load-port)
1647 (port-filename (current-load-port)))))
1648 (basic-load (if (and oldname
1649 (> (string-length filename) 0)
1650 (not (char=? (string-ref filename 0) #\/))
1651 (not (string=? (dirname oldname) ".")))
1652 (string-append (dirname oldname) "/" filename)
1658 ;;; {MODULE-REF -- exported}
1661 ;; Returns the value of a variable called NAME in MODULE or any of its
1662 ;; used modules. If there is no such variable, then if the optional third
1663 ;; argument DEFAULT is present, it is returned; otherwise an error is signaled.
1665 (define (module-ref module name . rest)
1666 (let ((variable (module-variable module name)))
1667 (if (and variable (variable-bound? variable))
1668 (variable-ref variable)
1670 (error "No variable named" name 'in module)
1671 (car rest) ; default value
1674 ;; MODULE-SET! -- exported
1676 ;; Sets the variable called NAME in MODULE (or in a module that MODULE uses)
1677 ;; to VALUE; if there is no such variable, an error is signaled.
1679 (define (module-set! module name value)
1680 (let ((variable (module-variable module name)))
1682 (variable-set! variable value)
1683 (error "No variable named" name 'in module))))
1685 ;; MODULE-DEFINE! -- exported
1687 ;; Sets the variable called NAME in MODULE to VALUE; if there is no such
1688 ;; variable, it is added first.
1690 (define (module-define! module name value)
1691 (let ((variable (module-local-variable module name)))
1694 (variable-set! variable value)
1695 (module-modified module))
1696 (let ((variable (make-variable value)))
1697 (module-add! module name variable)))))
1699 ;; MODULE-DEFINED? -- exported
1701 ;; Return #t iff NAME is defined in MODULE (or in a module that MODULE
1704 (define (module-defined? module name)
1705 (let ((variable (module-variable module name)))
1706 (and variable (variable-bound? variable))))
1708 ;; MODULE-USE! module interface
1710 ;; Add INTERFACE to the list of interfaces used by MODULE.
1712 (define (module-use! module interface)
1713 (set-module-uses! module
1716 (not (equal? (module-name m)
1717 (module-name interface))))
1718 (module-uses module))))
1719 (module-modified module))
1721 ;; MODULE-USE-INTERFACES! module interfaces
1723 ;; Same as MODULE-USE! but add multiple interfaces and check for duplicates
1725 (define (module-use-interfaces! module interfaces)
1726 (let* ((duplicates-handlers? (or (module-duplicates-handlers module)
1727 (default-duplicate-binding-procedures)))
1728 (uses (module-uses module)))
1729 ;; remove duplicates-interface
1730 (set! uses (delq! (module-duplicates-interface module) uses))
1731 ;; remove interfaces to be added
1732 (for-each (lambda (interface)
1735 (not (equal? (module-name m)
1736 (module-name interface))))
1739 ;; add interfaces to use list
1740 (set-module-uses! module uses)
1741 (for-each (lambda (interface)
1742 (and duplicates-handlers?
1743 ;; perform duplicate checking
1744 (process-duplicates module interface))
1745 (set! uses (cons interface uses))
1746 (set-module-uses! module uses))
1748 ;; add duplicates interface
1749 (if (module-duplicates-interface module)
1750 (set-module-uses! module
1751 (cons (module-duplicates-interface module) uses)))
1752 (module-modified module)))
1756 ;;; {Recursive Namespaces}
1758 ;;; A hierarchical namespace emerges if we consider some module to be
1759 ;;; root, and variables bound to modules as nested namespaces.
1761 ;;; The routines in this file manage variable names in hierarchical namespace.
1762 ;;; Each variable name is a list of elements, looked up in successively nested
1765 ;;; (nested-ref some-root-module '(foo bar baz))
1766 ;;; => <value of a variable named baz in the module bound to bar in
1767 ;;; the module bound to foo in some-root-module>
1772 ;;; ;; a-root is a module
1773 ;;; ;; name is a list of symbols
1775 ;;; nested-ref a-root name
1776 ;;; nested-set! a-root name val
1777 ;;; nested-define! a-root name val
1778 ;;; nested-remove! a-root name
1781 ;;; (current-module) is a natural choice for a-root so for convenience there are
1784 ;;; local-ref name == nested-ref (current-module) name
1785 ;;; local-set! name val == nested-set! (current-module) name val
1786 ;;; local-define! name val == nested-define! (current-module) name val
1787 ;;; local-remove! name == nested-remove! (current-module) name
1791 (define (nested-ref root names)
1792 (let loop ((cur root)
1796 ((not (module? cur)) #f)
1797 (else (loop (module-ref cur (car elts) #f) (cdr elts))))))
1799 (define (nested-set! root names val)
1800 (let loop ((cur root)
1802 (if (null? (cdr elts))
1803 (module-set! cur (car elts) val)
1804 (loop (module-ref cur (car elts)) (cdr elts)))))
1806 (define (nested-define! root names val)
1807 (let loop ((cur root)
1809 (if (null? (cdr elts))
1810 (module-define! cur (car elts) val)
1811 (loop (module-ref cur (car elts)) (cdr elts)))))
1813 (define (nested-remove! root names)
1814 (let loop ((cur root)
1816 (if (null? (cdr elts))
1817 (module-remove! cur (car elts))
1818 (loop (module-ref cur (car elts)) (cdr elts)))))
1820 (define (local-ref names) (nested-ref (current-module) names))
1821 (define (local-set! names val) (nested-set! (current-module) names val))
1822 (define (local-define names val) (nested-define! (current-module) names val))
1823 (define (local-remove names) (nested-remove! (current-module) names))
1828 ;;; {The (%app) module}
1830 ;;; The root of conventionally named objects not directly in the top level.
1833 ;;; (%app modules guile)
1835 ;;; The directory of all modules and the standard root module.
1838 (define (module-public-interface m)
1839 (module-ref m '%module-public-interface #f))
1840 (define (set-module-public-interface! m i)
1841 (module-define! m '%module-public-interface i))
1842 (define (set-system-module! m s)
1843 (set-procedure-property! (module-eval-closure m) 'system-module s))
1844 (define the-root-module (make-root-module))
1845 (define the-scm-module (make-scm-module))
1846 (set-module-public-interface! the-root-module the-scm-module)
1847 (set-module-name! the-root-module '(guile))
1848 (set-module-name! the-scm-module '(guile))
1849 (set-module-kind! the-scm-module 'interface)
1850 (for-each set-system-module! (list the-root-module the-scm-module) '(#t #t))
1852 ;; NOTE: This binding is used in libguile/modules.c.
1854 (define (make-modules-in module name)
1858 ((module-ref module (car name) #f)
1859 => (lambda (m) (make-modules-in m (cdr name))))
1860 (else (let ((m (make-module 31)))
1861 (set-module-kind! m 'directory)
1862 (set-module-name! m (append (or (module-name module)
1865 (module-define! module (car name) m)
1866 (make-modules-in m (cdr name)))))))
1868 (define (beautify-user-module! module)
1869 (let ((interface (module-public-interface module)))
1870 (if (or (not interface)
1871 (eq? interface module))
1872 (let ((interface (make-module 31)))
1873 (set-module-name! interface (module-name module))
1874 (set-module-kind! interface 'interface)
1875 (set-module-public-interface! module interface))))
1876 (if (and (not (memq the-scm-module (module-uses module)))
1877 (not (eq? module the-root-module)))
1878 (set-module-uses! module
1879 (append (module-uses module) (list the-scm-module)))))
1881 ;; NOTE: This binding is used in libguile/modules.c.
1883 (define (resolve-module name . maybe-autoload)
1884 (let ((full-name (append '(%app modules) name)))
1885 (let ((already (nested-ref the-root-module full-name)))
1887 ;; The module already exists...
1888 (if (and (or (null? maybe-autoload) (car maybe-autoload))
1889 (not (module-public-interface already)))
1890 ;; ...but we are told to load and it doesn't contain source, so
1892 (try-load-module name)
1894 ;; simply return it.
1897 ;; Try to autoload it if we are told so
1898 (if (or (null? maybe-autoload) (car maybe-autoload))
1899 (try-load-module name))
1901 (make-modules-in (current-module) full-name))))))
1903 ;; Cheat. These bindings are needed by modules.c, but we don't want
1904 ;; to move their real definition here because that would be unnatural.
1906 (define try-module-autoload #f)
1907 (define process-define-module #f)
1908 (define process-use-modules #f)
1909 (define module-export! #f)
1911 ;; This boots the module system. All bindings needed by modules.c
1912 ;; must have been defined by now.
1914 (set-current-module the-root-module)
1916 (define %app (make-module 31))
1917 (define app %app) ;; for backwards compatability
1918 (local-define '(%app modules) (make-module 31))
1919 (local-define '(%app modules guile) the-root-module)
1921 ;; (define-special-value '(%app modules new-ws) (lambda () (make-scm-module)))
1923 (define (try-load-module name)
1924 (or (begin-deprecated (try-module-linked name))
1925 (try-module-autoload name)
1926 (begin-deprecated (try-module-dynamic-link name))))
1928 (define (purify-module! module)
1929 "Removes bindings in MODULE which are inherited from the (guile) module."
1930 (let ((use-list (module-uses module)))
1931 (if (and (pair? use-list)
1932 (eq? (car (last-pair use-list)) the-scm-module))
1933 (set-module-uses! module (reverse (cdr (reverse use-list)))))))
1935 ;; Return a module that is an interface to the module designated by
1938 ;; `resolve-interface' takes four keyword arguments:
1940 ;; #:select SELECTION
1942 ;; SELECTION is a list of binding-specs to be imported; A binding-spec
1943 ;; is either a symbol or a pair of symbols (ORIG . SEEN), where ORIG
1944 ;; is the name in the used module and SEEN is the name in the using
1945 ;; module. Note that SEEN is also passed through RENAMER, below. The
1946 ;; default is to select all bindings. If you specify no selection but
1947 ;; a renamer, only the bindings that already exist in the used module
1948 ;; are made available in the interface. Bindings that are added later
1949 ;; are not picked up.
1953 ;; BINDINGS is a list of bindings which should not be imported.
1957 ;; PREFIX is a symbol that will be appended to each exported name.
1958 ;; The default is to not perform any renaming.
1960 ;; #:renamer RENAMER
1962 ;; RENAMER is a procedure that takes a symbol and returns its new
1963 ;; name. The default is not perform any renaming.
1965 ;; Signal "no code for module" error if module name is not resolvable
1966 ;; or its public interface is not available. Signal "no binding"
1967 ;; error if selected binding does not exist in the used module.
1969 (define (resolve-interface name . args)
1971 (define (get-keyword-arg args kw def)
1972 (cond ((memq kw args)
1974 (if (null? (cdr kw-arg))
1975 (error "keyword without value: " kw))
1980 (let* ((select (get-keyword-arg args #:select #f))
1981 (hide (get-keyword-arg args #:hide '()))
1982 (renamer (or (get-keyword-arg args #:renamer #f)
1983 (let ((prefix (get-keyword-arg args #:prefix #f)))
1984 (and prefix (symbol-prefix-proc prefix)))
1986 (module (resolve-module name))
1987 (public-i (and module (module-public-interface module))))
1988 (and (or (not module) (not public-i))
1989 (error "no code for module" name))
1990 (if (and (not select) (null? hide) (eq? renamer identity))
1992 (let ((selection (or select (module-map (lambda (sym var) sym)
1994 (custom-i (make-module 31)))
1995 (set-module-kind! custom-i 'custom-interface)
1996 (set-module-name! custom-i name)
1997 ;; XXX - should use a lazy binder so that changes to the
1998 ;; used module are picked up automatically.
1999 (for-each (lambda (bspec)
2000 (let* ((direct? (symbol? bspec))
2001 (orig (if direct? bspec (car bspec)))
2002 (seen (if direct? bspec (cdr bspec)))
2003 (var (or (module-local-variable public-i orig)
2004 (module-local-variable module orig)
2006 ;; fixme: format manually for now
2008 #f "no binding `~A' in module ~A"
2010 (if (memq orig hide)
2011 (set! hide (delq! orig hide))
2012 (module-add! custom-i
2016 ;; Check that we are not hiding bindings which don't exist
2017 (for-each (lambda (binding)
2018 (if (not (module-local-variable public-i binding))
2021 #f "no binding `~A' to hide in module ~A"
2026 (define (symbol-prefix-proc prefix)
2028 (symbol-append prefix symbol)))
2030 ;; This function is called from "modules.c". If you change it, be
2031 ;; sure to update "modules.c" as well.
2033 (define (process-define-module args)
2034 (let* ((module-id (car args))
2035 (module (resolve-module module-id #f))
2037 (unrecognized (lambda (arg)
2038 (error "unrecognized define-module argument" arg))))
2039 (beautify-user-module! module)
2040 (let loop ((kws kws)
2041 (reversed-interfaces '())
2046 (call-with-deferred-observers
2048 (module-use-interfaces! module (reverse reversed-interfaces))
2049 (module-export! module exports)
2050 (module-replace! module replacements)
2051 (module-re-export! module re-exports)))
2053 ((#:use-module #:use-syntax)
2054 (or (pair? (cdr kws))
2056 (let* ((interface-args (cadr kws))
2057 (interface (apply resolve-interface interface-args)))
2058 (and (eq? (car kws) #:use-syntax)
2059 (or (symbol? (caar interface-args))
2060 (error "invalid module name for use-syntax"
2061 (car interface-args)))
2062 (set-module-transformer!
2064 (module-ref interface
2065 (car (last-pair (car interface-args)))
2068 (cons interface reversed-interfaces)
2073 (or (and (pair? (cdr kws)) (pair? (cddr kws)))
2076 (cons (make-autoload-interface module
2079 reversed-interfaces)
2084 (set-system-module! module #t)
2085 (loop (cdr kws) reversed-interfaces exports re-exports replacements))
2087 (purify-module! module)
2088 (loop (cdr kws) reversed-interfaces exports re-exports replacements))
2090 (if (not (pair? (cdr kws)))
2092 (set-module-duplicates-handlers!
2094 (lookup-duplicates-handlers (cadr kws)))
2095 (loop (cddr kws) reversed-interfaces exports re-exports replacements))
2096 ((#:export #:export-syntax)
2097 (or (pair? (cdr kws))
2101 (append (cadr kws) exports)
2104 ((#:re-export #:re-export-syntax)
2105 (or (pair? (cdr kws))
2110 (append (cadr kws) re-exports)
2112 ((#:replace #:replace-syntax)
2113 (or (pair? (cdr kws))
2119 (append (cadr kws) replacements)))
2121 (unrecognized kws)))))
2122 (run-hook module-defined-hook module)
2125 ;; `module-defined-hook' is a hook that is run whenever a new module
2126 ;; is defined. Its members are called with one argument, the new
2128 (define module-defined-hook (make-hook 1))
2135 (define (make-autoload-interface module name bindings)
2136 (let ((b (lambda (a sym definep)
2137 (and (memq sym bindings)
2138 (let ((i (module-public-interface (resolve-module name))))
2140 (error "missing interface for module" name))
2141 ;; Replace autoload-interface with interface
2142 (set-car! (memq a (module-uses module)) i)
2143 (module-local-variable i sym))))))
2144 (module-constructor (make-hash-table 0) '() b #f #f name 'autoload #f #f
2145 '() (make-weak-value-hash-table 31) 0)))
2147 ;;; {Compiled module}
2149 (define load-compiled #f)
2153 ;;; {Autoloading modules}
2156 (define autoloads-in-progress '())
2158 ;; This function is called from "modules.c". If you change it, be
2159 ;; sure to update "modules.c" as well.
2161 (define (try-module-autoload module-name)
2162 (let* ((reverse-name (reverse module-name))
2163 (name (symbol->string (car reverse-name)))
2164 (dir-hint-module-name (reverse (cdr reverse-name)))
2165 (dir-hint (apply string-append
2167 (string-append (symbol->string elt) "/"))
2168 dir-hint-module-name))))
2169 (resolve-module dir-hint-module-name #f)
2170 (and (not (autoload-done-or-in-progress? dir-hint name))
2172 (define (load-file proc file)
2173 (save-module-excursion (lambda () (proc file)))
2176 (lambda () (autoload-in-progress! dir-hint name))
2178 (let ((file (in-vicinity dir-hint name)))
2179 (cond ((and load-compiled
2180 (%search-load-path (string-append file ".go")))
2182 (load-file load-compiled full)))
2183 ((%search-load-path file)
2185 (load-file primitive-load full))))))
2186 (lambda () (set-autoloaded! dir-hint name didit)))
2191 ;;; {Dynamic linking of modules}
2194 (define autoloads-done '((guile . guile)))
2196 (define (autoload-done-or-in-progress? p m)
2197 (let ((n (cons p m)))
2198 (->bool (or (member n autoloads-done)
2199 (member n autoloads-in-progress)))))
2201 (define (autoload-done! p m)
2202 (let ((n (cons p m)))
2203 (set! autoloads-in-progress
2204 (delete! n autoloads-in-progress))
2205 (or (member n autoloads-done)
2206 (set! autoloads-done (cons n autoloads-done)))))
2208 (define (autoload-in-progress! p m)
2209 (let ((n (cons p m)))
2210 (set! autoloads-done
2211 (delete! n autoloads-done))
2212 (set! autoloads-in-progress (cons n autoloads-in-progress))))
2214 (define (set-autoloaded! p m done?)
2216 (autoload-done! p m)
2217 (let ((n (cons p m)))
2218 (set! autoloads-done (delete! n autoloads-done))
2219 (set! autoloads-in-progress (delete! n autoloads-in-progress)))))
2223 ;;; {Run-time options}
2226 (define define-option-interface
2227 (let* ((option-name car)
2229 (option-documentation caddr)
2231 (print-option (lambda (option)
2232 (display (option-name option))
2233 (if (< (string-length
2234 (symbol->string (option-name option)))
2238 (display (option-value option))
2240 (display (option-documentation option))
2243 ;; Below follow the macros defining the run-time option interfaces.
2245 (make-options (lambda (interface)
2247 (cond ((null? args) (,interface))
2249 (,interface (car args)) (,interface))
2250 (else (for-each ,print-option
2251 (,interface #t)))))))
2253 (make-enable (lambda (interface)
2255 (,interface (append flags (,interface)))
2258 (make-disable (lambda (interface)
2260 (let ((options (,interface)))
2261 (for-each (lambda (flag)
2262 (set! options (delq! flag options)))
2264 (,interface options)
2266 (procedure->memoizing-macro
2268 (let* ((option-group (cadr exp))
2269 (interface (car option-group))
2270 (options/enable/disable (cadr option-group)))
2272 (define ,(car options/enable/disable)
2273 ,(make-options interface))
2274 (define ,(cadr options/enable/disable)
2275 ,(make-enable interface))
2276 (define ,(caddr options/enable/disable)
2277 ,(make-disable interface))
2278 (defmacro ,(caaddr option-group) (opt val)
2279 `(,,(car options/enable/disable)
2280 (append (,,(car options/enable/disable))
2281 (list ',opt ,val))))))))))
2283 (define-option-interface
2284 (eval-options-interface
2285 (eval-options eval-enable eval-disable)
2288 (define-option-interface
2289 (debug-options-interface
2290 (debug-options debug-enable debug-disable)
2293 (define-option-interface
2294 (evaluator-traps-interface
2295 (traps trap-enable trap-disable)
2298 (define-option-interface
2299 (read-options-interface
2300 (read-options read-enable read-disable)
2303 (define-option-interface
2304 (print-options-interface
2305 (print-options print-enable print-disable)
2313 (define (repl read evaler print)
2314 (let loop ((source (read (current-input-port))))
2315 (print (evaler source))
2316 (loop (read (current-input-port)))))
2318 ;; A provisional repl that acts like the SCM repl:
2320 (define scm-repl-silent #f)
2321 (define (assert-repl-silence v) (set! scm-repl-silent v))
2323 (define *unspecified* (if #f #f))
2324 (define (unspecified? v) (eq? v *unspecified*))
2326 (define scm-repl-print-unspecified #f)
2327 (define (assert-repl-print-unspecified v) (set! scm-repl-print-unspecified v))
2329 (define scm-repl-verbose #f)
2330 (define (assert-repl-verbosity v) (set! scm-repl-verbose v))
2332 (define scm-repl-prompt "guile> ")
2334 (define (set-repl-prompt! v) (set! scm-repl-prompt v))
2336 (define (default-lazy-handler key . args)
2337 (save-stack lazy-handler-dispatch)
2338 (apply throw key args))
2340 (define (lazy-handler-dispatch key . args)
2341 (apply default-lazy-handler key args))
2343 (define abort-hook (make-hook))
2345 ;; these definitions are used if running a script.
2346 ;; otherwise redefined in error-catching-loop.
2347 (define (set-batch-mode?! arg) #t)
2348 (define (batch-mode?) #t)
2350 (define (error-catching-loop thunk)
2353 (define (loop first)
2360 (call-with-unblocked-asyncs
2366 ;; This line is needed because mark
2367 ;; doesn't do closures quite right.
2368 ;; Unreferenced locals should be
2372 (let loop ((v (thunk)))
2376 ;; Note that having just
2377 ;; `lazy-handler-dispatch' here is
2378 ;; connected with the mechanism that
2379 ;; produces a nice backtrace upon
2380 ;; error. If, for example, this is
2381 ;; replaced with (lambda args (apply
2382 ;; lazy-handler-dispatch args)), the
2383 ;; stack cutting (in save-stack)
2384 ;; goes wrong and ends up saving no
2385 ;; stack at all, so there is no
2387 lazy-handler-dispatch))
2389 (lambda (key . args)
2396 (apply throw 'switch-repl args))
2399 ;; This is one of the closures that require
2400 ;; (set! first #f) above
2403 (run-hook abort-hook)
2404 (force-output (current-output-port))
2405 (display "ABORT: " (current-error-port))
2406 (write args (current-error-port))
2407 (newline (current-error-port))
2411 (not has-shown-debugger-hint?)
2412 (not (memq 'backtrace
2413 (debug-options-interface)))
2414 (stack? (fluid-ref the-last-stack)))
2416 (newline (current-error-port))
2418 "Type \"(backtrace)\" to get more information or \"(debug)\" to enter the debugger.\n"
2419 (current-error-port))
2420 (set! has-shown-debugger-hint? #t)))
2421 (force-output (current-error-port)))
2423 (primitive-exit 1)))
2424 (set! stack-saved? #f)))
2427 ;; This is the other cons-leak closure...
2429 (cond ((= (length args) 4)
2430 (apply handle-system-error key args))
2432 (apply bad-throw key args))))))))))
2433 (if next (loop next) status)))
2434 (set! set-batch-mode?! (lambda (arg)
2436 (set! interactive #f)
2439 (error "sorry, not implemented")))))
2440 (set! batch-mode? (lambda () (not interactive)))
2441 (call-with-blocked-asyncs
2442 (lambda () (loop (lambda () #t))))))
2444 ;;(define the-last-stack (make-fluid)) Defined by scm_init_backtrace ()
2445 (define before-signal-stack (make-fluid))
2446 (define stack-saved? #f)
2448 (define (save-stack . narrowing)
2450 (cond ((not (memq 'debug (debug-options-interface)))
2451 (fluid-set! the-last-stack #f)
2452 (set! stack-saved? #t))
2458 (apply make-stack #t save-stack primitive-eval #t 0 narrowing))
2460 (apply make-stack #t save-stack 0 #t 0 narrowing))
2462 (apply make-stack #t save-stack tk-stack-mark #t 0 narrowing))
2464 (apply make-stack #t save-stack 0 1 narrowing))
2466 (let ((id (stack-id #t)))
2467 (and (procedure? id)
2468 (apply make-stack #t save-stack id #t 0 narrowing))))))
2469 (set! stack-saved? #t)))))
2471 (define before-error-hook (make-hook))
2472 (define after-error-hook (make-hook))
2473 (define before-backtrace-hook (make-hook))
2474 (define after-backtrace-hook (make-hook))
2476 (define has-shown-debugger-hint? #f)
2478 (define (handle-system-error key . args)
2479 (let ((cep (current-error-port)))
2480 (cond ((not (stack? (fluid-ref the-last-stack))))
2481 ((memq 'backtrace (debug-options-interface))
2482 (let ((highlights (if (or (eq? key 'wrong-type-arg)
2483 (eq? key 'out-of-range))
2486 (run-hook before-backtrace-hook)
2488 (display "Backtrace:\n")
2489 (display-backtrace (fluid-ref the-last-stack) cep
2492 (run-hook after-backtrace-hook))))
2493 (run-hook before-error-hook)
2494 (apply display-error (fluid-ref the-last-stack) cep args)
2495 (run-hook after-error-hook)
2497 (throw 'abort key)))
2499 (define (quit . args)
2500 (apply throw 'quit args))
2504 ;;(define has-shown-backtrace-hint? #f) Defined by scm_init_backtrace ()
2506 ;; Replaced by C code:
2507 ;;(define (backtrace)
2508 ;; (if (fluid-ref the-last-stack)
2511 ;; (display-backtrace (fluid-ref the-last-stack) (current-output-port))
2513 ;; (if (and (not has-shown-backtrace-hint?)
2514 ;; (not (memq 'backtrace (debug-options-interface))))
2517 ;;"Type \"(debug-enable 'backtrace)\" if you would like a backtrace
2518 ;;automatically if an error occurs in the future.\n")
2519 ;; (set! has-shown-backtrace-hint? #t))))
2520 ;; (display "No backtrace available.\n")))
2522 (define (error-catching-repl r e p)
2523 (error-catching-loop
2525 (call-with-values (lambda () (e (r)))
2526 (lambda the-values (for-each p the-values))))))
2528 (define (gc-run-time)
2529 (cdr (assq 'gc-time-taken (gc-stats))))
2531 (define before-read-hook (make-hook))
2532 (define after-read-hook (make-hook))
2533 (define before-eval-hook (make-hook 1))
2534 (define after-eval-hook (make-hook 1))
2535 (define before-print-hook (make-hook 1))
2536 (define after-print-hook (make-hook 1))
2538 ;;; The default repl-reader function. We may override this if we've
2539 ;;; the readline library.
2544 (run-hook before-read-hook)
2545 (read (current-input-port))))
2547 (define (scm-style-repl)
2552 (repl-report-start-timing (lambda ()
2553 (set! start-gc-rt (gc-run-time))
2554 (set! start-rt (get-internal-run-time))))
2555 (repl-report (lambda ()
2557 (display (inexact->exact
2558 (* 1000 (/ (- (get-internal-run-time) start-rt)
2559 internal-time-units-per-second))))
2561 (display (inexact->exact
2562 (* 1000 (/ (- (gc-run-time) start-gc-rt)
2563 internal-time-units-per-second))))
2564 (display " msec in gc)\n")))
2566 (consume-trailing-whitespace
2568 (let ((ch (peek-char)))
2571 ((or (char=? ch #\space) (char=? ch #\tab))
2573 (consume-trailing-whitespace))
2574 ((char=? ch #\newline)
2578 (let ((prompt (cond ((string? scm-repl-prompt)
2580 ((thunk? scm-repl-prompt)
2582 (scm-repl-prompt "> ")
2584 (repl-reader prompt))))
2586 ;; As described in R4RS, the READ procedure updates the
2587 ;; port to point to the first character past the end of
2588 ;; the external representation of the object. This
2589 ;; means that it doesn't consume the newline typically
2590 ;; found after an expression. This means that, when
2591 ;; debugging Guile with GDB, GDB gets the newline, which
2592 ;; it often interprets as a "continue" command, making
2593 ;; breakpoints kind of useless. So, consume any
2594 ;; trailing newline here, as well as any whitespace
2596 ;; But not if EOF, for control-D.
2597 (if (not (eof-object? val))
2598 (consume-trailing-whitespace))
2599 (run-hook after-read-hook)
2600 (if (eof-object? val)
2602 (repl-report-start-timing)
2603 (if scm-repl-verbose
2606 (display ";;; EOF -- quitting")
2611 (-eval (lambda (sourc)
2612 (repl-report-start-timing)
2613 (run-hook before-eval-hook sourc)
2614 (let ((val (start-stack 'repl-stack
2615 ;; If you change this procedure
2616 ;; (primitive-eval), please also
2617 ;; modify the repl-stack case in
2618 ;; save-stack so that stack cutting
2619 ;; continues to work.
2620 (primitive-eval sourc))))
2621 (run-hook after-eval-hook sourc)
2625 (-print (let ((maybe-print (lambda (result)
2626 (if (or scm-repl-print-unspecified
2627 (not (unspecified? result)))
2632 (if (not scm-repl-silent)
2634 (run-hook before-print-hook result)
2635 (maybe-print result)
2636 (run-hook after-print-hook result)
2637 (if scm-repl-verbose
2641 (-quit (lambda (args)
2642 (if scm-repl-verbose
2644 (display ";;; QUIT executed, repl exitting")
2650 (if scm-repl-verbose
2652 (display ";;; ABORT executed.")
2655 (repl -read -eval -print))))
2657 (let ((status (error-catching-repl -read
2665 ;;; {IOTA functions: generating lists of numbers}
2669 (let loop ((count (1- n)) (result '()))
2670 (if (< count 0) result
2671 (loop (1- count) (cons count result)))))
2677 ;;; Similar to `begin' but returns a list of the results of all constituent
2678 ;;; forms instead of the result of the last form.
2679 ;;; (The definition relies on the current left-to-right
2680 ;;; order of evaluation of operands in applications.)
2683 (defmacro collect forms
2691 ;; with-fluids is a convenience wrapper for the builtin procedure
2692 ;; `with-fluids*'. The syntax is just like `let':
2694 ;; (with-fluids ((fluid val)
2698 (defmacro with-fluids (bindings . body)
2699 (let ((fluids (map car bindings))
2700 (values (map cadr bindings)))
2701 (if (and (= (length fluids) 1) (= (length values) 1))
2702 `(with-fluid* ,(car fluids) ,(car values) (lambda () ,@body))
2703 `(with-fluids* (list ,@fluids) (list ,@values)
2704 (lambda () ,@body)))))
2711 ;; actually....hobbit might be able to hack these with a little
2715 (define (primitive-macro? m)
2717 (not (macro-transformer m))))
2719 (defmacro define-macro (first . rest)
2720 (let ((name (if (symbol? first) first (car first)))
2724 `(lambda ,(cdr first) ,@rest))))
2727 (define ,name (defmacro:transformer ,transformer)))
2729 (error "define-macro can only be used at the top level")))))
2732 (defmacro define-syntax-macro (first . rest)
2733 (let ((name (if (symbol? first) first (car first)))
2737 `(lambda ,(cdr first) ,@rest))))
2740 (define ,name (defmacro:syntax-transformer ,transformer)))
2742 (error "define-syntax-macro can only be used at the top level")))))
2748 ;;; with `continue' and `break'.
2751 ;; The inner `do' loop avoids re-establishing a catch every iteration,
2752 ;; that's only necessary if continue is actually used. A new key is
2753 ;; generated every time, so break and continue apply to their originating
2754 ;; `while' even when recursing. `while-helper' is an easy way to keep the
2755 ;; `key' binding away from the cond and body code.
2757 ;; FIXME: This is supposed to have an `unquote' on the `do' the same used
2758 ;; for lambda and not, so as to protect against any user rebinding of that
2759 ;; symbol, but unfortunately an unquote breaks with ice-9 syncase, eg.
2761 ;; (use-modules (ice-9 syncase))
2763 ;; => ERROR: invalid syntax ()
2765 ;; This is probably a bug in syncase.
2767 (define-macro (while cond . body)
2768 (define (while-helper proc)
2769 (do ((key (make-symbol "while-key")))
2772 (proc (lambda () (throw key #t))
2773 (lambda () (throw key #f))))
2774 (lambda (key arg) arg)))))
2775 `(,while-helper (,lambda (break continue)
2784 ;;; {Module System Macros}
2787 ;; Return a list of expressions that evaluate to the appropriate
2788 ;; arguments for resolve-interface according to SPEC.
2790 (define (compile-interface-spec spec)
2791 (define (make-keyarg sym key quote?)
2792 (cond ((or (memq sym spec)
2796 (list key (list 'quote (cadr rest)))
2797 (list key (cadr rest)))))
2800 (define (map-apply func list)
2801 (map (lambda (args) (apply func args)) list))
2804 '((:select #:select #t)
2806 (:prefix #:prefix #t)
2807 (:renamer #:renamer #f)))
2808 (if (not (pair? (car spec)))
2811 ,@(apply append (map-apply make-keyarg keys)))))
2813 (define (keyword-like-symbol->keyword sym)
2814 (symbol->keyword (string->symbol (substring (symbol->string sym) 1))))
2816 (define (compile-define-module-args args)
2817 ;; Just quote everything except #:use-module and #:use-syntax. We
2818 ;; need to know about all arguments regardless since we want to turn
2819 ;; symbols that look like keywords into real keywords, and the
2820 ;; keyword args in a define-module form are not regular
2821 ;; (i.e. no-backtrace doesn't take a value).
2822 (let loop ((compiled-args `((quote ,(car args))))
2825 (reverse! compiled-args))
2826 ;; symbol in keyword position
2827 ((symbol? (car args))
2829 (cons (keyword-like-symbol->keyword (car args)) (cdr args))))
2830 ((memq (car args) '(#:no-backtrace #:pure))
2831 (loop (cons (car args) compiled-args)
2834 (error "keyword without value:" (car args)))
2835 ((memq (car args) '(#:use-module #:use-syntax))
2836 (loop (cons* `(list ,@(compile-interface-spec (cadr args)))
2840 ((eq? (car args) #:autoload)
2841 (loop (cons* `(quote ,(caddr args))
2842 `(quote ,(cadr args))
2847 (loop (cons* `(quote ,(cadr args))
2852 (defmacro define-module args
2855 (let ((m (process-define-module
2856 (list ,@(compile-define-module-args args)))))
2857 (set-current-module m)
2860 (error "define-module can only be used at the top level"))))
2862 ;; The guts of the use-modules macro. Add the interfaces of the named
2863 ;; modules to the use-list of the current module, in order.
2865 ;; This function is called by "modules.c". If you change it, be sure
2866 ;; to change scm_c_use_module as well.
2868 (define (process-use-modules module-interface-args)
2869 (let ((interfaces (map (lambda (mif-args)
2870 (or (apply resolve-interface mif-args)
2871 (error "no such module" mif-args)))
2872 module-interface-args)))
2873 (call-with-deferred-observers
2875 (module-use-interfaces! (current-module) interfaces)))))
2877 (defmacro use-modules modules
2880 (process-use-modules
2881 (list ,@(map (lambda (m)
2882 `(list ,@(compile-interface-spec m)))
2886 (error "use-modules can only be used at the top level"))))
2888 (defmacro use-syntax (spec)
2892 `((process-use-modules (list
2893 (list ,@(compile-interface-spec spec))))
2894 (set-module-transformer! (current-module)
2895 ,(car (last-pair spec))))
2896 `((set-module-transformer! (current-module) ,spec)))
2899 (error "use-syntax can only be used at the top level"))))
2901 ;; Dirk:FIXME:: This incorrect (according to R5RS) syntax needs to be changed
2902 ;; as soon as guile supports hygienic macros.
2903 (define define-private define)
2905 (defmacro define-public args
2907 (error "bad syntax" (list 'define-public args)))
2908 (define (defined-name n)
2911 ((pair? n) (defined-name (car n)))
2917 (let ((name (defined-name (car args))))
2919 (define-private ,@args)
2920 (eval-case ((load-toplevel) (export ,name))))))))
2922 (defmacro defmacro-public args
2924 (error "bad syntax" (list 'defmacro-public args)))
2925 (define (defined-name n)
2933 (let ((name (defined-name (car args))))
2935 (eval-case ((load-toplevel) (export-syntax ,name)))
2936 (defmacro ,@args))))))
2938 ;; Export a local variable
2940 ;; This function is called from "modules.c". If you change it, be
2941 ;; sure to update "modules.c" as well.
2943 (define (module-export! m names)
2944 (let ((public-i (module-public-interface m)))
2945 (for-each (lambda (name)
2946 (let ((var (module-ensure-local-variable! m name)))
2947 (module-add! public-i name var)))
2950 (define (module-replace! m names)
2951 (let ((public-i (module-public-interface m)))
2952 (for-each (lambda (name)
2953 (let ((var (module-ensure-local-variable! m name)))
2954 (set-object-property! var 'replace #t)
2955 (module-add! public-i name var)))
2958 ;; Re-export a imported variable
2960 (define (module-re-export! m names)
2961 (let ((public-i (module-public-interface m)))
2962 (for-each (lambda (name)
2963 (let ((var (module-variable m name)))
2965 (error "Undefined variable:" name))
2966 ((eq? var (module-local-variable m name))
2967 (error "re-exporting local variable:" name))
2969 (module-add! public-i name var)))))
2972 (defmacro export names
2975 (call-with-deferred-observers
2977 (module-export! (current-module) ',names))))
2979 (error "export can only be used at the top level"))))
2981 (defmacro re-export names
2984 (call-with-deferred-observers
2986 (module-re-export! (current-module) ',names))))
2988 (error "re-export can only be used at the top level"))))
2990 (defmacro export-syntax names
2993 (defmacro re-export-syntax names
2994 `(re-export ,@names))
2996 (define load load-module)
2998 ;; The following macro allows one to write, for example,
3000 ;; (@ (ice-9 pretty-print) pretty-print)
3002 ;; to refer directly to the pretty-print variable in module (ice-9
3003 ;; pretty-print). It works by looking up the variable and inserting
3004 ;; it directly into the code. This is understood by the evaluator.
3005 ;; Indeed, all references to global variables are memoized into such
3006 ;; variable objects.
3008 (define-macro (@ mod-name var-name)
3009 (let ((var (module-variable (resolve-interface mod-name) var-name)))
3011 (error "no such public variable" (list '@ mod-name var-name)))
3014 ;; The '@@' macro is like '@' but it can also access bindings that
3015 ;; have not been explicitely exported.
3017 (define-macro (@@ mod-name var-name)
3018 (let ((var (module-variable (resolve-module mod-name) var-name)))
3020 (error "no such variable" (list '@@ mod-name var-name)))
3028 (define make-mutable-parameter
3029 (let ((make (lambda (fluid converter)
3033 (fluid-set! fluid (converter (car args))))))))
3034 (lambda (init . converter)
3035 (let ((fluid (make-fluid))
3036 (converter (if (null? converter)
3039 (fluid-set! fluid (converter init))
3040 (make fluid converter)))))
3044 ;;; {Handling of duplicate imported bindings}
3047 ;; Duplicate handlers take the following arguments:
3049 ;; module importing module
3050 ;; name conflicting name
3051 ;; int1 old interface where name occurs
3052 ;; val1 value of binding in old interface
3053 ;; int2 new interface where name occurs
3054 ;; val2 value of binding in new interface
3055 ;; var previous resolution or #f
3056 ;; val value of previous resolution
3058 ;; A duplicate handler can take three alternative actions:
3060 ;; 1. return #f => leave responsibility to next handler
3061 ;; 2. exit with an error
3062 ;; 3. return a variable resolving the conflict
3065 (define duplicate-handlers
3066 (let ((m (make-module 7)))
3068 (define (check module name int1 val1 int2 val2 var val)
3069 (scm-error 'misc-error
3071 "~A: `~A' imported from both ~A and ~A"
3072 (list (module-name module)
3078 (define (warn module name int1 val1 int2 val2 var val)
3080 "WARNING: ~A: `~A' imported from both ~A and ~A\n"
3081 (module-name module)
3087 (define (replace module name int1 val1 int2 val2 var val)
3088 (let ((old (or (and var (object-property var 'replace) var)
3089 (module-variable int1 name)))
3090 (new (module-variable int2 name)))
3091 (if (object-property old 'replace)
3092 (and (or (eq? old new)
3093 (not (object-property new 'replace)))
3095 (and (object-property new 'replace)
3098 (define (warn-override-core module name int1 val1 int2 val2 var val)
3099 (and (eq? int1 the-scm-module)
3102 "WARNING: ~A: imported module ~A overrides core binding `~A'\n"
3103 (module-name module)
3106 (module-local-variable int2 name))))
3108 (define (first module name int1 val1 int2 val2 var val)
3109 (or var (module-local-variable int1 name)))
3111 (define (last module name int1 val1 int2 val2 var val)
3112 (module-local-variable int2 name))
3114 (define (noop module name int1 val1 int2 val2 var val)
3117 (set-module-name! m 'duplicate-handlers)
3118 (set-module-kind! m 'interface)
3119 (module-define! m 'check check)
3120 (module-define! m 'warn warn)
3121 (module-define! m 'replace replace)
3122 (module-define! m 'warn-override-core warn-override-core)
3123 (module-define! m 'first first)
3124 (module-define! m 'last last)
3125 (module-define! m 'merge-generics noop)
3126 (module-define! m 'merge-accessors noop)
3129 (define (lookup-duplicates-handlers handler-names)
3131 (map (lambda (handler-name)
3132 (or (module-symbol-local-binding
3133 duplicate-handlers handler-name #f)
3134 (error "invalid duplicate handler name:"
3136 (if (list? handler-names)
3138 (list handler-names)))))
3140 (define default-duplicate-binding-procedures
3141 (make-mutable-parameter #f))
3143 (define default-duplicate-binding-handler
3144 (make-mutable-parameter '(replace warn-override-core warn last)
3145 (lambda (handler-names)
3146 (default-duplicate-binding-procedures
3147 (lookup-duplicates-handlers handler-names))
3150 (define (make-duplicates-interface)
3151 (let ((m (make-module)))
3152 (set-module-kind! m 'custom-interface)
3153 (set-module-name! m 'duplicates)
3156 (define (process-duplicates module interface)
3157 (let* ((duplicates-handlers (or (module-duplicates-handlers module)
3158 (default-duplicate-binding-procedures)))
3159 (duplicates-interface (module-duplicates-interface module)))
3162 (cond ((module-import-interface module name)
3164 (lambda (prev-interface)
3165 (let ((var1 (module-local-variable prev-interface name))
3166 (var2 (module-local-variable interface name)))
3167 (if (not (eq? var1 var2))
3169 (if (not duplicates-interface)
3171 (set! duplicates-interface
3172 (make-duplicates-interface))
3173 (set-module-duplicates-interface!
3175 duplicates-interface)))
3176 (let* ((var (module-local-variable duplicates-interface
3179 (variable-bound? var)
3180 (variable-ref var))))
3181 (let loop ((duplicates-handlers duplicates-handlers))
3182 (cond ((null? duplicates-handlers))
3183 (((car duplicates-handlers)
3187 (and (variable-bound? var1)
3188 (variable-ref var1))
3190 (and (variable-bound? var2)
3191 (variable-ref var2))
3196 (module-add! duplicates-interface name var)))
3198 (loop (cdr duplicates-handlers)))))))))))))
3203 ;;; {`cond-expand' for SRFI-0 support.}
3205 ;;; This syntactic form expands into different commands or
3206 ;;; definitions, depending on the features provided by the Scheme
3212 ;;; --> (cond-expand <cond-expand-clause>+)
3213 ;;; | (cond-expand <cond-expand-clause>* (else <command-or-definition>))
3214 ;;; <cond-expand-clause>
3215 ;;; --> (<feature-requirement> <command-or-definition>*)
3216 ;;; <feature-requirement>
3217 ;;; --> <feature-identifier>
3218 ;;; | (and <feature-requirement>*)
3219 ;;; | (or <feature-requirement>*)
3220 ;;; | (not <feature-requirement>)
3221 ;;; <feature-identifier>
3222 ;;; --> <a symbol which is the name or alias of a SRFI>
3224 ;;; Additionally, this implementation provides the
3225 ;;; <feature-identifier>s `guile' and `r5rs', so that programs can
3226 ;;; determine the implementation type and the supported standard.
3228 ;;; Currently, the following feature identifiers are supported:
3230 ;;; guile r5rs srfi-0 srfi-4 srfi-6 srfi-13 srfi-14
3232 ;;; Remember to update the features list when adding more SRFIs.
3235 (define %cond-expand-features
3236 ;; Adjust the above comment when changing this.
3239 srfi-0 ;; cond-expand itself
3240 srfi-4 ;; homogenous numeric vectors
3241 srfi-6 ;; open-input-string etc, in the guile core
3242 srfi-13 ;; string library
3243 srfi-14 ;; character sets
3246 ;; This table maps module public interfaces to the list of features.
3248 (define %cond-expand-table (make-hash-table 31))
3250 ;; Add one or more features to the `cond-expand' feature list of the
3253 (define (cond-expand-provide module features)
3254 (let ((mod (module-public-interface module)))
3256 (hashq-set! %cond-expand-table mod
3257 (append (hashq-ref %cond-expand-table mod '())
3261 (procedure->memoizing-macro
3263 (let ((clauses (cdr exp))
3264 (syntax-error (lambda (cl)
3265 (error "invalid clause in `cond-expand'" cl))))
3271 (or (memq clause %cond-expand-features)
3272 (let lp ((uses (module-uses (env-module env))))
3275 (hashq-ref %cond-expand-table
3281 ((eq? 'and (car clause))
3282 (let lp ((l (cdr clause)))
3286 (and (test-clause (car l)) (lp (cdr l))))
3288 (syntax-error clause)))))
3289 ((eq? 'or (car clause))
3290 (let lp ((l (cdr clause)))
3294 (or (test-clause (car l)) (lp (cdr l))))
3296 (syntax-error clause)))))
3297 ((eq? 'not (car clause))
3298 (cond ((not (pair? (cdr clause)))
3299 (syntax-error clause))
3300 ((pair? (cddr clause))
3301 ((syntax-error clause))))
3302 (not (test-clause (cadr clause))))
3304 (syntax-error clause))))
3306 (syntax-error clause))))))
3307 (let lp ((c clauses))
3310 (error "Unfulfilled `cond-expand'"))
3313 ((not (pair? (car c)))
3314 (syntax-error (car c)))
3315 ((test-clause (caar c))
3316 `(begin ,@(cdar c)))
3317 ((eq? (caar c) 'else)
3320 `(begin ,@(cdar c)))
3322 (lp (cdr c))))))))))
3324 ;; This procedure gets called from the startup code with a list of
3325 ;; numbers, which are the numbers of the SRFIs to be loaded on startup.
3327 (define (use-srfis srfis)
3330 (let* ((srfi (string->symbol
3331 (string-append "srfi-" (number->string (car s)))))
3332 (mod-i (resolve-interface (list 'srfi srfi))))
3333 (module-use! (current-module) mod-i)
3338 ;;; {Load emacs interface support if emacs option is given.}
3341 (define (named-module-use! user usee)
3342 (module-use! (resolve-module user) (resolve-interface usee)))
3344 (define (load-emacs-interface)
3345 (and (provided? 'debug-extensions)
3346 (debug-enable 'backtrace))
3347 (named-module-use! '(guile-user) '(ice-9 emacs)))
3351 (define using-readline?
3352 (let ((using-readline? (make-fluid)))
3353 (make-procedure-with-setter
3354 (lambda () (fluid-ref using-readline?))
3355 (lambda (v) (fluid-set! using-readline? v)))))
3358 (let ((guile-user-module (resolve-module '(guile-user))))
3360 ;; Load emacs interface support if emacs option is given.
3361 (if (and (module-defined? guile-user-module 'use-emacs-interface)
3362 (module-ref guile-user-module 'use-emacs-interface))
3363 (load-emacs-interface))
3365 ;; Use some convenient modules (in reverse order)
3367 (if (provided? 'regex)
3368 (module-use! guile-user-module (resolve-interface '(ice-9 regex))))
3369 (if (provided? 'threads)
3370 (module-use! guile-user-module (resolve-interface '(ice-9 threads))))
3371 ;; load debugger on demand
3372 (module-use! guile-user-module
3373 (make-autoload-interface guile-user-module
3374 '(ice-9 debugger) '(debug)))
3375 (module-use! guile-user-module (resolve-interface '(ice-9 session)))
3376 (module-use! guile-user-module (resolve-interface '(ice-9 debug)))
3377 ;; so that builtin bindings will be checked first
3378 (module-use! guile-user-module (resolve-interface '(ice-9 r5rs)))
3379 (module-use! guile-user-module (resolve-interface '(guile)))
3381 (set-current-module guile-user-module)
3383 (let ((old-handlers #f)
3384 (signals (if (provided? 'posix)
3385 `((,SIGINT . "User interrupt")
3386 (,SIGFPE . "Arithmetic error")
3387 (,SIGBUS . "Bad memory access (bus error)")
3389 . "Bad memory access (Segmentation violation)"))
3396 (let ((make-handler (lambda (msg)
3398 ;; Make a backup copy of the stack
3399 (fluid-set! before-signal-stack
3400 (fluid-ref the-last-stack))
3408 (map (lambda (sig-msg)
3409 (sigaction (car sig-msg)
3410 (make-handler (cdr sig-msg))))
3413 ;; the protected thunk.
3415 (let ((status (scm-style-repl)))
3416 (run-hook exit-hook)
3421 (map (lambda (sig-msg old-handler)
3422 (if (not (car old-handler))
3423 ;; restore original C handler.
3424 (sigaction (car sig-msg) #f)
3425 ;; restore Scheme handler, SIG_IGN or SIG_DFL.
3426 (sigaction (car sig-msg)
3428 (cdr old-handler))))
3429 signals old-handlers))))))
3431 ;;; This hook is run at the very end of an interactive session.
3433 (define exit-hook (make-hook))
3437 ;;; {Deprecated stuff}
3441 (define (feature? sym)
3442 (issue-deprecation-warning
3443 "`feature?' is deprecated. Use `provided?' instead.")
3447 (primitive-load-path "ice-9/deprecated.scm"))
3451 ;;; Place the user in the guile-user module.
3454 (define-module (guile-user))
3456 ;;; boot-9.scm ends here