3 ;;;; Copyright (C) 1995,1996,1997,1998,1999,2000,2001,2002,2003,2004,2005,2006,2007,2009
4 ;;;; Free Software Foundation, Inc.
6 ;;;; This library is free software; you can redistribute it and/or
7 ;;;; modify it under the terms of the GNU Lesser General Public
8 ;;;; License as published by the Free Software Foundation; either
9 ;;;; version 2.1 of the License, or (at your option) any later version.
11 ;;;; This library is distributed in the hope that it will be useful,
12 ;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
13 ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 ;;;; Lesser General Public License for more details.
16 ;;;; You should have received a copy of the GNU Lesser General Public
17 ;;;; License along with this library; if not, write to the Free Software
18 ;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
25 ;;; This file is the first thing loaded into Guile. It adds many mundane
26 ;;; definitions and a few that are interesting.
28 ;;; The module system (hence the hierarchical namespace) are defined in this
39 (primitive-load-path "ice-9/r4rs")
43 ;;; {Simple Debugging Tools}
46 ;; peek takes any number of arguments, writes them to the
47 ;; current ouput port, and returns the last argument.
48 ;; It is handy to wrap around an expression to look at
49 ;; a value each time is evaluated, e.g.:
51 ;; (+ 10 (troublesome-fn))
52 ;; => (+ 10 (pk 'troublesome-fn-returned (troublesome-fn)))
55 (define (peek . stuff)
60 (car (last-pair stuff)))
64 (define (warn . stuff)
65 (with-output-to-port (current-error-port)
68 (display ";;; WARNING ")
71 (car (last-pair stuff)))))
79 (if (not (memq sym *features*))
80 (set! *features* (cons sym *features*))))
82 ;; Return #t iff FEATURE is available to this Guile interpreter. In SLIB,
83 ;; provided? also checks to see if the module is available. We should do that
86 (define (provided? feature)
87 (and (memq feature *features*) #t))
89 ;; let format alias simple-format until the more complete version is loaded
91 (define format simple-format)
93 ;; this is scheme wrapping the C code so the final pred call is a tail call,
95 (define (string-any char_pred s . rest)
96 (let ((start (if (null? rest)
98 (end (if (or (null? rest) (null? (cdr rest)))
99 (string-length s) (cadr rest))))
100 (if (and (procedure? char_pred)
102 (<= end (string-length s))) ;; let c-code handle range error
103 (or (string-any-c-code char_pred s start (1- end))
104 (char_pred (string-ref s (1- end))))
105 (string-any-c-code char_pred s start end))))
107 ;; this is scheme wrapping the C code so the final pred call is a tail call,
109 (define (string-every char_pred s . rest)
110 (let ((start (if (null? rest)
112 (end (if (or (null? rest) (null? (cdr rest)))
113 (string-length s) (cadr rest))))
114 (if (and (procedure? char_pred)
116 (<= end (string-length s))) ;; let c-code handle range error
117 (and (string-every-c-code char_pred s start (1- end))
118 (char_pred (string-ref s (1- end))))
119 (string-every-c-code char_pred s start end))))
121 ;; A variant of string-fill! that we keep for compatability
123 (define (substring-fill! str start end fill)
124 (string-fill! str fill start end))
128 ;; Before the module system boots, there are no module names. But
129 ;; psyntax does want a module-name definition, so give it one.
130 (define (module-name x)
132 (define (module-add! module sym var)
133 (hashq-set! (%get-pre-modules-obarray) sym var))
134 (define sc-macro 'sc-macro)
135 (define (make-module-ref mod var kind)
137 ((public) (if mod `(@ ,mod ,var) var))
138 ((private) (if (and mod (not (equal? mod (module-name (current-module)))))
142 ((hygiene) (if (and mod
143 (not (equal? mod (module-name (current-module))))
144 (module-variable (resolve-module mod) var))
147 (else (error "foo" mod var kind))))
148 (define (resolve-module . args)
151 (define sc-expand #f)
152 (define sc-expand3 #f)
154 (define install-global-transformer #f)
155 (define syntax-dispatch #f)
156 (define syntax-error #f)
157 (define (annotation? x) #f)
159 (define bound-identifier=? #f)
160 (define datum->syntax-object #f)
161 (define free-identifier=? #f)
162 (define generate-temporaries #f)
163 (define identifier? #f)
164 (define syntax-object->datum #f)
166 (define (void) (if #f #f))
169 (lambda (f first . rest)
172 (let andmap ((first first))
173 (let ((x (car first)) (first (cdr first)))
176 (and (f x) (andmap first)))))
177 (let andmap ((first first) (rest rest))
178 (let ((x (car first))
181 (rest (map cdr rest)))
183 (apply f (cons x xr))
184 (and (apply f (cons x xr)) (andmap first rest)))))))))
186 (define (syncase-error who format-string why what)
187 (%start-stack 'syncase-stack
189 (scm-error 'misc-error who "~A ~S" (list why what) '()))))
191 ;; Until the module system is booted, this will be the current expander.
192 (primitive-load-path "ice-9/psyntax-pp")
194 (define %pre-modules-transformer sc-expand)
198 ;; Before compiling, make sure any symbols are resolved in the (guile)
199 ;; module, the primary location of those symbols, rather than in
200 ;; (guile-user), the default module that we compile in.
203 (set-current-module (resolve-module '(guile))))
207 ;;; Depends on: features, eval-case
210 (define-syntax define-macro
213 ((_ (macro . args) . body)
214 (syntax (define-macro macro (lambda args . body))))
215 ((_ macro transformer)
219 (let ((v (syntax-object->datum y)))
220 (datum->syntax-object y (apply transformer (cdr v)))))))))))
222 (define-syntax defmacro
225 ((_ macro args . body)
226 (syntax (define-macro macro (lambda args . body)))))))
234 ;;; Depends on: defmacro
237 (defmacro begin-deprecated forms
238 (if (include-deprecated-features)
244 ;;; {Trivial Functions}
247 (define (identity x) x)
248 (define (and=> value procedure) (and value (procedure value)))
249 (define call/cc call-with-current-continuation)
251 ;;; apply-to-args is functionally redundant with apply and, worse,
252 ;;; is less general than apply since it only takes two arguments.
254 ;;; On the other hand, apply-to-args is a syntacticly convenient way to
255 ;;; perform binding in many circumstances when the "let" family of
256 ;;; of forms don't cut it. E.g.:
258 ;;; (apply-to-args (return-3d-mouse-coords)
263 (define (apply-to-args args fn) (apply fn args))
265 (defmacro false-if-exception (expr)
266 `(catch #t (lambda () ,expr)
271 ;;; {General Properties}
274 ;; This is a more modern interface to properties. It will replace all
275 ;; other property-like things eventually.
277 (define (make-object-property)
278 (let ((prop (primitive-make-property #f)))
279 (make-procedure-with-setter
280 (lambda (obj) (primitive-property-ref prop obj))
281 (lambda (obj val) (primitive-property-set! prop obj val)))))
285 ;;; {Symbol Properties}
288 (define (symbol-property sym prop)
289 (let ((pair (assoc prop (symbol-pref sym))))
290 (and pair (cdr pair))))
292 (define (set-symbol-property! sym prop val)
293 (let ((pair (assoc prop (symbol-pref sym))))
296 (symbol-pset! sym (acons prop val (symbol-pref sym))))))
298 (define (symbol-property-remove! sym prop)
299 (let ((pair (assoc prop (symbol-pref sym))))
301 (symbol-pset! sym (delq! pair (symbol-pref sym))))))
308 (define (array-shape a)
309 (map (lambda (ind) (if (number? ind) (list 0 (+ -1 ind)) ind))
310 (array-dimensions a)))
317 (define (kw-arg-ref args kw)
318 (let ((rem (member kw args)))
319 (and rem (pair? (cdr rem)) (cadr rem))))
326 (define (struct-layout s)
327 (struct-ref (struct-vtable s) vtable-index-layout))
334 ;; Printing records: by default, records are printed as
336 ;; #<type-name field1: val1 field2: val2 ...>
338 ;; You can change that by giving a custom printing function to
339 ;; MAKE-RECORD-TYPE (after the list of field symbols). This function
340 ;; will be called like
342 ;; (<printer> object port)
344 ;; It should print OBJECT to PORT.
346 (define (inherit-print-state old-port new-port)
347 (if (get-print-state old-port)
348 (port-with-print-state new-port (get-print-state old-port))
351 ;; 0: type-name, 1: fields
352 (define record-type-vtable
353 (make-vtable-vtable "prpr" 0
355 (cond ((eq? s record-type-vtable)
356 (display "#<record-type-vtable>" p))
358 (display "#<record-type " p)
359 (display (record-type-name s) p)
362 (define (record-type? obj)
363 (and (struct? obj) (eq? record-type-vtable (struct-vtable obj))))
365 (define (make-record-type type-name fields . opt)
366 (let ((printer-fn (and (pair? opt) (car opt))))
367 (let ((struct (make-struct record-type-vtable 0
370 (map (lambda (f) "pw") fields)))
374 (display type-name p)
375 (let loop ((fields fields)
378 ((not (null? fields))
380 (display (car fields) p)
382 (display (struct-ref s off) p)
383 (loop (cdr fields) (+ 1 off)))))
386 (copy-tree fields))))
387 ;; Temporary solution: Associate a name to the record type descriptor
388 ;; so that the object system can create a wrapper class for it.
389 (set-struct-vtable-name! struct (if (symbol? type-name)
391 (string->symbol type-name)))
394 (define (record-type-name obj)
395 (if (record-type? obj)
396 (struct-ref obj vtable-offset-user)
397 (error 'not-a-record-type obj)))
399 (define (record-type-fields obj)
400 (if (record-type? obj)
401 (struct-ref obj (+ 1 vtable-offset-user))
402 (error 'not-a-record-type obj)))
404 (define (record-constructor rtd . opt)
405 (let ((field-names (if (pair? opt) (car opt) (record-type-fields rtd))))
407 `(lambda ,field-names
408 (make-struct ',rtd 0 ,@(map (lambda (f)
409 (if (memq f field-names)
412 (record-type-fields rtd)))))))
414 (define (record-predicate rtd)
415 (lambda (obj) (and (struct? obj) (eq? rtd (struct-vtable obj)))))
417 (define (%record-type-error rtd obj) ;; private helper
418 (or (eq? rtd (record-type-descriptor obj))
419 (scm-error 'wrong-type-arg "%record-type-check"
420 "Wrong type record (want `~S'): ~S"
421 (list (record-type-name rtd) obj)
424 (define (record-accessor rtd field-name)
425 (let ((pos (list-index (record-type-fields rtd) field-name)))
427 (error 'no-such-field field-name))
429 (if (eq? (struct-vtable obj) rtd)
431 (%record-type-error rtd obj)))))
433 (define (record-modifier rtd field-name)
434 (let ((pos (list-index (record-type-fields rtd) field-name)))
436 (error 'no-such-field field-name))
438 (if (eq? (struct-vtable obj) rtd)
439 (struct-set! obj pos val)
440 (%record-type-error rtd obj)))))
442 (define (record? obj)
443 (and (struct? obj) (record-type? (struct-vtable obj))))
445 (define (record-type-descriptor obj)
448 (error 'not-a-record obj)))
457 (define (->bool x) (not (not x)))
464 (define (symbol-append . args)
465 (string->symbol (apply string-append (map symbol->string args))))
467 (define (list->symbol . args)
468 (string->symbol (apply list->string args)))
470 (define (symbol . args)
471 (string->symbol (apply string args)))
478 (define (list-index l k)
484 (loop (+ n 1) (cdr l))))))
488 ;;; {and-map and or-map}
490 ;;; (and-map fn lst) is like (and (fn (car lst)) (fn (cadr lst)) (fn...) ...)
491 ;;; (or-map fn lst) is like (or (fn (car lst)) (fn (cadr lst)) (fn...) ...)
496 ;; Apply f to successive elements of l until exhaustion or f returns #f.
497 ;; If returning early, return #f. Otherwise, return the last value returned
498 ;; by f. If f has never been called because l is empty, return #t.
500 (define (and-map f lst)
501 (let loop ((result #t)
506 (loop (f (car l)) (cdr l))))))
510 ;; Apply f to successive elements of l until exhaustion or while f returns #f.
511 ;; If returning early, return the return value of f.
513 (define (or-map f lst)
514 (let loop ((result #f)
518 (loop (f (car l)) (cdr l))))))
522 (if (provided? 'posix)
523 (primitive-load-path "ice-9/posix"))
525 (if (provided? 'socket)
526 (primitive-load-path "ice-9/networking"))
528 ;; For reference, Emacs file-exists-p uses stat in this same way.
529 ;; ENHANCE-ME: Catching an exception from stat is a bit wasteful, do this in
530 ;; C where all that's needed is to inspect the return from stat().
532 (if (provided? 'posix)
534 (->bool (false-if-exception (stat str))))
536 (let ((port (catch 'system-error (lambda () (open-file str OPEN_READ))
538 (if port (begin (close-port port) #t)
541 (define file-is-directory?
542 (if (provided? 'posix)
544 (eq? (stat:type (stat str)) 'directory))
546 (let ((port (catch 'system-error
547 (lambda () (open-file (string-append str "/.")
550 (if port (begin (close-port port) #t)
553 (define (has-suffix? str suffix)
554 (string-suffix? suffix str))
556 (define (system-error-errno args)
557 (if (eq? (car args) 'system-error)
558 (car (list-ref args 4))
566 (define (error . args)
569 (scm-error 'misc-error #f "?" #f #f)
570 (let loop ((msg "~A")
572 (if (not (null? rest))
573 (loop (string-append msg " ~S")
575 (scm-error 'misc-error #f msg args #f)))))
577 ;; bad-throw is the hook that is called upon a throw to a an unhandled
578 ;; key (unless the throw has four arguments, in which case
579 ;; it's usually interpreted as an error throw.)
580 ;; If the key has a default handler (a throw-handler-default property),
581 ;; it is applied to the throw.
583 (define (bad-throw key . args)
584 (let ((default (symbol-property key 'throw-handler-default)))
585 (or (and default (apply default key args))
586 (apply error "unhandled-exception:" key args))))
590 (define (tm:sec obj) (vector-ref obj 0))
591 (define (tm:min obj) (vector-ref obj 1))
592 (define (tm:hour obj) (vector-ref obj 2))
593 (define (tm:mday obj) (vector-ref obj 3))
594 (define (tm:mon obj) (vector-ref obj 4))
595 (define (tm:year obj) (vector-ref obj 5))
596 (define (tm:wday obj) (vector-ref obj 6))
597 (define (tm:yday obj) (vector-ref obj 7))
598 (define (tm:isdst obj) (vector-ref obj 8))
599 (define (tm:gmtoff obj) (vector-ref obj 9))
600 (define (tm:zone obj) (vector-ref obj 10))
602 (define (set-tm:sec obj val) (vector-set! obj 0 val))
603 (define (set-tm:min obj val) (vector-set! obj 1 val))
604 (define (set-tm:hour obj val) (vector-set! obj 2 val))
605 (define (set-tm:mday obj val) (vector-set! obj 3 val))
606 (define (set-tm:mon obj val) (vector-set! obj 4 val))
607 (define (set-tm:year obj val) (vector-set! obj 5 val))
608 (define (set-tm:wday obj val) (vector-set! obj 6 val))
609 (define (set-tm:yday obj val) (vector-set! obj 7 val))
610 (define (set-tm:isdst obj val) (vector-set! obj 8 val))
611 (define (set-tm:gmtoff obj val) (vector-set! obj 9 val))
612 (define (set-tm:zone obj val) (vector-set! obj 10 val))
614 (define (tms:clock obj) (vector-ref obj 0))
615 (define (tms:utime obj) (vector-ref obj 1))
616 (define (tms:stime obj) (vector-ref obj 2))
617 (define (tms:cutime obj) (vector-ref obj 3))
618 (define (tms:cstime obj) (vector-ref obj 4))
620 (define file-position ftell)
621 (define (file-set-position port offset . whence)
622 (let ((whence (if (eq? whence '()) SEEK_SET (car whence))))
623 (seek port offset whence)))
625 (define (move->fdes fd/port fd)
626 (cond ((integer? fd/port)
627 (dup->fdes fd/port fd)
631 (primitive-move->fdes fd/port fd)
632 (set-port-revealed! fd/port 1)
635 (define (release-port-handle port)
636 (let ((revealed (port-revealed port)))
638 (set-port-revealed! port (- revealed 1)))))
640 (define (dup->port port/fd mode . maybe-fd)
641 (let ((port (fdopen (apply dup->fdes port/fd maybe-fd)
644 (set-port-revealed! port 1))
647 (define (dup->inport port/fd . maybe-fd)
648 (apply dup->port port/fd "r" maybe-fd))
650 (define (dup->outport port/fd . maybe-fd)
651 (apply dup->port port/fd "w" maybe-fd))
653 (define (dup port/fd . maybe-fd)
654 (if (integer? port/fd)
655 (apply dup->fdes port/fd maybe-fd)
656 (apply dup->port port/fd (port-mode port/fd) maybe-fd)))
658 (define (duplicate-port port modes)
659 (dup->port port modes))
661 (define (fdes->inport fdes)
662 (let loop ((rest-ports (fdes->ports fdes)))
663 (cond ((null? rest-ports)
664 (let ((result (fdopen fdes "r")))
665 (set-port-revealed! result 1)
667 ((input-port? (car rest-ports))
668 (set-port-revealed! (car rest-ports)
669 (+ (port-revealed (car rest-ports)) 1))
672 (loop (cdr rest-ports))))))
674 (define (fdes->outport fdes)
675 (let loop ((rest-ports (fdes->ports fdes)))
676 (cond ((null? rest-ports)
677 (let ((result (fdopen fdes "w")))
678 (set-port-revealed! result 1)
680 ((output-port? (car rest-ports))
681 (set-port-revealed! (car rest-ports)
682 (+ (port-revealed (car rest-ports)) 1))
685 (loop (cdr rest-ports))))))
687 (define (port->fdes port)
688 (set-port-revealed! port (+ (port-revealed port) 1))
691 (define (setenv name value)
693 (putenv (string-append name "=" value))
696 (define (unsetenv name)
697 "Remove the entry for NAME from the environment."
705 ;;; Here for backward compatability
707 (define scheme-file-suffix (lambda () ".scm"))
709 (define (in-vicinity vicinity file)
710 (let ((tail (let ((len (string-length vicinity)))
713 (string-ref vicinity (- len 1))))))
714 (string-append vicinity
723 ;;; {Help for scm_shell}
725 ;;; The argument-processing code used by Guile-based shells generates
726 ;;; Scheme code based on the argument list. This page contains help
727 ;;; functions for the code it generates.
730 (define (command-line) (program-arguments))
732 ;; This is mostly for the internal use of the code generated by
733 ;; scm_compile_shell_switches.
735 (define (turn-on-debugging)
736 (debug-enable 'debug)
737 (debug-enable 'backtrace)
738 (read-enable 'positions))
740 (define (load-user-init)
741 (let* ((home (or (getenv "HOME")
742 (false-if-exception (passwd:dir (getpwuid (getuid))))
743 "/")) ;; fallback for cygwin etc.
744 (init-file (in-vicinity home ".guile")))
745 (if (file-exists? init-file)
746 (primitive-load init-file))))
750 ;;; {The interpreter stack}
753 (defmacro start-stack (tag exp)
754 `(%start-stack ,tag (lambda () ,exp)))
758 ;;; {Loading by paths}
761 ;;; Load a Scheme source file named NAME, searching for it in the
762 ;;; directories listed in %load-path, and applying each of the file
763 ;;; name extensions listed in %load-extensions.
764 (define (load-from-path name)
765 (start-stack 'load-stack
766 (primitive-load-path name)))
768 (define %load-verbosely #f)
769 (define (assert-load-verbosity v) (set! %load-verbosely v))
771 (define (%load-announce file)
773 (with-output-to-port (current-error-port)
781 (set! %load-hook %load-announce)
783 (define (load name . reader)
784 (with-fluid* current-reader (and (pair? reader) (car reader))
786 (start-stack 'load-stack
787 (primitive-load name)))))
791 ;;; {Transcendental Functions}
793 ;;; Derived from "Transcen.scm", Complex trancendental functions for SCM.
794 ;;; Written by Jerry D. Hedden, (C) FSF.
795 ;;; See the file `COPYING' for terms applying to this program.
799 (let ((integer-expt integer-expt))
801 (cond ((and (exact? z2) (integer? z2))
802 (integer-expt z1 z2))
803 ((and (real? z2) (real? z1) (>= z1 0))
806 (exp (* z2 (log z1))))))))
809 (if (real? z) ($sinh z)
810 (let ((x (real-part z)) (y (imag-part z)))
811 (make-rectangular (* ($sinh x) ($cos y))
812 (* ($cosh x) ($sin y))))))
814 (if (real? z) ($cosh z)
815 (let ((x (real-part z)) (y (imag-part z)))
816 (make-rectangular (* ($cosh x) ($cos y))
817 (* ($sinh x) ($sin y))))))
819 (if (real? z) ($tanh z)
820 (let* ((x (* 2 (real-part z)))
821 (y (* 2 (imag-part z)))
822 (w (+ ($cosh x) ($cos y))))
823 (make-rectangular (/ ($sinh x) w) (/ ($sin y) w)))))
826 (if (real? z) ($asinh z)
827 (log (+ z (sqrt (+ (* z z) 1))))))
830 (if (and (real? z) (>= z 1))
832 (log (+ z (sqrt (- (* z z) 1))))))
835 (if (and (real? z) (> z -1) (< z 1))
837 (/ (log (/ (+ 1 z) (- 1 z))) 2)))
840 (if (real? z) ($sin z)
841 (let ((x (real-part z)) (y (imag-part z)))
842 (make-rectangular (* ($sin x) ($cosh y))
843 (* ($cos x) ($sinh y))))))
845 (if (real? z) ($cos z)
846 (let ((x (real-part z)) (y (imag-part z)))
847 (make-rectangular (* ($cos x) ($cosh y))
848 (- (* ($sin x) ($sinh y)))))))
850 (if (real? z) ($tan z)
851 (let* ((x (* 2 (real-part z)))
852 (y (* 2 (imag-part z)))
853 (w (+ ($cos x) ($cosh y))))
854 (make-rectangular (/ ($sin x) w) (/ ($sinh y) w)))))
857 (if (and (real? z) (>= z -1) (<= z 1))
859 (* -i (asinh (* +i z)))))
862 (if (and (real? z) (>= z -1) (<= z 1))
864 (+ (/ (angle -1) 2) (* +i (asinh (* +i z))))))
868 (if (real? z) ($atan z)
869 (/ (log (/ (- +i z) (+ +i z))) +2i))
874 ;;; {Reader Extensions}
876 ;;; Reader code for various "#c" forms.
879 (read-hash-extend #\' (lambda (c port)
882 (define read-eval? (make-fluid))
883 (fluid-set! read-eval? #f)
884 (read-hash-extend #\.
886 (if (fluid-ref read-eval?)
887 (eval (read port) (interaction-environment))
889 "#. read expansion found and read-eval? is #f."))))
893 ;;; {Command Line Options}
896 (define (get-option argv kw-opts kw-args return)
901 ((or (not (eq? #\- (string-ref (car argv) 0)))
902 (eq? (string-length (car argv)) 1))
903 (return 'normal-arg (car argv) (cdr argv)))
905 ((eq? #\- (string-ref (car argv) 1))
906 (let* ((kw-arg-pos (or (string-index (car argv) #\=)
907 (string-length (car argv))))
908 (kw (symbol->keyword (substring (car argv) 2 kw-arg-pos)))
909 (kw-opt? (member kw kw-opts))
910 (kw-arg? (member kw kw-args))
911 (arg (or (and (not (eq? kw-arg-pos (string-length (car argv))))
912 (substring (car argv)
914 (string-length (car argv))))
916 (begin (set! argv (cdr argv)) (car argv))))))
917 (if (or kw-opt? kw-arg?)
918 (return kw arg (cdr argv))
919 (return 'usage-error kw (cdr argv)))))
922 (let* ((char (substring (car argv) 1 2))
923 (kw (symbol->keyword char)))
927 (let* ((rest-car (substring (car argv) 2 (string-length (car argv))))
928 (new-argv (if (= 0 (string-length rest-car))
930 (cons (string-append "-" rest-car) (cdr argv)))))
931 (return kw #f new-argv)))
934 (let* ((rest-car (substring (car argv) 2 (string-length (car argv))))
935 (arg (if (= 0 (string-length rest-car))
938 (new-argv (if (= 0 (string-length rest-car))
941 (return kw arg new-argv)))
943 (else (return 'usage-error kw argv)))))))
945 (define (for-next-option proc argv kw-opts kw-args)
946 (let loop ((argv argv))
947 (get-option argv kw-opts kw-args
948 (lambda (opt opt-arg argv)
949 (and opt (proc opt opt-arg argv loop))))))
951 (define (display-usage-report kw-desc)
954 (or (eq? (car kw) #t)
957 (help (cadr opt-desc))
958 (opts (car opt-desc))
959 (opts-proper (if (string? (car opts)) (cdr opts) opts))
960 (arg-name (if (string? (car opts))
961 (string-append "<" (car opts) ">")
963 (left-part (string-append
964 (with-output-to-string
966 (map (lambda (x) (display (keyword->symbol x)) (display " "))
969 (middle-part (if (and (< (string-length left-part) 30)
970 (< (string-length help) 40))
971 (make-string (- 30 (string-length left-part)) #\ )
974 (display middle-part)
981 (define (transform-usage-lambda cases)
982 (let* ((raw-usage (delq! 'else (map car cases)))
983 (usage-sans-specials (map (lambda (x)
984 (or (and (not (list? x)) x)
985 (and (symbol? (car x)) #t)
986 (and (boolean? (car x)) #t)
989 (usage-desc (delq! #t usage-sans-specials))
990 (kw-desc (map car usage-desc))
991 (kw-opts (apply append (map (lambda (x) (and (not (string? (car x))) x)) kw-desc)))
992 (kw-args (apply append (map (lambda (x) (and (string? (car x)) (cdr x))) kw-desc)))
993 (transmogrified-cases (map (lambda (case)
994 (cons (let ((opts (car case)))
995 (if (or (boolean? opts) (eq? 'else opts))
998 ((symbol? (car opts)) opts)
999 ((boolean? (car opts)) opts)
1000 ((string? (caar opts)) (cdar opts))
1001 (else (car opts)))))
1004 `(let ((%display-usage (lambda () (display-usage-report ',usage-desc))))
1006 (let %next-arg ((%argv %argv))
1010 (lambda (%opt %arg %new-argv)
1012 ,@ transmogrified-cases))))))))
1017 ;;; {Low Level Modules}
1019 ;;; These are the low level data structures for modules.
1021 ;;; Every module object is of the type 'module-type', which is a record
1022 ;;; consisting of the following members:
1024 ;;; - eval-closure: the function that defines for its module the strategy that
1025 ;;; shall be followed when looking up symbols in the module.
1027 ;;; An eval-closure is a function taking two arguments: the symbol to be
1028 ;;; looked up and a boolean value telling whether a binding for the symbol
1029 ;;; should be created if it does not exist yet. If the symbol lookup
1030 ;;; succeeded (either because an existing binding was found or because a new
1031 ;;; binding was created), a variable object representing the binding is
1032 ;;; returned. Otherwise, the value #f is returned. Note that the eval
1033 ;;; closure does not take the module to be searched as an argument: During
1034 ;;; construction of the eval-closure, the eval-closure has to store the
1035 ;;; module it belongs to in its environment. This means, that any
1036 ;;; eval-closure can belong to only one module.
1038 ;;; The eval-closure of a module can be defined arbitrarily. However, three
1039 ;;; special cases of eval-closures are to be distinguished: During startup
1040 ;;; the module system is not yet activated. In this phase, no modules are
1041 ;;; defined and all bindings are automatically stored by the system in the
1042 ;;; pre-modules-obarray. Since no eval-closures exist at this time, the
1043 ;;; functions which require an eval-closure as their argument need to be
1044 ;;; passed the value #f.
1046 ;;; The other two special cases of eval-closures are the
1047 ;;; standard-eval-closure and the standard-interface-eval-closure. Both
1048 ;;; behave equally for the case that no new binding is to be created. The
1049 ;;; difference between the two comes in, when the boolean argument to the
1050 ;;; eval-closure indicates that a new binding shall be created if it is not
1053 ;;; Given that no new binding shall be created, both standard eval-closures
1054 ;;; define the following standard strategy of searching bindings in the
1055 ;;; module: First, the module's obarray is searched for the symbol. Second,
1056 ;;; if no binding for the symbol was found in the module's obarray, the
1057 ;;; module's binder procedure is exececuted. If this procedure did not
1058 ;;; return a binding for the symbol, the modules referenced in the module's
1059 ;;; uses list are recursively searched for a binding of the symbol. If the
1060 ;;; binding can not be found in these modules also, the symbol lookup has
1063 ;;; If a new binding shall be created, the standard-interface-eval-closure
1064 ;;; immediately returns indicating failure. That is, it does not even try
1065 ;;; to look up the symbol. In contrast, the standard-eval-closure would
1066 ;;; first search the obarray, and if no binding was found there, would
1067 ;;; create a new binding in the obarray, therefore not calling the binder
1068 ;;; procedure or searching the modules in the uses list.
1070 ;;; The explanation of the following members obarray, binder and uses
1071 ;;; assumes that the symbol lookup follows the strategy that is defined in
1072 ;;; the standard-eval-closure and the standard-interface-eval-closure.
1074 ;;; - obarray: a hash table that maps symbols to variable objects. In this
1075 ;;; hash table, the definitions are found that are local to the module (that
1076 ;;; is, not imported from other modules). When looking up bindings in the
1077 ;;; module, this hash table is searched first.
1079 ;;; - binder: either #f or a function taking a module and a symbol argument.
1080 ;;; If it is a function it is called after the obarray has been
1081 ;;; unsuccessfully searched for a binding. It then can provide bindings
1082 ;;; that would otherwise not be found locally in the module.
1084 ;;; - uses: a list of modules from which non-local bindings can be inherited.
1085 ;;; These modules are the third place queried for bindings after the obarray
1086 ;;; has been unsuccessfully searched and the binder function did not deliver
1087 ;;; a result either.
1089 ;;; - transformer: either #f or a function taking a scheme expression as
1090 ;;; delivered by read. If it is a function, it will be called to perform
1091 ;;; syntax transformations (e. g. makro expansion) on the given scheme
1092 ;;; expression. The output of the transformer function will then be passed
1093 ;;; to Guile's internal memoizer. This means that the output must be valid
1094 ;;; scheme code. The only exception is, that the output may make use of the
1095 ;;; syntax extensions provided to identify the modules that a binding
1098 ;;; - name: the name of the module. This is used for all kinds of printing
1099 ;;; outputs. In certain places the module name also serves as a way of
1100 ;;; identification. When adding a module to the uses list of another
1101 ;;; module, it is made sure that the new uses list will not contain two
1102 ;;; modules of the same name.
1104 ;;; - kind: classification of the kind of module. The value is (currently?)
1105 ;;; only used for printing. It has no influence on how a module is treated.
1106 ;;; Currently the following values are used when setting the module kind:
1107 ;;; 'module, 'directory, 'interface, 'custom-interface. If no explicit kind
1108 ;;; is set, it defaults to 'module.
1110 ;;; - duplicates-handlers: a list of procedures that get called to make a
1111 ;;; choice between two duplicate bindings when name clashes occur. See the
1112 ;;; `duplicate-handlers' global variable below.
1114 ;;; - observers: a list of procedures that get called when the module is
1117 ;;; - weak-observers: a weak-key hash table of procedures that get called
1118 ;;; when the module is modified. See `module-observe-weak' for details.
1120 ;;; In addition, the module may (must?) contain a binding for
1121 ;;; `%module-public-interface'. This variable should be bound to a module
1122 ;;; representing the exported interface of a module. See the
1123 ;;; `module-public-interface' and `module-export!' procedures.
1125 ;;; !!! warning: The interface to lazy binder procedures is going
1126 ;;; to be changed in an incompatible way to permit all the basic
1127 ;;; module ops to be virtualized.
1129 ;;; (make-module size use-list lazy-binding-proc) => module
1130 ;;; module-{obarray,uses,binder}[|-set!]
1131 ;;; (module? obj) => [#t|#f]
1132 ;;; (module-locally-bound? module symbol) => [#t|#f]
1133 ;;; (module-bound? module symbol) => [#t|#f]
1134 ;;; (module-symbol-locally-interned? module symbol) => [#t|#f]
1135 ;;; (module-symbol-interned? module symbol) => [#t|#f]
1136 ;;; (module-local-variable module symbol) => [#<variable ...> | #f]
1137 ;;; (module-variable module symbol) => [#<variable ...> | #f]
1138 ;;; (module-symbol-binding module symbol opt-value)
1139 ;;; => [ <obj> | opt-value | an error occurs ]
1140 ;;; (module-make-local-var! module symbol) => #<variable...>
1141 ;;; (module-add! module symbol var) => unspecified
1142 ;;; (module-remove! module symbol) => unspecified
1143 ;;; (module-for-each proc module) => unspecified
1144 ;;; (make-scm-module) => module ; a lazy copy of the symhash module
1145 ;;; (set-current-module module) => unspecified
1146 ;;; (current-module) => #<module...>
1152 ;;; {Printing Modules}
1155 ;; This is how modules are printed. You can re-define it.
1156 ;; (Redefining is actually more complicated than simply redefining
1157 ;; %print-module because that would only change the binding and not
1158 ;; the value stored in the vtable that determines how record are
1161 (define (%print-module mod port) ; unused args: depth length style table)
1163 (display (or (module-kind mod) "module") port)
1164 (let ((name (module-name mod)))
1168 (display name port))))
1170 (display (number->string (object-address mod) 16) port)
1175 ;; A module is characterized by an obarray in which local symbols
1176 ;; are interned, a list of modules, "uses", from which non-local
1177 ;; bindings can be inherited, and an optional lazy-binder which
1178 ;; is a (CLOSURE module symbol) which, as a last resort, can provide
1179 ;; bindings that would otherwise not be found locally in the module.
1181 ;; NOTE: If you change anything here, you also need to change
1182 ;; libguile/modules.h.
1185 (make-record-type 'module
1186 '(obarray uses binder eval-closure transformer name kind
1187 duplicates-handlers import-obarray
1188 observers weak-observers)
1191 ;; make-module &opt size uses binder
1193 ;; Create a new module, perhaps with a particular size of obarray,
1194 ;; initial uses list, or binding procedure.
1199 (define (parse-arg index default)
1200 (if (> (length args) index)
1201 (list-ref args index)
1204 (define %default-import-size
1205 ;; Typical number of imported bindings actually used by a module.
1208 (if (> (length args) 3)
1209 (error "Too many args to make-module." args))
1211 (let ((size (parse-arg 0 31))
1212 (uses (parse-arg 1 '()))
1213 (binder (parse-arg 2 #f)))
1215 (if (not (integer? size))
1216 (error "Illegal size to make-module." size))
1217 (if (not (and (list? uses)
1218 (and-map module? uses)))
1219 (error "Incorrect use list." uses))
1220 (if (and binder (not (procedure? binder)))
1222 "Lazy-binder expected to be a procedure or #f." binder))
1224 (let ((module (module-constructor (make-hash-table size)
1225 uses binder #f %pre-modules-transformer
1227 (make-hash-table %default-import-size)
1229 (make-weak-key-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)) wait until mods are booted
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-observers (record-accessor module-type 'observers))
1260 (define set-module-observers! (record-modifier module-type 'observers))
1261 (define module-weak-observers (record-accessor module-type 'weak-observers))
1262 (define module? (record-predicate module-type))
1264 (define module-import-obarray (record-accessor module-type 'import-obarray))
1266 (define set-module-eval-closure!
1267 (let ((setter (record-modifier module-type 'eval-closure)))
1268 (lambda (module closure)
1269 (setter module closure)
1270 ;; Make it possible to lookup the module from the environment.
1271 ;; This implementation is correct since an eval closure can belong
1272 ;; to maximally one module.
1273 (set-procedure-property! closure 'module module))))
1277 ;;; {Observer protocol}
1280 (define (module-observe module proc)
1281 (set-module-observers! module (cons proc (module-observers module)))
1284 (define (module-observe-weak module observer-id . proc)
1285 ;; Register PROC as an observer of MODULE under name OBSERVER-ID (which can
1286 ;; be any Scheme object). PROC is invoked and passed MODULE any time
1287 ;; MODULE is modified. PROC gets unregistered when OBSERVER-ID gets GC'd
1288 ;; (thus, it is never unregistered if OBSERVER-ID is an immediate value,
1291 ;; The two-argument version is kept for backward compatibility: when called
1292 ;; with two arguments, the observer gets unregistered when closure PROC
1293 ;; gets GC'd (making it impossible to use an anonymous lambda for PROC).
1295 (let ((proc (if (null? proc) observer-id (car proc))))
1296 (hashq-set! (module-weak-observers module) observer-id proc)))
1298 (define (module-unobserve token)
1299 (let ((module (car token))
1302 (hash-remove! (module-weak-observers module) id)
1303 (set-module-observers! module (delq1! id (module-observers module)))))
1306 (define module-defer-observers #f)
1307 (define module-defer-observers-mutex (make-mutex 'recursive))
1308 (define module-defer-observers-table (make-hash-table))
1310 (define (module-modified m)
1311 (if module-defer-observers
1312 (hash-set! module-defer-observers-table m #t)
1313 (module-call-observers m)))
1315 ;;; This function can be used to delay calls to observers so that they
1316 ;;; can be called once only in the face of massive updating of modules.
1318 (define (call-with-deferred-observers thunk)
1321 (lock-mutex module-defer-observers-mutex)
1322 (set! module-defer-observers #t))
1325 (set! module-defer-observers #f)
1326 (hash-for-each (lambda (m dummy)
1327 (module-call-observers m))
1328 module-defer-observers-table)
1329 (hash-clear! module-defer-observers-table)
1330 (unlock-mutex module-defer-observers-mutex))))
1332 (define (module-call-observers m)
1333 (for-each (lambda (proc) (proc m)) (module-observers m))
1335 ;; We assume that weak observers don't (un)register themselves as they are
1336 ;; called since this would preclude proper iteration over the hash table
1338 (hash-for-each (lambda (id proc) (proc m)) (module-weak-observers m)))
1342 ;;; {Module Searching in General}
1344 ;;; We sometimes want to look for properties of a symbol
1345 ;;; just within the obarray of one module. If the property
1346 ;;; holds, then it is said to hold ``locally'' as in, ``The symbol
1347 ;;; DISPLAY is locally rebound in the module `safe-guile'.''
1350 ;;; Other times, we want to test for a symbol property in the obarray
1351 ;;; of M and, if it is not found there, try each of the modules in the
1352 ;;; uses list of M. This is the normal way of testing for some
1353 ;;; property, so we state these properties without qualification as
1354 ;;; in: ``The symbol 'fnord is interned in module M because it is
1355 ;;; interned locally in module M2 which is a member of the uses list
1359 ;; module-search fn m
1361 ;; return the first non-#f result of FN applied to M and then to
1362 ;; the modules in the uses of m, and so on recursively. If all applications
1363 ;; return #f, then so does this function.
1365 (define (module-search fn m v)
1368 (or (module-search fn (car pos) v)
1371 (loop (module-uses m))))
1374 ;;; {Is a symbol bound in a module?}
1376 ;;; Symbol S in Module M is bound if S is interned in M and if the binding
1377 ;;; of S in M has been set to some well-defined value.
1380 ;; module-locally-bound? module symbol
1382 ;; Is a symbol bound (interned and defined) locally in a given module?
1384 (define (module-locally-bound? m v)
1385 (let ((var (module-local-variable m v)))
1387 (variable-bound? var))))
1389 ;; module-bound? module symbol
1391 ;; Is a symbol bound (interned and defined) anywhere in a given module
1394 (define (module-bound? m v)
1395 (module-search module-locally-bound? m v))
1397 ;;; {Is a symbol interned in a module?}
1399 ;;; Symbol S in Module M is interned if S occurs in
1400 ;;; of S in M has been set to some well-defined value.
1402 ;;; It is possible to intern a symbol in a module without providing
1403 ;;; an initial binding for the corresponding variable. This is done
1405 ;;; (module-add! module symbol (make-undefined-variable))
1407 ;;; In that case, the symbol is interned in the module, but not
1408 ;;; bound there. The unbound symbol shadows any binding for that
1409 ;;; symbol that might otherwise be inherited from a member of the uses list.
1412 (define (module-obarray-get-handle ob key)
1413 ((if (symbol? key) hashq-get-handle hash-get-handle) ob key))
1415 (define (module-obarray-ref ob key)
1416 ((if (symbol? key) hashq-ref hash-ref) ob key))
1418 (define (module-obarray-set! ob key val)
1419 ((if (symbol? key) hashq-set! hash-set!) ob key val))
1421 (define (module-obarray-remove! ob key)
1422 ((if (symbol? key) hashq-remove! hash-remove!) ob key))
1424 ;; module-symbol-locally-interned? module symbol
1426 ;; is a symbol interned (not neccessarily defined) locally in a given module
1427 ;; or its uses? Interned symbols shadow inherited bindings even if
1428 ;; they are not themselves bound to a defined value.
1430 (define (module-symbol-locally-interned? m v)
1431 (not (not (module-obarray-get-handle (module-obarray m) v))))
1433 ;; module-symbol-interned? module symbol
1435 ;; is a symbol interned (not neccessarily defined) anywhere in a given module
1436 ;; or its uses? Interned symbols shadow inherited bindings even if
1437 ;; they are not themselves bound to a defined value.
1439 (define (module-symbol-interned? m v)
1440 (module-search module-symbol-locally-interned? m v))
1443 ;;; {Mapping modules x symbols --> variables}
1446 ;; module-local-variable module symbol
1447 ;; return the local variable associated with a MODULE and SYMBOL.
1449 ;;; This function is very important. It is the only function that can
1450 ;;; return a variable from a module other than the mutators that store
1451 ;;; new variables in modules. Therefore, this function is the location
1452 ;;; of the "lazy binder" hack.
1454 ;;; If symbol is defined in MODULE, and if the definition binds symbol
1455 ;;; to a variable, return that variable object.
1457 ;;; If the symbols is not found at first, but the module has a lazy binder,
1458 ;;; then try the binder.
1460 ;;; If the symbol is not found at all, return #f.
1462 ;;; (This is now written in C, see `modules.c'.)
1465 ;;; {Mapping modules x symbols --> bindings}
1467 ;;; These are similar to the mapping to variables, except that the
1468 ;;; variable is dereferenced.
1471 ;; module-symbol-binding module symbol opt-value
1473 ;; return the binding of a variable specified by name within
1474 ;; a given module, signalling an error if the variable is unbound.
1475 ;; If the OPT-VALUE is passed, then instead of signalling an error,
1476 ;; return OPT-VALUE.
1478 (define (module-symbol-local-binding m v . opt-val)
1479 (let ((var (module-local-variable m v)))
1480 (if (and var (variable-bound? var))
1482 (if (not (null? opt-val))
1484 (error "Locally unbound variable." v)))))
1486 ;; module-symbol-binding module symbol opt-value
1488 ;; return the binding of a variable specified by name within
1489 ;; a given module, signalling an error if the variable is unbound.
1490 ;; If the OPT-VALUE is passed, then instead of signalling an error,
1491 ;; return OPT-VALUE.
1493 (define (module-symbol-binding m v . opt-val)
1494 (let ((var (module-variable m v)))
1495 (if (and var (variable-bound? var))
1497 (if (not (null? opt-val))
1499 (error "Unbound variable." v)))))
1504 ;;; {Adding Variables to Modules}
1507 ;; module-make-local-var! module symbol
1509 ;; ensure a variable for V in the local namespace of M.
1510 ;; If no variable was already there, then create a new and uninitialzied
1513 ;; This function is used in modules.c.
1515 (define (module-make-local-var! m v)
1516 (or (let ((b (module-obarray-ref (module-obarray m) v)))
1519 ;; Mark as modified since this function is called when
1520 ;; the standard eval closure defines a binding
1524 ;; Create a new local variable.
1525 (let ((local-var (make-undefined-variable)))
1526 (module-add! m v local-var)
1529 ;; module-ensure-local-variable! module symbol
1531 ;; Ensure that there is a local variable in MODULE for SYMBOL. If
1532 ;; there is no binding for SYMBOL, create a new uninitialized
1533 ;; variable. Return the local variable.
1535 (define (module-ensure-local-variable! module symbol)
1536 (or (module-local-variable module symbol)
1537 (let ((var (make-undefined-variable)))
1538 (module-add! module symbol var)
1541 ;; module-add! module symbol var
1543 ;; ensure a particular variable for V in the local namespace of M.
1545 (define (module-add! m v var)
1546 (if (not (variable? var))
1547 (error "Bad variable to module-add!" var))
1548 (module-obarray-set! (module-obarray m) v var)
1549 (module-modified m))
1553 ;; make sure that a symbol is undefined in the local namespace of M.
1555 (define (module-remove! m v)
1556 (module-obarray-remove! (module-obarray m) v)
1557 (module-modified m))
1559 (define (module-clear! m)
1560 (hash-clear! (module-obarray m))
1561 (module-modified m))
1563 ;; MODULE-FOR-EACH -- exported
1565 ;; Call PROC on each symbol in MODULE, with arguments of (SYMBOL VARIABLE).
1567 (define (module-for-each proc module)
1568 (hash-for-each proc (module-obarray module)))
1570 (define (module-map proc module)
1571 (hash-map->list proc (module-obarray module)))
1575 ;;; {Low Level Bootstrapping}
1580 ;; A root module uses the pre-modules-obarray as its obarray. This
1581 ;; special obarray accumulates all bindings that have been established
1582 ;; before the module system is fully booted.
1584 ;; (The obarray continues to be used by code that has been closed over
1585 ;; before the module system has been booted.)
1587 (define (make-root-module)
1588 (let ((m (make-module 0)))
1589 (set-module-obarray! m (%get-pre-modules-obarray))
1594 ;; The root interface is a module that uses the same obarray as the
1595 ;; root module. It does not allow new definitions, tho.
1597 (define (make-scm-module)
1598 (let ((m (make-module 0)))
1599 (set-module-obarray! m (%get-pre-modules-obarray))
1600 (set-module-eval-closure! m (standard-interface-eval-closure m))
1606 ;;; {Module-based Loading}
1609 (define (save-module-excursion thunk)
1610 (let ((inner-module (current-module))
1612 (dynamic-wind (lambda ()
1613 (set! outer-module (current-module))
1614 (set-current-module inner-module)
1615 (set! inner-module #f))
1618 (set! inner-module (current-module))
1619 (set-current-module outer-module)
1620 (set! outer-module #f)))))
1622 (define basic-load load)
1624 (define (load-module filename . reader)
1625 (save-module-excursion
1627 (let ((oldname (and (current-load-port)
1628 (port-filename (current-load-port)))))
1631 (> (string-length filename) 0)
1632 (not (char=? (string-ref filename 0) #\/))
1633 (not (string=? (dirname oldname) ".")))
1634 (string-append (dirname oldname) "/" filename)
1641 ;;; {MODULE-REF -- exported}
1644 ;; Returns the value of a variable called NAME in MODULE or any of its
1645 ;; used modules. If there is no such variable, then if the optional third
1646 ;; argument DEFAULT is present, it is returned; otherwise an error is signaled.
1648 (define (module-ref module name . rest)
1649 (let ((variable (module-variable module name)))
1650 (if (and variable (variable-bound? variable))
1651 (variable-ref variable)
1653 (error "No variable named" name 'in module)
1654 (car rest) ; default value
1657 ;; MODULE-SET! -- exported
1659 ;; Sets the variable called NAME in MODULE (or in a module that MODULE uses)
1660 ;; to VALUE; if there is no such variable, an error is signaled.
1662 (define (module-set! module name value)
1663 (let ((variable (module-variable module name)))
1665 (variable-set! variable value)
1666 (error "No variable named" name 'in module))))
1668 ;; MODULE-DEFINE! -- exported
1670 ;; Sets the variable called NAME in MODULE to VALUE; if there is no such
1671 ;; variable, it is added first.
1673 (define (module-define! module name value)
1674 (let ((variable (module-local-variable module name)))
1677 (variable-set! variable value)
1678 (module-modified module))
1679 (let ((variable (make-variable value)))
1680 (module-add! module name variable)))))
1682 ;; MODULE-DEFINED? -- exported
1684 ;; Return #t iff NAME is defined in MODULE (or in a module that MODULE
1687 (define (module-defined? module name)
1688 (let ((variable (module-variable module name)))
1689 (and variable (variable-bound? variable))))
1691 ;; MODULE-USE! module interface
1693 ;; Add INTERFACE to the list of interfaces used by MODULE.
1695 (define (module-use! module interface)
1696 (if (not (or (eq? module interface)
1697 (memq interface (module-uses module))))
1699 ;; Newly used modules must be appended rather than consed, so that
1700 ;; `module-variable' traverses the use list starting from the first
1702 (set-module-uses! module
1703 (append (filter (lambda (m)
1705 (equal? (module-name m)
1706 (module-name interface))))
1707 (module-uses module))
1710 (module-modified module))))
1712 ;; MODULE-USE-INTERFACES! module interfaces
1714 ;; Same as MODULE-USE! but add multiple interfaces and check for duplicates
1716 (define (module-use-interfaces! module interfaces)
1717 (set-module-uses! module
1718 (append (module-uses module) interfaces))
1719 (module-modified module))
1723 ;;; {Recursive Namespaces}
1725 ;;; A hierarchical namespace emerges if we consider some module to be
1726 ;;; root, and variables bound to modules as nested namespaces.
1728 ;;; The routines in this file manage variable names in hierarchical namespace.
1729 ;;; Each variable name is a list of elements, looked up in successively nested
1732 ;;; (nested-ref some-root-module '(foo bar baz))
1733 ;;; => <value of a variable named baz in the module bound to bar in
1734 ;;; the module bound to foo in some-root-module>
1739 ;;; ;; a-root is a module
1740 ;;; ;; name is a list of symbols
1742 ;;; nested-ref a-root name
1743 ;;; nested-set! a-root name val
1744 ;;; nested-define! a-root name val
1745 ;;; nested-remove! a-root name
1748 ;;; (current-module) is a natural choice for a-root so for convenience there are
1751 ;;; local-ref name == nested-ref (current-module) name
1752 ;;; local-set! name val == nested-set! (current-module) name val
1753 ;;; local-define! name val == nested-define! (current-module) name val
1754 ;;; local-remove! name == nested-remove! (current-module) name
1758 (define (nested-ref root names)
1759 (let loop ((cur root)
1763 ((not (module? cur)) #f)
1764 (else (loop (module-ref cur (car elts) #f) (cdr elts))))))
1766 (define (nested-set! root names val)
1767 (let loop ((cur root)
1769 (if (null? (cdr elts))
1770 (module-set! cur (car elts) val)
1771 (loop (module-ref cur (car elts)) (cdr elts)))))
1773 (define (nested-define! root names val)
1774 (let loop ((cur root)
1776 (if (null? (cdr elts))
1777 (module-define! cur (car elts) val)
1778 (loop (module-ref cur (car elts)) (cdr elts)))))
1780 (define (nested-remove! root names)
1781 (let loop ((cur root)
1783 (if (null? (cdr elts))
1784 (module-remove! cur (car elts))
1785 (loop (module-ref cur (car elts)) (cdr elts)))))
1787 (define (local-ref names) (nested-ref (current-module) names))
1788 (define (local-set! names val) (nested-set! (current-module) names val))
1789 (define (local-define names val) (nested-define! (current-module) names val))
1790 (define (local-remove names) (nested-remove! (current-module) names))
1795 ;;; {The (%app) module}
1797 ;;; The root of conventionally named objects not directly in the top level.
1800 ;;; (%app modules guile)
1802 ;;; The directory of all modules and the standard root module.
1805 ;; module-public-interface is defined in C.
1806 (define (set-module-public-interface! m i)
1807 (module-define! m '%module-public-interface i))
1808 (define (set-system-module! m s)
1809 (set-procedure-property! (module-eval-closure m) 'system-module s))
1810 (define the-root-module (make-root-module))
1811 (define the-scm-module (make-scm-module))
1812 (set-module-public-interface! the-root-module the-scm-module)
1813 (set-module-name! the-root-module '(guile))
1814 (set-module-name! the-scm-module '(guile))
1815 (set-module-kind! the-scm-module 'interface)
1816 (set-system-module! the-root-module #t)
1817 (set-system-module! the-scm-module #t)
1819 ;; NOTE: This binding is used in libguile/modules.c.
1821 (define (make-modules-in module name)
1825 (let* ((var (module-local-variable module (car name)))
1826 (val (and var (variable-bound? var) (variable-ref var))))
1829 (let ((m (make-module 31)))
1830 (set-module-kind! m 'directory)
1831 (set-module-name! m (append (or (module-name module) '())
1833 (module-define! module (car name) m)
1837 (define (beautify-user-module! module)
1838 (let ((interface (module-public-interface module)))
1839 (if (or (not interface)
1840 (eq? interface module))
1841 (let ((interface (make-module 31)))
1842 (set-module-name! interface (module-name module))
1843 (set-module-kind! interface 'interface)
1844 (set-module-public-interface! module interface))))
1845 (if (and (not (memq the-scm-module (module-uses module)))
1846 (not (eq? module the-root-module)))
1847 ;; Import the default set of bindings (from the SCM module) in MODULE.
1848 (module-use! module the-scm-module)))
1850 ;; NOTE: This binding is used in libguile/modules.c.
1852 (define resolve-module
1853 (let ((the-root-module the-root-module))
1854 (lambda (name . maybe-autoload)
1855 (if (equal? name '(guile))
1857 (let ((full-name (append '(%app modules) name)))
1858 (let ((already (nested-ref the-root-module full-name))
1859 (autoload (or (null? maybe-autoload) (car maybe-autoload))))
1861 ((and already (module? already)
1862 (or (not autoload) (module-public-interface already)))
1863 ;; A hit, a palpable hit.
1866 ;; Try to autoload the module, and recurse.
1867 (try-load-module name)
1868 (resolve-module name #f))
1870 ;; A module is not bound (but maybe something else is),
1871 ;; we're not autoloading -- here's the weird semantics,
1872 ;; we create an empty module.
1873 (make-modules-in the-root-module full-name)))))))))
1875 ;; Cheat. These bindings are needed by modules.c, but we don't want
1876 ;; to move their real definition here because that would be unnatural.
1878 (define try-module-autoload #f)
1879 (define process-define-module #f)
1880 (define process-use-modules #f)
1881 (define module-export! #f)
1882 (define default-duplicate-binding-procedures #f)
1884 (define %app (make-module 31))
1885 (define app %app) ;; for backwards compatability
1887 (local-define '(%app modules) (make-module 31))
1888 (local-define '(%app modules guile) the-root-module)
1890 ;; This boots the module system. All bindings needed by modules.c
1891 ;; must have been defined by now.
1893 (set-current-module the-root-module)
1894 ;; definition deferred for syncase's benefit
1895 (define module-name (record-accessor module-type 'name))
1897 ;; (define-special-value '(%app modules new-ws) (lambda () (make-scm-module)))
1899 (define (try-load-module name)
1900 (try-module-autoload name))
1902 (define (purify-module! module)
1903 "Removes bindings in MODULE which are inherited from the (guile) module."
1904 (let ((use-list (module-uses module)))
1905 (if (and (pair? use-list)
1906 (eq? (car (last-pair use-list)) the-scm-module))
1907 (set-module-uses! module (reverse (cdr (reverse use-list)))))))
1909 ;; Return a module that is an interface to the module designated by
1912 ;; `resolve-interface' takes four keyword arguments:
1914 ;; #:select SELECTION
1916 ;; SELECTION is a list of binding-specs to be imported; A binding-spec
1917 ;; is either a symbol or a pair of symbols (ORIG . SEEN), where ORIG
1918 ;; is the name in the used module and SEEN is the name in the using
1919 ;; module. Note that SEEN is also passed through RENAMER, below. The
1920 ;; default is to select all bindings. If you specify no selection but
1921 ;; a renamer, only the bindings that already exist in the used module
1922 ;; are made available in the interface. Bindings that are added later
1923 ;; are not picked up.
1927 ;; BINDINGS is a list of bindings which should not be imported.
1931 ;; PREFIX is a symbol that will be appended to each exported name.
1932 ;; The default is to not perform any renaming.
1934 ;; #:renamer RENAMER
1936 ;; RENAMER is a procedure that takes a symbol and returns its new
1937 ;; name. The default is not perform any renaming.
1939 ;; Signal "no code for module" error if module name is not resolvable
1940 ;; or its public interface is not available. Signal "no binding"
1941 ;; error if selected binding does not exist in the used module.
1943 (define (resolve-interface name . args)
1945 (define (get-keyword-arg args kw def)
1946 (cond ((memq kw args)
1948 (if (null? (cdr kw-arg))
1949 (error "keyword without value: " kw))
1954 (let* ((select (get-keyword-arg args #:select #f))
1955 (hide (get-keyword-arg args #:hide '()))
1956 (renamer (or (get-keyword-arg args #:renamer #f)
1957 (let ((prefix (get-keyword-arg args #:prefix #f)))
1958 (and prefix (symbol-prefix-proc prefix)))
1960 (module (resolve-module name))
1961 (public-i (and module (module-public-interface module))))
1962 (and (or (not module) (not public-i))
1963 (error "no code for module" name))
1964 (if (and (not select) (null? hide) (eq? renamer identity))
1966 (let ((selection (or select (module-map (lambda (sym var) sym)
1968 (custom-i (make-module 31)))
1969 (set-module-kind! custom-i 'custom-interface)
1970 (set-module-name! custom-i name)
1971 ;; XXX - should use a lazy binder so that changes to the
1972 ;; used module are picked up automatically.
1973 (for-each (lambda (bspec)
1974 (let* ((direct? (symbol? bspec))
1975 (orig (if direct? bspec (car bspec)))
1976 (seen (if direct? bspec (cdr bspec)))
1977 (var (or (module-local-variable public-i orig)
1978 (module-local-variable module orig)
1980 ;; fixme: format manually for now
1982 #f "no binding `~A' in module ~A"
1984 (if (memq orig hide)
1985 (set! hide (delq! orig hide))
1986 (module-add! custom-i
1990 ;; Check that we are not hiding bindings which don't exist
1991 (for-each (lambda (binding)
1992 (if (not (module-local-variable public-i binding))
1995 #f "no binding `~A' to hide in module ~A"
2000 (define (symbol-prefix-proc prefix)
2002 (symbol-append prefix symbol)))
2004 ;; This function is called from "modules.c". If you change it, be
2005 ;; sure to update "modules.c" as well.
2007 (define (process-define-module args)
2008 (let* ((module-id (car args))
2009 (module (resolve-module module-id #f))
2011 (unrecognized (lambda (arg)
2012 (error "unrecognized define-module argument" arg))))
2013 (beautify-user-module! module)
2014 (let loop ((kws kws)
2015 (reversed-interfaces '())
2022 (call-with-deferred-observers
2024 (module-use-interfaces! module (reverse reversed-interfaces))
2025 (module-export! module exports)
2026 (module-replace! module replacements)
2027 (module-re-export! module re-exports)
2028 (if (not (null? autoloads))
2029 (apply module-autoload! module autoloads))))
2031 ((#:use-module #:use-syntax)
2032 (or (pair? (cdr kws))
2035 ((equal? (caadr kws) '(ice-9 syncase))
2036 (issue-deprecation-warning
2037 "(ice-9 syncase) is deprecated. Support for syntax-case is now in Guile core.")
2045 (let* ((interface-args (cadr kws))
2046 (interface (apply resolve-interface interface-args)))
2047 (and (eq? (car kws) #:use-syntax)
2048 (or (symbol? (caar interface-args))
2049 (error "invalid module name for use-syntax"
2050 (car interface-args)))
2051 (set-module-transformer!
2053 (module-ref interface
2054 (car (last-pair (car interface-args)))
2057 (cons interface reversed-interfaces)
2063 (or (and (pair? (cdr kws)) (pair? (cddr kws)))
2070 (let ((name (cadr kws))
2071 (bindings (caddr kws)))
2072 (cons* name bindings autoloads))))
2074 (set-system-module! module #t)
2075 (loop (cdr kws) reversed-interfaces exports re-exports
2076 replacements autoloads))
2078 (purify-module! module)
2079 (loop (cdr kws) reversed-interfaces exports re-exports
2080 replacements autoloads))
2082 (if (not (pair? (cdr kws)))
2084 (set-module-duplicates-handlers!
2086 (lookup-duplicates-handlers (cadr kws)))
2087 (loop (cddr kws) reversed-interfaces exports re-exports
2088 replacements autoloads))
2089 ((#:export #:export-syntax)
2090 (or (pair? (cdr kws))
2094 (append (cadr kws) exports)
2098 ((#:re-export #:re-export-syntax)
2099 (or (pair? (cdr kws))
2104 (append (cadr kws) re-exports)
2107 ((#:replace #:replace-syntax)
2108 (or (pair? (cdr kws))
2114 (append (cadr kws) replacements)
2117 (unrecognized kws)))))
2118 (run-hook module-defined-hook module)
2121 ;; `module-defined-hook' is a hook that is run whenever a new module
2122 ;; is defined. Its members are called with one argument, the new
2124 (define module-defined-hook (make-hook 1))
2131 (define (make-autoload-interface module name bindings)
2132 (let ((b (lambda (a sym definep)
2133 (and (memq sym bindings)
2134 (let ((i (module-public-interface (resolve-module name))))
2136 (error "missing interface for module" name))
2137 (let ((autoload (memq a (module-uses module))))
2138 ;; Replace autoload-interface with actual interface if
2139 ;; that has not happened yet.
2140 (if (pair? autoload)
2141 (set-car! autoload i)))
2142 (module-local-variable i sym))))))
2143 (module-constructor (make-hash-table 0) '() b #f #f name 'autoload #f
2144 (make-hash-table 0) '() (make-weak-value-hash-table 31))))
2146 (define (module-autoload! module . args)
2147 "Have @var{module} automatically load the module named @var{name} when one
2148 of the symbols listed in @var{bindings} is looked up. @var{args} should be a
2149 list of module-name/binding-list pairs, e.g., as in @code{(module-autoload!
2150 module '(ice-9 q) '(make-q q-length))}."
2151 (let loop ((args args))
2155 (error "invalid name+binding autoload list" args))
2157 (let ((name (car args))
2158 (bindings (cadr args)))
2159 (module-use! module (make-autoload-interface module
2161 (loop (cddr args)))))))
2166 ;;; {Autoloading modules}
2169 (define autoloads-in-progress '())
2171 ;; This function is called from "modules.c". If you change it, be
2172 ;; sure to update "modules.c" as well.
2174 (define (try-module-autoload module-name)
2175 (let* ((reverse-name (reverse module-name))
2176 (name (symbol->string (car reverse-name)))
2177 (dir-hint-module-name (reverse (cdr reverse-name)))
2178 (dir-hint (apply string-append
2180 (string-append (symbol->string elt) "/"))
2181 dir-hint-module-name))))
2182 (resolve-module dir-hint-module-name #f)
2183 (and (not (autoload-done-or-in-progress? dir-hint name))
2185 (define (load-file proc file)
2186 (save-module-excursion (lambda () (proc file)))
2189 (lambda () (autoload-in-progress! dir-hint name))
2191 (let ((file (in-vicinity dir-hint name)))
2192 (let ((compiled (and load-compiled
2194 (string-append file ".go"))))
2195 (source (%search-load-path file)))
2198 (< (stat:mtime (stat compiled))
2199 (stat:mtime (stat source)))))
2201 (warn "source file" source "newer than" compiled))
2202 (with-fluid* current-reader #f
2203 (lambda () (load-file primitive-load source))))
2205 (load-file load-compiled compiled))))))
2206 (lambda () (set-autoloaded! dir-hint name didit)))
2211 ;;; {Dynamic linking of modules}
2214 (define autoloads-done '((guile . guile)))
2216 (define (autoload-done-or-in-progress? p m)
2217 (let ((n (cons p m)))
2218 (->bool (or (member n autoloads-done)
2219 (member n autoloads-in-progress)))))
2221 (define (autoload-done! p m)
2222 (let ((n (cons p m)))
2223 (set! autoloads-in-progress
2224 (delete! n autoloads-in-progress))
2225 (or (member n autoloads-done)
2226 (set! autoloads-done (cons n autoloads-done)))))
2228 (define (autoload-in-progress! p m)
2229 (let ((n (cons p m)))
2230 (set! autoloads-done
2231 (delete! n autoloads-done))
2232 (set! autoloads-in-progress (cons n autoloads-in-progress))))
2234 (define (set-autoloaded! p m done?)
2236 (autoload-done! p m)
2237 (let ((n (cons p m)))
2238 (set! autoloads-done (delete! n autoloads-done))
2239 (set! autoloads-in-progress (delete! n autoloads-in-progress)))))
2243 ;;; {Run-time options}
2246 (defmacro define-option-interface (option-group)
2247 (let* ((option-name car)
2249 (option-documentation caddr)
2251 ;; Below follow the macros defining the run-time option interfaces.
2253 (make-options (lambda (interface)
2255 (cond ((null? args) (,interface))
2257 (,interface (car args)) (,interface))
2260 (display (option-name option))
2261 (if (< (string-length
2262 (symbol->string (option-name option)))
2266 (display (option-value option))
2268 (display (option-documentation option))
2270 (,interface #t)))))))
2272 (make-enable (lambda (interface)
2274 (,interface (append flags (,interface)))
2277 (make-disable (lambda (interface)
2279 (let ((options (,interface)))
2280 (for-each (lambda (flag)
2281 (set! options (delq! flag options)))
2283 (,interface options)
2285 (let* ((interface (car option-group))
2286 (options/enable/disable (cadr option-group)))
2288 (define ,(car options/enable/disable)
2289 ,(make-options interface))
2290 (define ,(cadr options/enable/disable)
2291 ,(make-enable interface))
2292 (define ,(caddr options/enable/disable)
2293 ,(make-disable interface))
2294 (defmacro ,(caaddr option-group) (opt val)
2295 `(,',(car options/enable/disable)
2296 (append (,',(car options/enable/disable))
2297 (list ',opt ,val))))))))
2299 (define-option-interface
2300 (eval-options-interface
2301 (eval-options eval-enable eval-disable)
2304 (define-option-interface
2305 (debug-options-interface
2306 (debug-options debug-enable debug-disable)
2309 (define-option-interface
2310 (evaluator-traps-interface
2311 (traps trap-enable trap-disable)
2314 (define-option-interface
2315 (read-options-interface
2316 (read-options read-enable read-disable)
2319 (define-option-interface
2320 (print-options-interface
2321 (print-options print-enable print-disable)
2329 (define (repl read evaler print)
2330 (let loop ((source (read (current-input-port))))
2331 (print (evaler source))
2332 (loop (read (current-input-port)))))
2334 ;; A provisional repl that acts like the SCM repl:
2336 (define scm-repl-silent #f)
2337 (define (assert-repl-silence v) (set! scm-repl-silent v))
2339 (define *unspecified* (if #f #f))
2340 (define (unspecified? v) (eq? v *unspecified*))
2342 (define scm-repl-print-unspecified #f)
2343 (define (assert-repl-print-unspecified v) (set! scm-repl-print-unspecified v))
2345 (define scm-repl-verbose #f)
2346 (define (assert-repl-verbosity v) (set! scm-repl-verbose v))
2348 (define scm-repl-prompt "guile> ")
2350 (define (set-repl-prompt! v) (set! scm-repl-prompt v))
2352 (define (default-pre-unwind-handler key . args)
2353 (save-stack pre-unwind-handler-dispatch)
2354 (apply throw key args))
2356 (define (pre-unwind-handler-dispatch key . args)
2357 (apply default-pre-unwind-handler key args))
2359 (define abort-hook (make-hook))
2361 ;; these definitions are used if running a script.
2362 ;; otherwise redefined in error-catching-loop.
2363 (define (set-batch-mode?! arg) #t)
2364 (define (batch-mode?) #t)
2366 (define (error-catching-loop thunk)
2369 (define (loop first)
2374 (call-with-unblocked-asyncs
2380 ;; This line is needed because mark
2381 ;; doesn't do closures quite right.
2382 ;; Unreferenced locals should be
2385 (let loop ((v (thunk)))
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)))))))
2434 ;; Note that having just `pre-unwind-handler-dispatch'
2435 ;; here is connected with the mechanism that
2436 ;; produces a nice backtrace upon error. If, for
2437 ;; example, this is replaced with (lambda args
2438 ;; (apply pre-unwind-handler-dispatch args)), the stack
2439 ;; cutting (in save-stack) goes wrong and ends up
2440 ;; saving no stack at all, so there is no
2442 pre-unwind-handler-dispatch)))
2444 (if next (loop next) status)))
2445 (set! set-batch-mode?! (lambda (arg)
2447 (set! interactive #f)
2450 (error "sorry, not implemented")))))
2451 (set! batch-mode? (lambda () (not interactive)))
2452 (call-with-blocked-asyncs
2453 (lambda () (loop (lambda () #t))))))
2455 ;;(define the-last-stack (make-fluid)) Defined by scm_init_backtrace ()
2456 (define before-signal-stack (make-fluid))
2457 (define stack-saved? #f)
2459 (define (save-stack . narrowing)
2461 (cond ((not (memq 'debug (debug-options-interface)))
2462 (fluid-set! the-last-stack #f)
2463 (set! stack-saved? #t))
2469 (apply make-stack #t save-stack primitive-eval #t 0 narrowing))
2471 (apply make-stack #t save-stack 0 #t 0 narrowing))
2473 (apply make-stack #t save-stack tk-stack-mark #t 0 narrowing))
2475 (apply make-stack #t save-stack 0 1 narrowing))
2477 (let ((id (stack-id #t)))
2478 (and (procedure? id)
2479 (apply make-stack #t save-stack id #t 0 narrowing))))))
2480 (set! stack-saved? #t)))))
2482 (define before-error-hook (make-hook))
2483 (define after-error-hook (make-hook))
2484 (define before-backtrace-hook (make-hook))
2485 (define after-backtrace-hook (make-hook))
2487 (define has-shown-debugger-hint? #f)
2489 (define (handle-system-error key . args)
2490 (let ((cep (current-error-port)))
2491 (cond ((not (stack? (fluid-ref the-last-stack))))
2492 ((memq 'backtrace (debug-options-interface))
2493 (let ((highlights (if (or (eq? key 'wrong-type-arg)
2494 (eq? key 'out-of-range))
2497 (run-hook before-backtrace-hook)
2499 (display "Backtrace:\n")
2500 (display-backtrace (fluid-ref the-last-stack) cep
2503 (run-hook after-backtrace-hook))))
2504 (run-hook before-error-hook)
2505 (apply display-error (fluid-ref the-last-stack) cep args)
2506 (run-hook after-error-hook)
2508 (throw 'abort key)))
2510 (define (quit . args)
2511 (apply throw 'quit args))
2515 ;;(define has-shown-backtrace-hint? #f) Defined by scm_init_backtrace ()
2517 ;; Replaced by C code:
2518 ;;(define (backtrace)
2519 ;; (if (fluid-ref the-last-stack)
2522 ;; (display-backtrace (fluid-ref the-last-stack) (current-output-port))
2524 ;; (if (and (not has-shown-backtrace-hint?)
2525 ;; (not (memq 'backtrace (debug-options-interface))))
2528 ;;"Type \"(debug-enable 'backtrace)\" if you would like a backtrace
2529 ;;automatically if an error occurs in the future.\n")
2530 ;; (set! has-shown-backtrace-hint? #t))))
2531 ;; (display "No backtrace available.\n")))
2533 (define (error-catching-repl r e p)
2534 (error-catching-loop
2536 (call-with-values (lambda () (e (r)))
2537 (lambda the-values (for-each p the-values))))))
2539 (define (gc-run-time)
2540 (cdr (assq 'gc-time-taken (gc-stats))))
2542 (define before-read-hook (make-hook))
2543 (define after-read-hook (make-hook))
2544 (define before-eval-hook (make-hook 1))
2545 (define after-eval-hook (make-hook 1))
2546 (define before-print-hook (make-hook 1))
2547 (define after-print-hook (make-hook 1))
2549 ;;; The default repl-reader function. We may override this if we've
2550 ;;; the readline library.
2553 (display (if (string? prompt) prompt (prompt)))
2555 (run-hook before-read-hook)
2556 ((or (fluid-ref current-reader) read) (current-input-port))))
2558 (define (scm-style-repl)
2563 (repl-report-start-timing (lambda ()
2564 (set! start-gc-rt (gc-run-time))
2565 (set! start-rt (get-internal-run-time))))
2566 (repl-report (lambda ()
2568 (display (inexact->exact
2569 (* 1000 (/ (- (get-internal-run-time) start-rt)
2570 internal-time-units-per-second))))
2572 (display (inexact->exact
2573 (* 1000 (/ (- (gc-run-time) start-gc-rt)
2574 internal-time-units-per-second))))
2575 (display " msec in gc)\n")))
2577 (consume-trailing-whitespace
2579 (let ((ch (peek-char)))
2582 ((or (char=? ch #\space) (char=? ch #\tab))
2584 (consume-trailing-whitespace))
2585 ((char=? ch #\newline)
2589 (let ((prompt (cond ((string? scm-repl-prompt)
2591 ((thunk? scm-repl-prompt)
2593 (scm-repl-prompt "> ")
2595 (repl-reader prompt))))
2597 ;; As described in R4RS, the READ procedure updates the
2598 ;; port to point to the first character past the end of
2599 ;; the external representation of the object. This
2600 ;; means that it doesn't consume the newline typically
2601 ;; found after an expression. This means that, when
2602 ;; debugging Guile with GDB, GDB gets the newline, which
2603 ;; it often interprets as a "continue" command, making
2604 ;; breakpoints kind of useless. So, consume any
2605 ;; trailing newline here, as well as any whitespace
2607 ;; But not if EOF, for control-D.
2608 (if (not (eof-object? val))
2609 (consume-trailing-whitespace))
2610 (run-hook after-read-hook)
2611 (if (eof-object? val)
2613 (repl-report-start-timing)
2614 (if scm-repl-verbose
2617 (display ";;; EOF -- quitting")
2622 (-eval (lambda (sourc)
2623 (repl-report-start-timing)
2624 (run-hook before-eval-hook sourc)
2625 (let ((val (start-stack 'repl-stack
2626 ;; If you change this procedure
2627 ;; (primitive-eval), please also
2628 ;; modify the repl-stack case in
2629 ;; save-stack so that stack cutting
2630 ;; continues to work.
2631 (primitive-eval sourc))))
2632 (run-hook after-eval-hook sourc)
2636 (-print (let ((maybe-print (lambda (result)
2637 (if (or scm-repl-print-unspecified
2638 (not (unspecified? result)))
2643 (if (not scm-repl-silent)
2645 (run-hook before-print-hook result)
2646 (maybe-print result)
2647 (run-hook after-print-hook result)
2648 (if scm-repl-verbose
2652 (-quit (lambda (args)
2653 (if scm-repl-verbose
2655 (display ";;; QUIT executed, repl exitting")
2661 (if scm-repl-verbose
2663 (display ";;; ABORT executed.")
2666 (repl -read -eval -print))))
2668 (let ((status (error-catching-repl -read
2676 ;;; {IOTA functions: generating lists of numbers}
2680 (let loop ((count (1- n)) (result '()))
2681 (if (< count 0) result
2682 (loop (1- count) (cons count result)))))
2688 ;;; Similar to `begin' but returns a list of the results of all constituent
2689 ;;; forms instead of the result of the last form.
2690 ;;; (The definition relies on the current left-to-right
2691 ;;; order of evaluation of operands in applications.)
2694 (defmacro collect forms
2702 ;; with-fluids is a convenience wrapper for the builtin procedure
2703 ;; `with-fluids*'. The syntax is just like `let':
2705 ;; (with-fluids ((fluid val)
2709 (defmacro with-fluids (bindings . body)
2710 (let ((fluids (map car bindings))
2711 (values (map cadr bindings)))
2712 (if (and (= (length fluids) 1) (= (length values) 1))
2713 `(with-fluid* ,(car fluids) ,(car values) (lambda () ,@body))
2714 `(with-fluids* (list ,@fluids) (list ,@values)
2715 (lambda () ,@body)))))
2719 ;;; with `continue' and `break'.
2722 ;; The inner `do' loop avoids re-establishing a catch every iteration,
2723 ;; that's only necessary if continue is actually used. A new key is
2724 ;; generated every time, so break and continue apply to their originating
2725 ;; `while' even when recursing.
2727 ;; FIXME: This macro is unintentionally unhygienic with respect to let,
2728 ;; make-symbol, do, throw, catch, lambda, and not.
2730 (define-macro (while cond . body)
2731 (let ((keyvar (make-symbol "while-keyvar")))
2732 `(let ((,keyvar (make-symbol "while-key")))
2736 (let ((break (lambda () (throw ,keyvar #t)))
2737 (continue (lambda () (throw ,keyvar #f))))
2748 ;;; {Module System Macros}
2751 ;; Return a list of expressions that evaluate to the appropriate
2752 ;; arguments for resolve-interface according to SPEC.
2756 (if (memq 'prefix (read-options))
2757 (error "boot-9 must be compiled with #:kw, not :kw")))
2759 (define (compile-interface-spec spec)
2760 (define (make-keyarg sym key quote?)
2761 (cond ((or (memq sym spec)
2765 (list key (list 'quote (cadr rest)))
2766 (list key (cadr rest)))))
2769 (define (map-apply func list)
2770 (map (lambda (args) (apply func args)) list))
2773 '((:select #:select #t)
2775 (:prefix #:prefix #t)
2776 (:renamer #:renamer #f)))
2777 (if (not (pair? (car spec)))
2780 ,@(apply append (map-apply make-keyarg keys)))))
2782 (define (keyword-like-symbol->keyword sym)
2783 (symbol->keyword (string->symbol (substring (symbol->string sym) 1))))
2785 (define (compile-define-module-args args)
2786 ;; Just quote everything except #:use-module and #:use-syntax. We
2787 ;; need to know about all arguments regardless since we want to turn
2788 ;; symbols that look like keywords into real keywords, and the
2789 ;; keyword args in a define-module form are not regular
2790 ;; (i.e. no-backtrace doesn't take a value).
2791 (let loop ((compiled-args `((quote ,(car args))))
2794 (reverse! compiled-args))
2795 ;; symbol in keyword position
2796 ((symbol? (car args))
2798 (cons (keyword-like-symbol->keyword (car args)) (cdr args))))
2799 ((memq (car args) '(#:no-backtrace #:pure))
2800 (loop (cons (car args) compiled-args)
2803 (error "keyword without value:" (car args)))
2804 ((memq (car args) '(#:use-module #:use-syntax))
2805 (loop (cons* `(list ,@(compile-interface-spec (cadr args)))
2809 ((eq? (car args) #:autoload)
2810 (loop (cons* `(quote ,(caddr args))
2811 `(quote ,(cadr args))
2816 (loop (cons* `(quote ,(cadr args))
2821 (defmacro define-module args
2824 (let ((m (process-define-module
2825 (list ,@(compile-define-module-args args)))))
2826 (set-current-module m)
2829 ;; The guts of the use-modules macro. Add the interfaces of the named
2830 ;; modules to the use-list of the current module, in order.
2832 ;; This function is called by "modules.c". If you change it, be sure
2833 ;; to change scm_c_use_module as well.
2835 (define (process-use-modules module-interface-args)
2836 (let ((interfaces (map (lambda (mif-args)
2837 (or (apply resolve-interface mif-args)
2838 (error "no such module" mif-args)))
2839 module-interface-args)))
2840 (call-with-deferred-observers
2842 (module-use-interfaces! (current-module) interfaces)))))
2844 (defmacro use-modules modules
2847 (process-use-modules
2848 (list ,@(map (lambda (m)
2849 `(list ,@(compile-interface-spec m)))
2853 (defmacro use-syntax (spec)
2856 (issue-deprecation-warning
2857 "`use-syntax' is deprecated. Please contact guile-devel for more info.")
2858 (process-use-modules (list (list ,@(compile-interface-spec spec))))
2861 ;; Dirk:FIXME:: This incorrect (according to R5RS) syntax needs to be changed
2862 ;; as soon as guile supports hygienic macros.
2863 (define-syntax define-private
2868 (define-syntax define-public
2870 ((_ (name . args) . body)
2871 (define-public name (lambda args . body)))
2877 (define-syntax defmacro-public
2879 ((_ name args . body)
2881 (defmacro name args . body)
2882 (export-syntax name)))))
2884 ;; Export a local variable
2886 ;; This function is called from "modules.c". If you change it, be
2887 ;; sure to update "modules.c" as well.
2889 (define (module-export! m names)
2890 (let ((public-i (module-public-interface m)))
2891 (for-each (lambda (name)
2892 (let ((var (module-ensure-local-variable! m name)))
2893 (module-add! public-i name var)))
2896 (define (module-replace! m names)
2897 (let ((public-i (module-public-interface m)))
2898 (for-each (lambda (name)
2899 (let ((var (module-ensure-local-variable! m name)))
2900 (set-object-property! var 'replace #t)
2901 (module-add! public-i name var)))
2904 ;; Re-export a imported variable
2906 (define (module-re-export! m names)
2907 (let ((public-i (module-public-interface m)))
2908 (for-each (lambda (name)
2909 (let ((var (module-variable m name)))
2911 (error "Undefined variable:" name))
2912 ((eq? var (module-local-variable m name))
2913 (error "re-exporting local variable:" name))
2915 (module-add! public-i name var)))))
2918 (defmacro export names
2919 `(call-with-deferred-observers
2921 (module-export! (current-module) ',names))))
2923 (defmacro re-export names
2924 `(call-with-deferred-observers
2926 (module-re-export! (current-module) ',names))))
2928 (defmacro export-syntax names
2931 (defmacro re-export-syntax names
2932 `(re-export ,@names))
2934 (define load load-module)
2938 ;;; {Compiler interface}
2940 ;;; The full compiler interface can be found in (system). Here we put a
2941 ;;; few useful procedures into the global namespace.
2943 (module-autoload! the-scm-module
2944 '(system base compile)
2946 compile-time-environment))
2954 (define make-mutable-parameter
2955 (let ((make (lambda (fluid converter)
2959 (fluid-set! fluid (converter (car args))))))))
2960 (lambda (init . converter)
2961 (let ((fluid (make-fluid))
2962 (converter (if (null? converter)
2965 (fluid-set! fluid (converter init))
2966 (make fluid converter)))))
2970 ;;; {Handling of duplicate imported bindings}
2973 ;; Duplicate handlers take the following arguments:
2975 ;; module importing module
2976 ;; name conflicting name
2977 ;; int1 old interface where name occurs
2978 ;; val1 value of binding in old interface
2979 ;; int2 new interface where name occurs
2980 ;; val2 value of binding in new interface
2981 ;; var previous resolution or #f
2982 ;; val value of previous resolution
2984 ;; A duplicate handler can take three alternative actions:
2986 ;; 1. return #f => leave responsibility to next handler
2987 ;; 2. exit with an error
2988 ;; 3. return a variable resolving the conflict
2991 (define duplicate-handlers
2992 (let ((m (make-module 7)))
2994 (define (check module name int1 val1 int2 val2 var val)
2995 (scm-error 'misc-error
2997 "~A: `~A' imported from both ~A and ~A"
2998 (list (module-name module)
3004 (define (warn module name int1 val1 int2 val2 var val)
3005 (format (current-error-port)
3006 "WARNING: ~A: `~A' imported from both ~A and ~A\n"
3007 (module-name module)
3013 (define (replace module name int1 val1 int2 val2 var val)
3014 (let ((old (or (and var (object-property var 'replace) var)
3015 (module-variable int1 name)))
3016 (new (module-variable int2 name)))
3017 (if (object-property old 'replace)
3018 (and (or (eq? old new)
3019 (not (object-property new 'replace)))
3021 (and (object-property new 'replace)
3024 (define (warn-override-core module name int1 val1 int2 val2 var val)
3025 (and (eq? int1 the-scm-module)
3027 (format (current-error-port)
3028 "WARNING: ~A: imported module ~A overrides core binding `~A'\n"
3029 (module-name module)
3032 (module-local-variable int2 name))))
3034 (define (first module name int1 val1 int2 val2 var val)
3035 (or var (module-local-variable int1 name)))
3037 (define (last module name int1 val1 int2 val2 var val)
3038 (module-local-variable int2 name))
3040 (define (noop module name int1 val1 int2 val2 var val)
3043 (set-module-name! m 'duplicate-handlers)
3044 (set-module-kind! m 'interface)
3045 (module-define! m 'check check)
3046 (module-define! m 'warn warn)
3047 (module-define! m 'replace replace)
3048 (module-define! m 'warn-override-core warn-override-core)
3049 (module-define! m 'first first)
3050 (module-define! m 'last last)
3051 (module-define! m 'merge-generics noop)
3052 (module-define! m 'merge-accessors noop)
3055 (define (lookup-duplicates-handlers handler-names)
3057 (map (lambda (handler-name)
3058 (or (module-symbol-local-binding
3059 duplicate-handlers handler-name #f)
3060 (error "invalid duplicate handler name:"
3062 (if (list? handler-names)
3064 (list handler-names)))))
3066 (define default-duplicate-binding-procedures
3067 (make-mutable-parameter #f))
3069 (define default-duplicate-binding-handler
3070 (make-mutable-parameter '(replace warn-override-core warn last)
3071 (lambda (handler-names)
3072 (default-duplicate-binding-procedures
3073 (lookup-duplicates-handlers handler-names))
3078 ;;; {`cond-expand' for SRFI-0 support.}
3080 ;;; This syntactic form expands into different commands or
3081 ;;; definitions, depending on the features provided by the Scheme
3087 ;;; --> (cond-expand <cond-expand-clause>+)
3088 ;;; | (cond-expand <cond-expand-clause>* (else <command-or-definition>))
3089 ;;; <cond-expand-clause>
3090 ;;; --> (<feature-requirement> <command-or-definition>*)
3091 ;;; <feature-requirement>
3092 ;;; --> <feature-identifier>
3093 ;;; | (and <feature-requirement>*)
3094 ;;; | (or <feature-requirement>*)
3095 ;;; | (not <feature-requirement>)
3096 ;;; <feature-identifier>
3097 ;;; --> <a symbol which is the name or alias of a SRFI>
3099 ;;; Additionally, this implementation provides the
3100 ;;; <feature-identifier>s `guile' and `r5rs', so that programs can
3101 ;;; determine the implementation type and the supported standard.
3103 ;;; Currently, the following feature identifiers are supported:
3105 ;;; guile r5rs srfi-0 srfi-4 srfi-6 srfi-13 srfi-14 srfi-55 srfi-61
3107 ;;; Remember to update the features list when adding more SRFIs.
3110 (define %cond-expand-features
3111 ;; Adjust the above comment when changing this.
3114 srfi-0 ;; cond-expand itself
3115 srfi-4 ;; homogenous numeric vectors
3116 srfi-6 ;; open-input-string etc, in the guile core
3117 srfi-13 ;; string library
3118 srfi-14 ;; character sets
3119 srfi-55 ;; require-extension
3120 srfi-61 ;; general cond clause
3123 ;; This table maps module public interfaces to the list of features.
3125 (define %cond-expand-table (make-hash-table 31))
3127 ;; Add one or more features to the `cond-expand' feature list of the
3130 (define (cond-expand-provide module features)
3131 (let ((mod (module-public-interface module)))
3133 (hashq-set! %cond-expand-table mod
3134 (append (hashq-ref %cond-expand-table mod '())
3138 (procedure->memoizing-macro
3140 (let ((clauses (cdr exp))
3141 (syntax-error (lambda (cl)
3142 (error "invalid clause in `cond-expand'" cl))))
3148 (or (memq clause %cond-expand-features)
3149 (let lp ((uses (module-uses (env-module env))))
3152 (hashq-ref %cond-expand-table
3158 ((eq? 'and (car clause))
3159 (let lp ((l (cdr clause)))
3163 (and (test-clause (car l)) (lp (cdr l))))
3165 (syntax-error clause)))))
3166 ((eq? 'or (car clause))
3167 (let lp ((l (cdr clause)))
3171 (or (test-clause (car l)) (lp (cdr l))))
3173 (syntax-error clause)))))
3174 ((eq? 'not (car clause))
3175 (cond ((not (pair? (cdr clause)))
3176 (syntax-error clause))
3177 ((pair? (cddr clause))
3178 ((syntax-error clause))))
3179 (not (test-clause (cadr clause))))
3181 (syntax-error clause))))
3183 (syntax-error clause))))))
3184 (let lp ((c clauses))
3187 (error "Unfulfilled `cond-expand'"))
3190 ((not (pair? (car c)))
3191 (syntax-error (car c)))
3192 ((test-clause (caar c))
3193 `(begin ,@(cdar c)))
3194 ((eq? (caar c) 'else)
3197 `(begin ,@(cdar c)))
3199 (lp (cdr c))))))))))
3201 ;; This procedure gets called from the startup code with a list of
3202 ;; numbers, which are the numbers of the SRFIs to be loaded on startup.
3204 (define (use-srfis srfis)
3205 (process-use-modules
3207 (list (list 'srfi (string->symbol
3208 (string-append "srfi-" (number->string num))))))
3213 ;;; srfi-55: require-extension
3216 (define-macro (require-extension extension-spec)
3217 ;; This macro only handles the srfi extension, which, at present, is
3218 ;; the only one defined by the standard.
3219 (if (not (pair? extension-spec))
3220 (scm-error 'wrong-type-arg "require-extension"
3221 "Not an extension: ~S" (list extension-spec) #f))
3222 (let ((extension (car extension-spec))
3223 (extension-args (cdr extension-spec)))
3226 (let ((use-list '()))
3229 (if (not (integer? i))
3230 (scm-error 'wrong-type-arg "require-extension"
3231 "Invalid srfi name: ~S" (list i) #f))
3232 (let ((srfi-sym (string->symbol
3233 (string-append "srfi-" (number->string i)))))
3234 (if (not (memq srfi-sym %cond-expand-features))
3235 (set! use-list (cons `(use-modules (srfi ,srfi-sym))
3238 (if (pair? use-list)
3239 ;; i.e. (begin (use-modules x) (use-modules y) (use-modules z))
3240 `(begin ,@(reverse! use-list)))))
3243 'wrong-type-arg "require-extension"
3244 "Not a recognized extension type: ~S" (list extension) #f)))))
3248 ;;; {Load emacs interface support if emacs option is given.}
3251 (define (named-module-use! user usee)
3252 (module-use! (resolve-module user) (resolve-interface usee)))
3254 (define (load-emacs-interface)
3255 (and (provided? 'debug-extensions)
3256 (debug-enable 'backtrace))
3257 (named-module-use! '(guile-user) '(ice-9 emacs)))
3261 (define using-readline?
3262 (let ((using-readline? (make-fluid)))
3263 (make-procedure-with-setter
3264 (lambda () (fluid-ref using-readline?))
3265 (lambda (v) (fluid-set! using-readline? v)))))
3268 (let ((guile-user-module (resolve-module '(guile-user))))
3270 ;; Load emacs interface support if emacs option is given.
3271 (if (and (module-defined? guile-user-module 'use-emacs-interface)
3272 (module-ref guile-user-module 'use-emacs-interface))
3273 (load-emacs-interface))
3275 ;; Use some convenient modules (in reverse order)
3277 (set-current-module guile-user-module)
3278 (process-use-modules
3283 (if (provided? 'regex)
3286 (if (provided? 'threads)
3287 '(((ice-9 threads)))
3289 ;; load debugger on demand
3290 (module-autoload! guile-user-module '(ice-9 debugger) '(debug))
3292 ;; Note: SIGFPE, SIGSEGV and SIGBUS are actually "query-only" (see
3293 ;; scmsigs.c scm_sigaction_for_thread), so the handlers setup here have
3295 (let ((old-handlers #f)
3296 (start-repl (module-ref (resolve-interface '(system repl repl))
3298 (signals (if (provided? 'posix)
3299 `((,SIGINT . "User interrupt")
3300 (,SIGFPE . "Arithmetic error")
3302 . "Bad memory access (Segmentation violation)"))
3304 ;; no SIGBUS on mingw
3305 (if (defined? 'SIGBUS)
3306 (set! signals (acons SIGBUS "Bad memory access (bus error)"
3313 (let ((make-handler (lambda (msg)
3315 ;; Make a backup copy of the stack
3316 (fluid-set! before-signal-stack
3317 (fluid-ref the-last-stack))
3325 (map (lambda (sig-msg)
3326 (sigaction (car sig-msg)
3327 (make-handler (cdr sig-msg))))
3330 ;; the protected thunk.
3332 (let ((status (start-repl 'scheme)))
3333 (run-hook exit-hook)
3338 (map (lambda (sig-msg old-handler)
3339 (if (not (car old-handler))
3340 ;; restore original C handler.
3341 (sigaction (car sig-msg) #f)
3342 ;; restore Scheme handler, SIG_IGN or SIG_DFL.
3343 (sigaction (car sig-msg)
3345 (cdr old-handler))))
3346 signals old-handlers))))))
3348 ;;; This hook is run at the very end of an interactive session.
3350 (define exit-hook (make-hook))
3354 ;;; {Deprecated stuff}
3358 (define (feature? sym)
3359 (issue-deprecation-warning
3360 "`feature?' is deprecated. Use `provided?' instead.")
3364 (primitive-load-path "ice-9/deprecated"))
3368 ;;; Place the user in the guile-user module.
3371 ;;; FIXME: annotate ?
3372 ;; (define (syncase exp)
3373 ;; (with-fluids ((expansion-eval-closure
3374 ;; (module-eval-closure (current-module))))
3375 ;; (deannotate/source-properties (sc-expand (annotate exp)))))
3377 (define-module (guile-user))
3379 ;;; boot-9.scm ends here