3 ;;;; Copyright (C) 1995,1996,1997,1998,1999,2000,2001,2002,2003,2004,2005,2006,2007,2009
4 ;;;; Free Software Foundation, Inc.
6 ;;;; This library is free software; you can redistribute it and/or
7 ;;;; modify it under the terms of the GNU Lesser General Public
8 ;;;; License as published by the Free Software Foundation; either
9 ;;;; version 2.1 of the License, or (at your option) any later version.
11 ;;;; This library is distributed in the hope that it will be useful,
12 ;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
13 ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 ;;;; Lesser General Public License for more details.
16 ;;;; You should have received a copy of the GNU Lesser General Public
17 ;;;; License along with this library; if not, write to the Free Software
18 ;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
25 ;;; This file is the first thing loaded into Guile. It adds many mundane
26 ;;; definitions and a few that are interesting.
28 ;;; The module system (hence the hierarchical namespace) are defined in this
39 (primitive-load-path "ice-9/r4rs")
43 ;;; {Simple Debugging Tools}
46 ;; peek takes any number of arguments, writes them to the
47 ;; current ouput port, and returns the last argument.
48 ;; It is handy to wrap around an expression to look at
49 ;; a value each time is evaluated, e.g.:
51 ;; (+ 10 (troublesome-fn))
52 ;; => (+ 10 (pk 'troublesome-fn-returned (troublesome-fn)))
55 (define (peek . stuff)
60 (car (last-pair stuff)))
64 (define (warn . stuff)
65 (with-output-to-port (current-error-port)
68 (display ";;; WARNING ")
71 (car (last-pair stuff)))))
79 (if (not (memq sym *features*))
80 (set! *features* (cons sym *features*))))
82 ;; Return #t iff FEATURE is available to this Guile interpreter. In SLIB,
83 ;; provided? also checks to see if the module is available. We should do that
86 (define (provided? feature)
87 (and (memq feature *features*) #t))
89 ;; let format alias simple-format until the more complete version is loaded
91 (define format simple-format)
93 ;; this is scheme wrapping the C code so the final pred call is a tail call,
95 (define (string-any char_pred s . rest)
96 (let ((start (if (null? rest)
98 (end (if (or (null? rest) (null? (cdr rest)))
99 (string-length s) (cadr rest))))
100 (if (and (procedure? char_pred)
102 (<= end (string-length s))) ;; let c-code handle range error
103 (or (string-any-c-code char_pred s start (1- end))
104 (char_pred (string-ref s (1- end))))
105 (string-any-c-code char_pred s start end))))
107 ;; this is scheme wrapping the C code so the final pred call is a tail call,
109 (define (string-every char_pred s . rest)
110 (let ((start (if (null? rest)
112 (end (if (or (null? rest) (null? (cdr rest)))
113 (string-length s) (cadr rest))))
114 (if (and (procedure? char_pred)
116 (<= end (string-length s))) ;; let c-code handle range error
117 (and (string-every-c-code char_pred s start (1- end))
118 (char_pred (string-ref s (1- end))))
119 (string-every-c-code char_pred s start end))))
121 ;; A variant of string-fill! that we keep for compatability
123 (define (substring-fill! str start end fill)
124 (string-fill! str fill start end))
128 ;; Before the module system boots, there are no module names. But
129 ;; psyntax does want a module-name definition, so give it one.
130 (define (module-name x)
132 (define (module-add! module sym var)
133 (hashq-set! (%get-pre-modules-obarray) sym var))
134 (define sc-macro 'sc-macro)
135 (define (make-module-ref mod var public?)
138 (eq? mod (module-name (current-module)))
140 (not (module-variable (resolve-module mod) var))))
143 (list (if public? '@ '@@) mod var))))
144 (define (resolve-module . args)
147 (define sc-expand #f)
148 (define sc-expand3 #f)
150 (define install-global-transformer #f)
151 (define syntax-dispatch #f)
152 (define syntax-error #f)
153 (define (annotation? x) #f)
155 (define bound-identifier=? #f)
156 (define datum->syntax-object #f)
157 (define free-identifier=? #f)
158 (define generate-temporaries #f)
159 (define identifier? #f)
160 (define syntax-object->datum #f)
162 (define (void) (if #f #f))
165 (lambda (f first . rest)
168 (let andmap ((first first))
169 (let ((x (car first)) (first (cdr first)))
172 (and (f x) (andmap first)))))
173 (let andmap ((first first) (rest rest))
174 (let ((x (car first))
177 (rest (map cdr rest)))
179 (apply f (cons x xr))
180 (and (apply f (cons x xr)) (andmap first rest)))))))))
182 (define (syncase-error who format-string why what)
183 (%start-stack 'syncase-stack
185 (scm-error 'misc-error who "~A ~S" (list why what) '()))))
187 ;; Until the module system is booted, this will be the current expander.
188 (primitive-load-path "ice-9/psyntax-pp")
190 (define %pre-modules-transformer (lambda args (pk 'in args 'out (apply sc-expand args))))
194 ;; Before compiling, make sure any symbols are resolved in the (guile)
195 ;; module, the primary location of those symbols, rather than in
196 ;; (guile-user), the default module that we compile in.
199 (set-current-module (resolve-module '(guile))))
203 ;;; Depends on: features, eval-case
206 (define-syntax define-macro
209 ((_ (macro . args) . body)
210 (syntax (define-macro macro (lambda args . body))))
211 ((_ macro transformer)
215 (let ((v (syntax-object->datum y)))
216 (datum->syntax-object y (apply transformer (cdr v)))))))))))
218 (define-syntax defmacro
221 ((_ macro args . body)
222 (syntax (define-macro macro (lambda args . body)))))))
230 ;;; Depends on: defmacro
233 (defmacro begin-deprecated forms
234 (if (include-deprecated-features)
240 ;;; {Trivial Functions}
243 (define (identity x) x)
244 (define (and=> value procedure) (and value (procedure value)))
245 (define call/cc call-with-current-continuation)
247 ;;; apply-to-args is functionally redundant with apply and, worse,
248 ;;; is less general than apply since it only takes two arguments.
250 ;;; On the other hand, apply-to-args is a syntacticly convenient way to
251 ;;; perform binding in many circumstances when the "let" family of
252 ;;; of forms don't cut it. E.g.:
254 ;;; (apply-to-args (return-3d-mouse-coords)
259 (define (apply-to-args args fn) (apply fn args))
261 (defmacro false-if-exception (expr)
262 `(catch #t (lambda () ,expr)
267 ;;; {General Properties}
270 ;; This is a more modern interface to properties. It will replace all
271 ;; other property-like things eventually.
273 (define (make-object-property)
274 (let ((prop (primitive-make-property #f)))
275 (make-procedure-with-setter
276 (lambda (obj) (primitive-property-ref prop obj))
277 (lambda (obj val) (primitive-property-set! prop obj val)))))
281 ;;; {Symbol Properties}
284 (define (symbol-property sym prop)
285 (let ((pair (assoc prop (symbol-pref sym))))
286 (and pair (cdr pair))))
288 (define (set-symbol-property! sym prop val)
289 (let ((pair (assoc prop (symbol-pref sym))))
292 (symbol-pset! sym (acons prop val (symbol-pref sym))))))
294 (define (symbol-property-remove! sym prop)
295 (let ((pair (assoc prop (symbol-pref sym))))
297 (symbol-pset! sym (delq! pair (symbol-pref sym))))))
304 (define (array-shape a)
305 (map (lambda (ind) (if (number? ind) (list 0 (+ -1 ind)) ind))
306 (array-dimensions a)))
313 (define (kw-arg-ref args kw)
314 (let ((rem (member kw args)))
315 (and rem (pair? (cdr rem)) (cadr rem))))
322 (define (struct-layout s)
323 (struct-ref (struct-vtable s) vtable-index-layout))
330 ;; Printing records: by default, records are printed as
332 ;; #<type-name field1: val1 field2: val2 ...>
334 ;; You can change that by giving a custom printing function to
335 ;; MAKE-RECORD-TYPE (after the list of field symbols). This function
336 ;; will be called like
338 ;; (<printer> object port)
340 ;; It should print OBJECT to PORT.
342 (define (inherit-print-state old-port new-port)
343 (if (get-print-state old-port)
344 (port-with-print-state new-port (get-print-state old-port))
347 ;; 0: type-name, 1: fields
348 (define record-type-vtable
349 (make-vtable-vtable "prpr" 0
351 (cond ((eq? s record-type-vtable)
352 (display "#<record-type-vtable>" p))
354 (display "#<record-type " p)
355 (display (record-type-name s) p)
358 (define (record-type? obj)
359 (and (struct? obj) (eq? record-type-vtable (struct-vtable obj))))
361 (define (make-record-type type-name fields . opt)
362 (let ((printer-fn (and (pair? opt) (car opt))))
363 (let ((struct (make-struct record-type-vtable 0
366 (map (lambda (f) "pw") fields)))
370 (display type-name p)
371 (let loop ((fields fields)
374 ((not (null? fields))
376 (display (car fields) p)
378 (display (struct-ref s off) p)
379 (loop (cdr fields) (+ 1 off)))))
382 (copy-tree fields))))
383 ;; Temporary solution: Associate a name to the record type descriptor
384 ;; so that the object system can create a wrapper class for it.
385 (set-struct-vtable-name! struct (if (symbol? type-name)
387 (string->symbol type-name)))
390 (define (record-type-name obj)
391 (if (record-type? obj)
392 (struct-ref obj vtable-offset-user)
393 (error 'not-a-record-type obj)))
395 (define (record-type-fields obj)
396 (if (record-type? obj)
397 (struct-ref obj (+ 1 vtable-offset-user))
398 (error 'not-a-record-type obj)))
400 (define (record-constructor rtd . opt)
401 (let ((field-names (if (pair? opt) (car opt) (record-type-fields rtd))))
403 `(lambda ,field-names
404 (make-struct ',rtd 0 ,@(map (lambda (f)
405 (if (memq f field-names)
408 (record-type-fields rtd)))))))
410 (define (record-predicate rtd)
411 (lambda (obj) (and (struct? obj) (eq? rtd (struct-vtable obj)))))
413 (define (%record-type-error rtd obj) ;; private helper
414 (or (eq? rtd (record-type-descriptor obj))
415 (scm-error 'wrong-type-arg "%record-type-check"
416 "Wrong type record (want `~S'): ~S"
417 (list (record-type-name rtd) obj)
420 (define (record-accessor rtd field-name)
421 (let ((pos (list-index (record-type-fields rtd) field-name)))
423 (error 'no-such-field field-name))
425 (if (eq? (struct-vtable obj) rtd)
427 (%record-type-error rtd obj)))))
429 (define (record-modifier rtd field-name)
430 (let ((pos (list-index (record-type-fields rtd) field-name)))
432 (error 'no-such-field field-name))
434 (if (eq? (struct-vtable obj) rtd)
435 (struct-set! obj pos val)
436 (%record-type-error rtd obj)))))
438 (define (record? obj)
439 (and (struct? obj) (record-type? (struct-vtable obj))))
441 (define (record-type-descriptor obj)
444 (error 'not-a-record obj)))
453 (define (->bool x) (not (not x)))
460 (define (symbol-append . args)
461 (string->symbol (apply string-append (map symbol->string args))))
463 (define (list->symbol . args)
464 (string->symbol (apply list->string args)))
466 (define (symbol . args)
467 (string->symbol (apply string args)))
474 (define (list-index l k)
480 (loop (+ n 1) (cdr l))))))
484 ;;; {and-map and or-map}
486 ;;; (and-map fn lst) is like (and (fn (car lst)) (fn (cadr lst)) (fn...) ...)
487 ;;; (or-map fn lst) is like (or (fn (car lst)) (fn (cadr lst)) (fn...) ...)
492 ;; Apply f to successive elements of l until exhaustion or f returns #f.
493 ;; If returning early, return #f. Otherwise, return the last value returned
494 ;; by f. If f has never been called because l is empty, return #t.
496 (define (and-map f lst)
497 (let loop ((result #t)
502 (loop (f (car l)) (cdr l))))))
506 ;; Apply f to successive elements of l until exhaustion or while f returns #f.
507 ;; If returning early, return the return value of f.
509 (define (or-map f lst)
510 (let loop ((result #f)
514 (loop (f (car l)) (cdr l))))))
518 (if (provided? 'posix)
519 (primitive-load-path "ice-9/posix"))
521 (if (provided? 'socket)
522 (primitive-load-path "ice-9/networking"))
524 ;; For reference, Emacs file-exists-p uses stat in this same way.
525 ;; ENHANCE-ME: Catching an exception from stat is a bit wasteful, do this in
526 ;; C where all that's needed is to inspect the return from stat().
528 (if (provided? 'posix)
530 (->bool (false-if-exception (stat str))))
532 (let ((port (catch 'system-error (lambda () (open-file str OPEN_READ))
534 (if port (begin (close-port port) #t)
537 (define file-is-directory?
538 (if (provided? 'posix)
540 (eq? (stat:type (stat str)) 'directory))
542 (let ((port (catch 'system-error
543 (lambda () (open-file (string-append str "/.")
546 (if port (begin (close-port port) #t)
549 (define (has-suffix? str suffix)
550 (string-suffix? suffix str))
552 (define (system-error-errno args)
553 (if (eq? (car args) 'system-error)
554 (car (list-ref args 4))
562 (define (error . args)
565 (scm-error 'misc-error #f "?" #f #f)
566 (let loop ((msg "~A")
568 (if (not (null? rest))
569 (loop (string-append msg " ~S")
571 (scm-error 'misc-error #f msg args #f)))))
573 ;; bad-throw is the hook that is called upon a throw to a an unhandled
574 ;; key (unless the throw has four arguments, in which case
575 ;; it's usually interpreted as an error throw.)
576 ;; If the key has a default handler (a throw-handler-default property),
577 ;; it is applied to the throw.
579 (define (bad-throw key . args)
580 (let ((default (symbol-property key 'throw-handler-default)))
581 (or (and default (apply default key args))
582 (apply error "unhandled-exception:" key args))))
586 (define (tm:sec obj) (vector-ref obj 0))
587 (define (tm:min obj) (vector-ref obj 1))
588 (define (tm:hour obj) (vector-ref obj 2))
589 (define (tm:mday obj) (vector-ref obj 3))
590 (define (tm:mon obj) (vector-ref obj 4))
591 (define (tm:year obj) (vector-ref obj 5))
592 (define (tm:wday obj) (vector-ref obj 6))
593 (define (tm:yday obj) (vector-ref obj 7))
594 (define (tm:isdst obj) (vector-ref obj 8))
595 (define (tm:gmtoff obj) (vector-ref obj 9))
596 (define (tm:zone obj) (vector-ref obj 10))
598 (define (set-tm:sec obj val) (vector-set! obj 0 val))
599 (define (set-tm:min obj val) (vector-set! obj 1 val))
600 (define (set-tm:hour obj val) (vector-set! obj 2 val))
601 (define (set-tm:mday obj val) (vector-set! obj 3 val))
602 (define (set-tm:mon obj val) (vector-set! obj 4 val))
603 (define (set-tm:year obj val) (vector-set! obj 5 val))
604 (define (set-tm:wday obj val) (vector-set! obj 6 val))
605 (define (set-tm:yday obj val) (vector-set! obj 7 val))
606 (define (set-tm:isdst obj val) (vector-set! obj 8 val))
607 (define (set-tm:gmtoff obj val) (vector-set! obj 9 val))
608 (define (set-tm:zone obj val) (vector-set! obj 10 val))
610 (define (tms:clock obj) (vector-ref obj 0))
611 (define (tms:utime obj) (vector-ref obj 1))
612 (define (tms:stime obj) (vector-ref obj 2))
613 (define (tms:cutime obj) (vector-ref obj 3))
614 (define (tms:cstime obj) (vector-ref obj 4))
616 (define file-position ftell)
617 (define (file-set-position port offset . whence)
618 (let ((whence (if (eq? whence '()) SEEK_SET (car whence))))
619 (seek port offset whence)))
621 (define (move->fdes fd/port fd)
622 (cond ((integer? fd/port)
623 (dup->fdes fd/port fd)
627 (primitive-move->fdes fd/port fd)
628 (set-port-revealed! fd/port 1)
631 (define (release-port-handle port)
632 (let ((revealed (port-revealed port)))
634 (set-port-revealed! port (- revealed 1)))))
636 (define (dup->port port/fd mode . maybe-fd)
637 (let ((port (fdopen (apply dup->fdes port/fd maybe-fd)
640 (set-port-revealed! port 1))
643 (define (dup->inport port/fd . maybe-fd)
644 (apply dup->port port/fd "r" maybe-fd))
646 (define (dup->outport port/fd . maybe-fd)
647 (apply dup->port port/fd "w" maybe-fd))
649 (define (dup port/fd . maybe-fd)
650 (if (integer? port/fd)
651 (apply dup->fdes port/fd maybe-fd)
652 (apply dup->port port/fd (port-mode port/fd) maybe-fd)))
654 (define (duplicate-port port modes)
655 (dup->port port modes))
657 (define (fdes->inport fdes)
658 (let loop ((rest-ports (fdes->ports fdes)))
659 (cond ((null? rest-ports)
660 (let ((result (fdopen fdes "r")))
661 (set-port-revealed! result 1)
663 ((input-port? (car rest-ports))
664 (set-port-revealed! (car rest-ports)
665 (+ (port-revealed (car rest-ports)) 1))
668 (loop (cdr rest-ports))))))
670 (define (fdes->outport fdes)
671 (let loop ((rest-ports (fdes->ports fdes)))
672 (cond ((null? rest-ports)
673 (let ((result (fdopen fdes "w")))
674 (set-port-revealed! result 1)
676 ((output-port? (car rest-ports))
677 (set-port-revealed! (car rest-ports)
678 (+ (port-revealed (car rest-ports)) 1))
681 (loop (cdr rest-ports))))))
683 (define (port->fdes port)
684 (set-port-revealed! port (+ (port-revealed port) 1))
687 (define (setenv name value)
689 (putenv (string-append name "=" value))
692 (define (unsetenv name)
693 "Remove the entry for NAME from the environment."
701 ;;; Here for backward compatability
703 (define scheme-file-suffix (lambda () ".scm"))
705 (define (in-vicinity vicinity file)
706 (let ((tail (let ((len (string-length vicinity)))
709 (string-ref vicinity (- len 1))))))
710 (string-append vicinity
719 ;;; {Help for scm_shell}
721 ;;; The argument-processing code used by Guile-based shells generates
722 ;;; Scheme code based on the argument list. This page contains help
723 ;;; functions for the code it generates.
726 (define (command-line) (program-arguments))
728 ;; This is mostly for the internal use of the code generated by
729 ;; scm_compile_shell_switches.
731 (define (turn-on-debugging)
732 (debug-enable 'debug)
733 (debug-enable 'backtrace)
734 (read-enable 'positions))
736 (define (load-user-init)
737 (let* ((home (or (getenv "HOME")
738 (false-if-exception (passwd:dir (getpwuid (getuid))))
739 "/")) ;; fallback for cygwin etc.
740 (init-file (in-vicinity home ".guile")))
741 (if (file-exists? init-file)
742 (primitive-load init-file))))
746 ;;; {The interpreter stack}
749 (defmacro start-stack (tag exp)
750 `(%start-stack ,tag (lambda () ,exp)))
754 ;;; {Loading by paths}
757 ;;; Load a Scheme source file named NAME, searching for it in the
758 ;;; directories listed in %load-path, and applying each of the file
759 ;;; name extensions listed in %load-extensions.
760 (define (load-from-path name)
761 (start-stack 'load-stack
762 (primitive-load-path name)))
767 ;;; {Transcendental Functions}
769 ;;; Derived from "Transcen.scm", Complex trancendental functions for SCM.
770 ;;; Written by Jerry D. Hedden, (C) FSF.
771 ;;; See the file `COPYING' for terms applying to this program.
775 (let ((integer-expt integer-expt))
777 (cond ((and (exact? z2) (integer? z2))
778 (integer-expt z1 z2))
779 ((and (real? z2) (real? z1) (>= z1 0))
782 (exp (* z2 (log z1))))))))
785 (if (real? z) ($sinh z)
786 (let ((x (real-part z)) (y (imag-part z)))
787 (make-rectangular (* ($sinh x) ($cos y))
788 (* ($cosh x) ($sin y))))))
790 (if (real? z) ($cosh z)
791 (let ((x (real-part z)) (y (imag-part z)))
792 (make-rectangular (* ($cosh x) ($cos y))
793 (* ($sinh x) ($sin y))))))
795 (if (real? z) ($tanh z)
796 (let* ((x (* 2 (real-part z)))
797 (y (* 2 (imag-part z)))
798 (w (+ ($cosh x) ($cos y))))
799 (make-rectangular (/ ($sinh x) w) (/ ($sin y) w)))))
802 (if (real? z) ($asinh z)
803 (log (+ z (sqrt (+ (* z z) 1))))))
806 (if (and (real? z) (>= z 1))
808 (log (+ z (sqrt (- (* z z) 1))))))
811 (if (and (real? z) (> z -1) (< z 1))
813 (/ (log (/ (+ 1 z) (- 1 z))) 2)))
816 (if (real? z) ($sin z)
817 (let ((x (real-part z)) (y (imag-part z)))
818 (make-rectangular (* ($sin x) ($cosh y))
819 (* ($cos x) ($sinh y))))))
821 (if (real? z) ($cos z)
822 (let ((x (real-part z)) (y (imag-part z)))
823 (make-rectangular (* ($cos x) ($cosh y))
824 (- (* ($sin x) ($sinh y)))))))
826 (if (real? z) ($tan z)
827 (let* ((x (* 2 (real-part z)))
828 (y (* 2 (imag-part z)))
829 (w (+ ($cos x) ($cosh y))))
830 (make-rectangular (/ ($sin x) w) (/ ($sinh y) w)))))
833 (if (and (real? z) (>= z -1) (<= z 1))
835 (* -i (asinh (* +i z)))))
838 (if (and (real? z) (>= z -1) (<= z 1))
840 (+ (/ (angle -1) 2) (* +i (asinh (* +i z))))))
844 (if (real? z) ($atan z)
845 (/ (log (/ (- +i z) (+ +i z))) +2i))
850 ;;; {Reader Extensions}
852 ;;; Reader code for various "#c" forms.
855 (read-hash-extend #\' (lambda (c port)
858 (define read-eval? (make-fluid))
859 (fluid-set! read-eval? #f)
860 (read-hash-extend #\.
862 (if (fluid-ref read-eval?)
863 (eval (read port) (interaction-environment))
865 "#. read expansion found and read-eval? is #f."))))
869 ;;; {Command Line Options}
872 (define (get-option argv kw-opts kw-args return)
877 ((or (not (eq? #\- (string-ref (car argv) 0)))
878 (eq? (string-length (car argv)) 1))
879 (return 'normal-arg (car argv) (cdr argv)))
881 ((eq? #\- (string-ref (car argv) 1))
882 (let* ((kw-arg-pos (or (string-index (car argv) #\=)
883 (string-length (car argv))))
884 (kw (symbol->keyword (substring (car argv) 2 kw-arg-pos)))
885 (kw-opt? (member kw kw-opts))
886 (kw-arg? (member kw kw-args))
887 (arg (or (and (not (eq? kw-arg-pos (string-length (car argv))))
888 (substring (car argv)
890 (string-length (car argv))))
892 (begin (set! argv (cdr argv)) (car argv))))))
893 (if (or kw-opt? kw-arg?)
894 (return kw arg (cdr argv))
895 (return 'usage-error kw (cdr argv)))))
898 (let* ((char (substring (car argv) 1 2))
899 (kw (symbol->keyword char)))
903 (let* ((rest-car (substring (car argv) 2 (string-length (car argv))))
904 (new-argv (if (= 0 (string-length rest-car))
906 (cons (string-append "-" rest-car) (cdr argv)))))
907 (return kw #f new-argv)))
910 (let* ((rest-car (substring (car argv) 2 (string-length (car argv))))
911 (arg (if (= 0 (string-length rest-car))
914 (new-argv (if (= 0 (string-length rest-car))
917 (return kw arg new-argv)))
919 (else (return 'usage-error kw argv)))))))
921 (define (for-next-option proc argv kw-opts kw-args)
922 (let loop ((argv argv))
923 (get-option argv kw-opts kw-args
924 (lambda (opt opt-arg argv)
925 (and opt (proc opt opt-arg argv loop))))))
927 (define (display-usage-report kw-desc)
930 (or (eq? (car kw) #t)
933 (help (cadr opt-desc))
934 (opts (car opt-desc))
935 (opts-proper (if (string? (car opts)) (cdr opts) opts))
936 (arg-name (if (string? (car opts))
937 (string-append "<" (car opts) ">")
939 (left-part (string-append
940 (with-output-to-string
942 (map (lambda (x) (display (keyword->symbol x)) (display " "))
945 (middle-part (if (and (< (string-length left-part) 30)
946 (< (string-length help) 40))
947 (make-string (- 30 (string-length left-part)) #\ )
950 (display middle-part)
957 (define (transform-usage-lambda cases)
958 (let* ((raw-usage (delq! 'else (map car cases)))
959 (usage-sans-specials (map (lambda (x)
960 (or (and (not (list? x)) x)
961 (and (symbol? (car x)) #t)
962 (and (boolean? (car x)) #t)
965 (usage-desc (delq! #t usage-sans-specials))
966 (kw-desc (map car usage-desc))
967 (kw-opts (apply append (map (lambda (x) (and (not (string? (car x))) x)) kw-desc)))
968 (kw-args (apply append (map (lambda (x) (and (string? (car x)) (cdr x))) kw-desc)))
969 (transmogrified-cases (map (lambda (case)
970 (cons (let ((opts (car case)))
971 (if (or (boolean? opts) (eq? 'else opts))
974 ((symbol? (car opts)) opts)
975 ((boolean? (car opts)) opts)
976 ((string? (caar opts)) (cdar opts))
980 `(let ((%display-usage (lambda () (display-usage-report ',usage-desc))))
982 (let %next-arg ((%argv %argv))
986 (lambda (%opt %arg %new-argv)
988 ,@ transmogrified-cases))))))))
993 ;;; {Low Level Modules}
995 ;;; These are the low level data structures for modules.
997 ;;; Every module object is of the type 'module-type', which is a record
998 ;;; consisting of the following members:
1000 ;;; - eval-closure: the function that defines for its module the strategy that
1001 ;;; shall be followed when looking up symbols in the module.
1003 ;;; An eval-closure is a function taking two arguments: the symbol to be
1004 ;;; looked up and a boolean value telling whether a binding for the symbol
1005 ;;; should be created if it does not exist yet. If the symbol lookup
1006 ;;; succeeded (either because an existing binding was found or because a new
1007 ;;; binding was created), a variable object representing the binding is
1008 ;;; returned. Otherwise, the value #f is returned. Note that the eval
1009 ;;; closure does not take the module to be searched as an argument: During
1010 ;;; construction of the eval-closure, the eval-closure has to store the
1011 ;;; module it belongs to in its environment. This means, that any
1012 ;;; eval-closure can belong to only one module.
1014 ;;; The eval-closure of a module can be defined arbitrarily. However, three
1015 ;;; special cases of eval-closures are to be distinguished: During startup
1016 ;;; the module system is not yet activated. In this phase, no modules are
1017 ;;; defined and all bindings are automatically stored by the system in the
1018 ;;; pre-modules-obarray. Since no eval-closures exist at this time, the
1019 ;;; functions which require an eval-closure as their argument need to be
1020 ;;; passed the value #f.
1022 ;;; The other two special cases of eval-closures are the
1023 ;;; standard-eval-closure and the standard-interface-eval-closure. Both
1024 ;;; behave equally for the case that no new binding is to be created. The
1025 ;;; difference between the two comes in, when the boolean argument to the
1026 ;;; eval-closure indicates that a new binding shall be created if it is not
1029 ;;; Given that no new binding shall be created, both standard eval-closures
1030 ;;; define the following standard strategy of searching bindings in the
1031 ;;; module: First, the module's obarray is searched for the symbol. Second,
1032 ;;; if no binding for the symbol was found in the module's obarray, the
1033 ;;; module's binder procedure is exececuted. If this procedure did not
1034 ;;; return a binding for the symbol, the modules referenced in the module's
1035 ;;; uses list are recursively searched for a binding of the symbol. If the
1036 ;;; binding can not be found in these modules also, the symbol lookup has
1039 ;;; If a new binding shall be created, the standard-interface-eval-closure
1040 ;;; immediately returns indicating failure. That is, it does not even try
1041 ;;; to look up the symbol. In contrast, the standard-eval-closure would
1042 ;;; first search the obarray, and if no binding was found there, would
1043 ;;; create a new binding in the obarray, therefore not calling the binder
1044 ;;; procedure or searching the modules in the uses list.
1046 ;;; The explanation of the following members obarray, binder and uses
1047 ;;; assumes that the symbol lookup follows the strategy that is defined in
1048 ;;; the standard-eval-closure and the standard-interface-eval-closure.
1050 ;;; - obarray: a hash table that maps symbols to variable objects. In this
1051 ;;; hash table, the definitions are found that are local to the module (that
1052 ;;; is, not imported from other modules). When looking up bindings in the
1053 ;;; module, this hash table is searched first.
1055 ;;; - binder: either #f or a function taking a module and a symbol argument.
1056 ;;; If it is a function it is called after the obarray has been
1057 ;;; unsuccessfully searched for a binding. It then can provide bindings
1058 ;;; that would otherwise not be found locally in the module.
1060 ;;; - uses: a list of modules from which non-local bindings can be inherited.
1061 ;;; These modules are the third place queried for bindings after the obarray
1062 ;;; has been unsuccessfully searched and the binder function did not deliver
1063 ;;; a result either.
1065 ;;; - transformer: either #f or a function taking a scheme expression as
1066 ;;; delivered by read. If it is a function, it will be called to perform
1067 ;;; syntax transformations (e. g. makro expansion) on the given scheme
1068 ;;; expression. The output of the transformer function will then be passed
1069 ;;; to Guile's internal memoizer. This means that the output must be valid
1070 ;;; scheme code. The only exception is, that the output may make use of the
1071 ;;; syntax extensions provided to identify the modules that a binding
1074 ;;; - name: the name of the module. This is used for all kinds of printing
1075 ;;; outputs. In certain places the module name also serves as a way of
1076 ;;; identification. When adding a module to the uses list of another
1077 ;;; module, it is made sure that the new uses list will not contain two
1078 ;;; modules of the same name.
1080 ;;; - kind: classification of the kind of module. The value is (currently?)
1081 ;;; only used for printing. It has no influence on how a module is treated.
1082 ;;; Currently the following values are used when setting the module kind:
1083 ;;; 'module, 'directory, 'interface, 'custom-interface. If no explicit kind
1084 ;;; is set, it defaults to 'module.
1086 ;;; - duplicates-handlers: a list of procedures that get called to make a
1087 ;;; choice between two duplicate bindings when name clashes occur. See the
1088 ;;; `duplicate-handlers' global variable below.
1090 ;;; - observers: a list of procedures that get called when the module is
1093 ;;; - weak-observers: a weak-key hash table of procedures that get called
1094 ;;; when the module is modified. See `module-observe-weak' for details.
1096 ;;; In addition, the module may (must?) contain a binding for
1097 ;;; `%module-public-interface'. This variable should be bound to a module
1098 ;;; representing the exported interface of a module. See the
1099 ;;; `module-public-interface' and `module-export!' procedures.
1101 ;;; !!! warning: The interface to lazy binder procedures is going
1102 ;;; to be changed in an incompatible way to permit all the basic
1103 ;;; module ops to be virtualized.
1105 ;;; (make-module size use-list lazy-binding-proc) => module
1106 ;;; module-{obarray,uses,binder}[|-set!]
1107 ;;; (module? obj) => [#t|#f]
1108 ;;; (module-locally-bound? module symbol) => [#t|#f]
1109 ;;; (module-bound? module symbol) => [#t|#f]
1110 ;;; (module-symbol-locally-interned? module symbol) => [#t|#f]
1111 ;;; (module-symbol-interned? module symbol) => [#t|#f]
1112 ;;; (module-local-variable module symbol) => [#<variable ...> | #f]
1113 ;;; (module-variable module symbol) => [#<variable ...> | #f]
1114 ;;; (module-symbol-binding module symbol opt-value)
1115 ;;; => [ <obj> | opt-value | an error occurs ]
1116 ;;; (module-make-local-var! module symbol) => #<variable...>
1117 ;;; (module-add! module symbol var) => unspecified
1118 ;;; (module-remove! module symbol) => unspecified
1119 ;;; (module-for-each proc module) => unspecified
1120 ;;; (make-scm-module) => module ; a lazy copy of the symhash module
1121 ;;; (set-current-module module) => unspecified
1122 ;;; (current-module) => #<module...>
1128 ;;; {Printing Modules}
1131 ;; This is how modules are printed. You can re-define it.
1132 ;; (Redefining is actually more complicated than simply redefining
1133 ;; %print-module because that would only change the binding and not
1134 ;; the value stored in the vtable that determines how record are
1137 (define (%print-module mod port) ; unused args: depth length style table)
1139 (display (or (module-kind mod) "module") port)
1140 (let ((name (module-name mod)))
1144 (display name port))))
1146 (display (number->string (object-address mod) 16) port)
1151 ;; A module is characterized by an obarray in which local symbols
1152 ;; are interned, a list of modules, "uses", from which non-local
1153 ;; bindings can be inherited, and an optional lazy-binder which
1154 ;; is a (CLOSURE module symbol) which, as a last resort, can provide
1155 ;; bindings that would otherwise not be found locally in the module.
1157 ;; NOTE: If you change anything here, you also need to change
1158 ;; libguile/modules.h.
1161 (make-record-type 'module
1162 '(obarray uses binder eval-closure transformer name kind
1163 duplicates-handlers import-obarray
1164 observers weak-observers)
1167 ;; make-module &opt size uses binder
1169 ;; Create a new module, perhaps with a particular size of obarray,
1170 ;; initial uses list, or binding procedure.
1175 (define (parse-arg index default)
1176 (if (> (length args) index)
1177 (list-ref args index)
1180 (define %default-import-size
1181 ;; Typical number of imported bindings actually used by a module.
1184 (if (> (length args) 3)
1185 (error "Too many args to make-module." args))
1187 (let ((size (parse-arg 0 31))
1188 (uses (parse-arg 1 '()))
1189 (binder (parse-arg 2 #f)))
1191 (if (not (integer? size))
1192 (error "Illegal size to make-module." size))
1193 (if (not (and (list? uses)
1194 (and-map module? uses)))
1195 (error "Incorrect use list." uses))
1196 (if (and binder (not (procedure? binder)))
1198 "Lazy-binder expected to be a procedure or #f." binder))
1200 (let ((module (module-constructor (make-hash-table size)
1201 uses binder #f %pre-modules-transformer
1203 (make-hash-table %default-import-size)
1205 (make-weak-key-hash-table 31))))
1207 ;; We can't pass this as an argument to module-constructor,
1208 ;; because we need it to close over a pointer to the module
1210 (set-module-eval-closure! module (standard-eval-closure module))
1214 (define module-constructor (record-constructor module-type))
1215 (define module-obarray (record-accessor module-type 'obarray))
1216 (define set-module-obarray! (record-modifier module-type 'obarray))
1217 (define module-uses (record-accessor module-type 'uses))
1218 (define set-module-uses! (record-modifier module-type 'uses))
1219 (define module-binder (record-accessor module-type 'binder))
1220 (define set-module-binder! (record-modifier module-type 'binder))
1222 ;; NOTE: This binding is used in libguile/modules.c.
1223 (define module-eval-closure (record-accessor module-type 'eval-closure))
1225 (define module-transformer (record-accessor module-type 'transformer))
1226 (define set-module-transformer! (record-modifier module-type 'transformer))
1227 ;; (define module-name (record-accessor module-type 'name)) wait until mods are booted
1228 (define set-module-name! (record-modifier module-type 'name))
1229 (define module-kind (record-accessor module-type 'kind))
1230 (define set-module-kind! (record-modifier module-type 'kind))
1231 (define module-duplicates-handlers
1232 (record-accessor module-type 'duplicates-handlers))
1233 (define set-module-duplicates-handlers!
1234 (record-modifier module-type 'duplicates-handlers))
1235 (define module-observers (record-accessor module-type 'observers))
1236 (define set-module-observers! (record-modifier module-type 'observers))
1237 (define module-weak-observers (record-accessor module-type 'weak-observers))
1238 (define module? (record-predicate module-type))
1240 (define module-import-obarray (record-accessor module-type 'import-obarray))
1242 (define set-module-eval-closure!
1243 (let ((setter (record-modifier module-type 'eval-closure)))
1244 (lambda (module closure)
1245 (setter module closure)
1246 ;; Make it possible to lookup the module from the environment.
1247 ;; This implementation is correct since an eval closure can belong
1248 ;; to maximally one module.
1249 (set-procedure-property! closure 'module module))))
1253 ;;; {Observer protocol}
1256 (define (module-observe module proc)
1257 (set-module-observers! module (cons proc (module-observers module)))
1260 (define (module-observe-weak module observer-id . proc)
1261 ;; Register PROC as an observer of MODULE under name OBSERVER-ID (which can
1262 ;; be any Scheme object). PROC is invoked and passed MODULE any time
1263 ;; MODULE is modified. PROC gets unregistered when OBSERVER-ID gets GC'd
1264 ;; (thus, it is never unregistered if OBSERVER-ID is an immediate value,
1267 ;; The two-argument version is kept for backward compatibility: when called
1268 ;; with two arguments, the observer gets unregistered when closure PROC
1269 ;; gets GC'd (making it impossible to use an anonymous lambda for PROC).
1271 (let ((proc (if (null? proc) observer-id (car proc))))
1272 (hashq-set! (module-weak-observers module) observer-id proc)))
1274 (define (module-unobserve token)
1275 (let ((module (car token))
1278 (hash-remove! (module-weak-observers module) id)
1279 (set-module-observers! module (delq1! id (module-observers module)))))
1282 (define module-defer-observers #f)
1283 (define module-defer-observers-mutex (make-mutex 'recursive))
1284 (define module-defer-observers-table (make-hash-table))
1286 (define (module-modified m)
1287 (if module-defer-observers
1288 (hash-set! module-defer-observers-table m #t)
1289 (module-call-observers m)))
1291 ;;; This function can be used to delay calls to observers so that they
1292 ;;; can be called once only in the face of massive updating of modules.
1294 (define (call-with-deferred-observers thunk)
1297 (lock-mutex module-defer-observers-mutex)
1298 (set! module-defer-observers #t))
1301 (set! module-defer-observers #f)
1302 (hash-for-each (lambda (m dummy)
1303 (module-call-observers m))
1304 module-defer-observers-table)
1305 (hash-clear! module-defer-observers-table)
1306 (unlock-mutex module-defer-observers-mutex))))
1308 (define (module-call-observers m)
1309 (for-each (lambda (proc) (proc m)) (module-observers m))
1311 ;; We assume that weak observers don't (un)register themselves as they are
1312 ;; called since this would preclude proper iteration over the hash table
1314 (hash-for-each (lambda (id proc) (proc m)) (module-weak-observers m)))
1318 ;;; {Module Searching in General}
1320 ;;; We sometimes want to look for properties of a symbol
1321 ;;; just within the obarray of one module. If the property
1322 ;;; holds, then it is said to hold ``locally'' as in, ``The symbol
1323 ;;; DISPLAY is locally rebound in the module `safe-guile'.''
1326 ;;; Other times, we want to test for a symbol property in the obarray
1327 ;;; of M and, if it is not found there, try each of the modules in the
1328 ;;; uses list of M. This is the normal way of testing for some
1329 ;;; property, so we state these properties without qualification as
1330 ;;; in: ``The symbol 'fnord is interned in module M because it is
1331 ;;; interned locally in module M2 which is a member of the uses list
1335 ;; module-search fn m
1337 ;; return the first non-#f result of FN applied to M and then to
1338 ;; the modules in the uses of m, and so on recursively. If all applications
1339 ;; return #f, then so does this function.
1341 (define (module-search fn m v)
1344 (or (module-search fn (car pos) v)
1347 (loop (module-uses m))))
1350 ;;; {Is a symbol bound in a module?}
1352 ;;; Symbol S in Module M is bound if S is interned in M and if the binding
1353 ;;; of S in M has been set to some well-defined value.
1356 ;; module-locally-bound? module symbol
1358 ;; Is a symbol bound (interned and defined) locally in a given module?
1360 (define (module-locally-bound? m v)
1361 (let ((var (module-local-variable m v)))
1363 (variable-bound? var))))
1365 ;; module-bound? module symbol
1367 ;; Is a symbol bound (interned and defined) anywhere in a given module
1370 (define (module-bound? m v)
1371 (module-search module-locally-bound? m v))
1373 ;;; {Is a symbol interned in a module?}
1375 ;;; Symbol S in Module M is interned if S occurs in
1376 ;;; of S in M has been set to some well-defined value.
1378 ;;; It is possible to intern a symbol in a module without providing
1379 ;;; an initial binding for the corresponding variable. This is done
1381 ;;; (module-add! module symbol (make-undefined-variable))
1383 ;;; In that case, the symbol is interned in the module, but not
1384 ;;; bound there. The unbound symbol shadows any binding for that
1385 ;;; symbol that might otherwise be inherited from a member of the uses list.
1388 (define (module-obarray-get-handle ob key)
1389 ((if (symbol? key) hashq-get-handle hash-get-handle) ob key))
1391 (define (module-obarray-ref ob key)
1392 ((if (symbol? key) hashq-ref hash-ref) ob key))
1394 (define (module-obarray-set! ob key val)
1395 ((if (symbol? key) hashq-set! hash-set!) ob key val))
1397 (define (module-obarray-remove! ob key)
1398 ((if (symbol? key) hashq-remove! hash-remove!) ob key))
1400 ;; module-symbol-locally-interned? module symbol
1402 ;; is a symbol interned (not neccessarily defined) locally in a given module
1403 ;; or its uses? Interned symbols shadow inherited bindings even if
1404 ;; they are not themselves bound to a defined value.
1406 (define (module-symbol-locally-interned? m v)
1407 (not (not (module-obarray-get-handle (module-obarray m) v))))
1409 ;; module-symbol-interned? module symbol
1411 ;; is a symbol interned (not neccessarily defined) anywhere in a given module
1412 ;; or its uses? Interned symbols shadow inherited bindings even if
1413 ;; they are not themselves bound to a defined value.
1415 (define (module-symbol-interned? m v)
1416 (module-search module-symbol-locally-interned? m v))
1419 ;;; {Mapping modules x symbols --> variables}
1422 ;; module-local-variable module symbol
1423 ;; return the local variable associated with a MODULE and SYMBOL.
1425 ;;; This function is very important. It is the only function that can
1426 ;;; return a variable from a module other than the mutators that store
1427 ;;; new variables in modules. Therefore, this function is the location
1428 ;;; of the "lazy binder" hack.
1430 ;;; If symbol is defined in MODULE, and if the definition binds symbol
1431 ;;; to a variable, return that variable object.
1433 ;;; If the symbols is not found at first, but the module has a lazy binder,
1434 ;;; then try the binder.
1436 ;;; If the symbol is not found at all, return #f.
1438 ;;; (This is now written in C, see `modules.c'.)
1441 ;;; {Mapping modules x symbols --> bindings}
1443 ;;; These are similar to the mapping to variables, except that the
1444 ;;; variable is dereferenced.
1447 ;; module-symbol-binding module symbol opt-value
1449 ;; return the binding of a variable specified by name within
1450 ;; a given module, signalling an error if the variable is unbound.
1451 ;; If the OPT-VALUE is passed, then instead of signalling an error,
1452 ;; return OPT-VALUE.
1454 (define (module-symbol-local-binding m v . opt-val)
1455 (let ((var (module-local-variable m v)))
1456 (if (and var (variable-bound? var))
1458 (if (not (null? opt-val))
1460 (error "Locally unbound variable." v)))))
1462 ;; module-symbol-binding module symbol opt-value
1464 ;; return the binding of a variable specified by name within
1465 ;; a given module, signalling an error if the variable is unbound.
1466 ;; If the OPT-VALUE is passed, then instead of signalling an error,
1467 ;; return OPT-VALUE.
1469 (define (module-symbol-binding m v . opt-val)
1470 (let ((var (module-variable m v)))
1471 (if (and var (variable-bound? var))
1473 (if (not (null? opt-val))
1475 (error "Unbound variable." v)))))
1480 ;;; {Adding Variables to Modules}
1483 ;; module-make-local-var! module symbol
1485 ;; ensure a variable for V in the local namespace of M.
1486 ;; If no variable was already there, then create a new and uninitialzied
1489 ;; This function is used in modules.c.
1491 (define (module-make-local-var! m v)
1492 (or (let ((b (module-obarray-ref (module-obarray m) v)))
1495 ;; Mark as modified since this function is called when
1496 ;; the standard eval closure defines a binding
1500 ;; Create a new local variable.
1501 (let ((local-var (make-undefined-variable)))
1502 (module-add! m v local-var)
1505 ;; module-ensure-local-variable! module symbol
1507 ;; Ensure that there is a local variable in MODULE for SYMBOL. If
1508 ;; there is no binding for SYMBOL, create a new uninitialized
1509 ;; variable. Return the local variable.
1511 (define (module-ensure-local-variable! module symbol)
1512 (or (module-local-variable module symbol)
1513 (let ((var (make-undefined-variable)))
1514 (module-add! module symbol var)
1517 ;; module-add! module symbol var
1519 ;; ensure a particular variable for V in the local namespace of M.
1521 (define (module-add! m v var)
1522 (if (not (variable? var))
1523 (error "Bad variable to module-add!" var))
1524 (module-obarray-set! (module-obarray m) v var)
1525 (module-modified m))
1529 ;; make sure that a symbol is undefined in the local namespace of M.
1531 (define (module-remove! m v)
1532 (module-obarray-remove! (module-obarray m) v)
1533 (module-modified m))
1535 (define (module-clear! m)
1536 (hash-clear! (module-obarray m))
1537 (module-modified m))
1539 ;; MODULE-FOR-EACH -- exported
1541 ;; Call PROC on each symbol in MODULE, with arguments of (SYMBOL VARIABLE).
1543 (define (module-for-each proc module)
1544 (hash-for-each proc (module-obarray module)))
1546 (define (module-map proc module)
1547 (hash-map->list proc (module-obarray module)))
1551 ;;; {Low Level Bootstrapping}
1556 ;; A root module uses the pre-modules-obarray as its obarray. This
1557 ;; special obarray accumulates all bindings that have been established
1558 ;; before the module system is fully booted.
1560 ;; (The obarray continues to be used by code that has been closed over
1561 ;; before the module system has been booted.)
1563 (define (make-root-module)
1564 (let ((m (make-module 0)))
1565 (set-module-obarray! m (%get-pre-modules-obarray))
1570 ;; The root interface is a module that uses the same obarray as the
1571 ;; root module. It does not allow new definitions, tho.
1573 (define (make-scm-module)
1574 (let ((m (make-module 0)))
1575 (set-module-obarray! m (%get-pre-modules-obarray))
1576 (set-module-eval-closure! m (standard-interface-eval-closure m))
1582 ;;; {Module-based Loading}
1585 (define (save-module-excursion thunk)
1586 (let ((inner-module (current-module))
1588 (dynamic-wind (lambda ()
1589 (set! outer-module (current-module))
1590 (set-current-module inner-module)
1591 (set! inner-module #f))
1594 (set! inner-module (current-module))
1595 (set-current-module outer-module)
1596 (set! outer-module #f)))))
1598 (define basic-load load)
1600 (define (load-module filename . reader)
1601 (save-module-excursion
1603 (let ((oldname (and (current-load-port)
1604 (port-filename (current-load-port)))))
1607 (> (string-length filename) 0)
1608 (not (char=? (string-ref filename 0) #\/))
1609 (not (string=? (dirname oldname) ".")))
1610 (string-append (dirname oldname) "/" filename)
1617 ;;; {MODULE-REF -- exported}
1620 ;; Returns the value of a variable called NAME in MODULE or any of its
1621 ;; used modules. If there is no such variable, then if the optional third
1622 ;; argument DEFAULT is present, it is returned; otherwise an error is signaled.
1624 (define (module-ref module name . rest)
1625 (let ((variable (module-variable module name)))
1626 (if (and variable (variable-bound? variable))
1627 (variable-ref variable)
1629 (error "No variable named" name 'in module)
1630 (car rest) ; default value
1633 ;; MODULE-SET! -- exported
1635 ;; Sets the variable called NAME in MODULE (or in a module that MODULE uses)
1636 ;; to VALUE; if there is no such variable, an error is signaled.
1638 (define (module-set! module name value)
1639 (let ((variable (module-variable module name)))
1641 (variable-set! variable value)
1642 (error "No variable named" name 'in module))))
1644 ;; MODULE-DEFINE! -- exported
1646 ;; Sets the variable called NAME in MODULE to VALUE; if there is no such
1647 ;; variable, it is added first.
1649 (define (module-define! module name value)
1650 (let ((variable (module-local-variable module name)))
1653 (variable-set! variable value)
1654 (module-modified module))
1655 (let ((variable (make-variable value)))
1656 (module-add! module name variable)))))
1658 ;; MODULE-DEFINED? -- exported
1660 ;; Return #t iff NAME is defined in MODULE (or in a module that MODULE
1663 (define (module-defined? module name)
1664 (let ((variable (module-variable module name)))
1665 (and variable (variable-bound? variable))))
1667 ;; MODULE-USE! module interface
1669 ;; Add INTERFACE to the list of interfaces used by MODULE.
1671 (define (module-use! module interface)
1672 (if (not (or (eq? module interface)
1673 (memq interface (module-uses module))))
1675 ;; Newly used modules must be appended rather than consed, so that
1676 ;; `module-variable' traverses the use list starting from the first
1678 (set-module-uses! module
1679 (append (filter (lambda (m)
1681 (equal? (module-name m)
1682 (module-name interface))))
1683 (module-uses module))
1686 (module-modified module))))
1688 ;; MODULE-USE-INTERFACES! module interfaces
1690 ;; Same as MODULE-USE! but add multiple interfaces and check for duplicates
1692 (define (module-use-interfaces! module interfaces)
1693 (set-module-uses! module
1694 (append (module-uses module) interfaces))
1695 (module-modified module))
1699 ;;; {Recursive Namespaces}
1701 ;;; A hierarchical namespace emerges if we consider some module to be
1702 ;;; root, and variables bound to modules as nested namespaces.
1704 ;;; The routines in this file manage variable names in hierarchical namespace.
1705 ;;; Each variable name is a list of elements, looked up in successively nested
1708 ;;; (nested-ref some-root-module '(foo bar baz))
1709 ;;; => <value of a variable named baz in the module bound to bar in
1710 ;;; the module bound to foo in some-root-module>
1715 ;;; ;; a-root is a module
1716 ;;; ;; name is a list of symbols
1718 ;;; nested-ref a-root name
1719 ;;; nested-set! a-root name val
1720 ;;; nested-define! a-root name val
1721 ;;; nested-remove! a-root name
1724 ;;; (current-module) is a natural choice for a-root so for convenience there are
1727 ;;; local-ref name == nested-ref (current-module) name
1728 ;;; local-set! name val == nested-set! (current-module) name val
1729 ;;; local-define! name val == nested-define! (current-module) name val
1730 ;;; local-remove! name == nested-remove! (current-module) name
1734 (define (nested-ref root names)
1735 (let loop ((cur root)
1739 ((not (module? cur)) #f)
1740 (else (loop (module-ref cur (car elts) #f) (cdr elts))))))
1742 (define (nested-set! root names val)
1743 (let loop ((cur root)
1745 (if (null? (cdr elts))
1746 (module-set! cur (car elts) val)
1747 (loop (module-ref cur (car elts)) (cdr elts)))))
1749 (define (nested-define! root names val)
1750 (let loop ((cur root)
1752 (if (null? (cdr elts))
1753 (module-define! cur (car elts) val)
1754 (loop (module-ref cur (car elts)) (cdr elts)))))
1756 (define (nested-remove! root names)
1757 (let loop ((cur root)
1759 (if (null? (cdr elts))
1760 (module-remove! cur (car elts))
1761 (loop (module-ref cur (car elts)) (cdr elts)))))
1763 (define (local-ref names) (nested-ref (current-module) names))
1764 (define (local-set! names val) (nested-set! (current-module) names val))
1765 (define (local-define names val) (nested-define! (current-module) names val))
1766 (define (local-remove names) (nested-remove! (current-module) names))
1771 ;;; {The (%app) module}
1773 ;;; The root of conventionally named objects not directly in the top level.
1776 ;;; (%app modules guile)
1778 ;;; The directory of all modules and the standard root module.
1781 ;; module-public-interface is defined in C.
1782 (define (set-module-public-interface! m i)
1783 (module-define! m '%module-public-interface i))
1784 (define (set-system-module! m s)
1785 (set-procedure-property! (module-eval-closure m) 'system-module s))
1786 (define the-root-module (make-root-module))
1787 (define the-scm-module (make-scm-module))
1788 (set-module-public-interface! the-root-module the-scm-module)
1789 (set-module-name! the-root-module '(guile))
1790 (set-module-name! the-scm-module '(guile))
1791 (set-module-kind! the-scm-module 'interface)
1792 (set-system-module! the-root-module #t)
1793 (set-system-module! the-scm-module #t)
1795 ;; NOTE: This binding is used in libguile/modules.c.
1797 (define (make-modules-in module name)
1801 (let* ((var (module-local-variable module (car name)))
1802 (val (and var (variable-bound? var) (variable-ref var))))
1805 (let ((m (make-module 31)))
1806 (set-module-kind! m 'directory)
1807 (set-module-name! m (append (or (module-name module) '())
1809 (module-define! module (car name) m)
1813 (define (beautify-user-module! module)
1814 (let ((interface (module-public-interface module)))
1815 (if (or (not interface)
1816 (eq? interface module))
1817 (let ((interface (make-module 31)))
1818 (set-module-name! interface (module-name module))
1819 (set-module-kind! interface 'interface)
1820 (set-module-public-interface! module interface))))
1821 (if (and (not (memq the-scm-module (module-uses module)))
1822 (not (eq? module the-root-module)))
1823 ;; Import the default set of bindings (from the SCM module) in MODULE.
1824 (module-use! module the-scm-module)))
1826 ;; NOTE: This binding is used in libguile/modules.c.
1828 (define resolve-module
1829 (let ((the-root-module the-root-module))
1830 (lambda (name . maybe-autoload)
1831 (if (equal? name '(guile))
1833 (let ((full-name (append '(%app modules) name)))
1834 (let ((already (nested-ref the-root-module full-name))
1835 (autoload (or (null? maybe-autoload) (car maybe-autoload))))
1837 ((and already (module? already)
1838 (or (not autoload) (module-public-interface already)))
1839 ;; A hit, a palpable hit.
1842 ;; Try to autoload the module, and recurse.
1844 (try-load-module name)
1845 (resolve-module name #f))
1847 ;; A module is not bound (but maybe something else is),
1848 ;; we're not autoloading -- here's the weird semantics,
1849 ;; we create an empty module.
1850 (make-modules-in the-root-module full-name)))))))))
1852 ;; Cheat. These bindings are needed by modules.c, but we don't want
1853 ;; to move their real definition here because that would be unnatural.
1855 (define try-module-autoload #f)
1856 (define process-define-module #f)
1857 (define process-use-modules #f)
1858 (define module-export! #f)
1859 (define default-duplicate-binding-procedures #f)
1861 (define %app (make-module 31))
1862 (define app %app) ;; for backwards compatability
1864 (local-define '(%app modules) (make-module 31))
1865 (local-define '(%app modules guile) the-root-module)
1867 ;; This boots the module system. All bindings needed by modules.c
1868 ;; must have been defined by now.
1870 (set-current-module the-root-module)
1871 ;; definition deferred for syncase's benefit
1872 (define module-name (record-accessor module-type 'name))
1874 ;; (define-special-value '(%app modules new-ws) (lambda () (make-scm-module)))
1876 (define (try-load-module name)
1877 (or (begin-deprecated (try-module-linked name))
1878 (try-module-autoload name)
1879 (begin-deprecated (try-module-dynamic-link name))))
1881 (define (purify-module! module)
1882 "Removes bindings in MODULE which are inherited from the (guile) module."
1883 (let ((use-list (module-uses module)))
1884 (if (and (pair? use-list)
1885 (eq? (car (last-pair use-list)) the-scm-module))
1886 (set-module-uses! module (reverse (cdr (reverse use-list)))))))
1888 ;; Return a module that is an interface to the module designated by
1891 ;; `resolve-interface' takes four keyword arguments:
1893 ;; #:select SELECTION
1895 ;; SELECTION is a list of binding-specs to be imported; A binding-spec
1896 ;; is either a symbol or a pair of symbols (ORIG . SEEN), where ORIG
1897 ;; is the name in the used module and SEEN is the name in the using
1898 ;; module. Note that SEEN is also passed through RENAMER, below. The
1899 ;; default is to select all bindings. If you specify no selection but
1900 ;; a renamer, only the bindings that already exist in the used module
1901 ;; are made available in the interface. Bindings that are added later
1902 ;; are not picked up.
1906 ;; BINDINGS is a list of bindings which should not be imported.
1910 ;; PREFIX is a symbol that will be appended to each exported name.
1911 ;; The default is to not perform any renaming.
1913 ;; #:renamer RENAMER
1915 ;; RENAMER is a procedure that takes a symbol and returns its new
1916 ;; name. The default is not perform any renaming.
1918 ;; Signal "no code for module" error if module name is not resolvable
1919 ;; or its public interface is not available. Signal "no binding"
1920 ;; error if selected binding does not exist in the used module.
1922 (define (resolve-interface name . args)
1924 (define (get-keyword-arg args kw def)
1925 (cond ((memq kw args)
1927 (if (null? (cdr kw-arg))
1928 (error "keyword without value: " kw))
1933 (let* ((select (get-keyword-arg args #:select #f))
1934 (hide (get-keyword-arg args #:hide '()))
1935 (renamer (or (get-keyword-arg args #:renamer #f)
1936 (let ((prefix (get-keyword-arg args #:prefix #f)))
1937 (and prefix (symbol-prefix-proc prefix)))
1939 (module (resolve-module name))
1940 (public-i (and module (module-public-interface module))))
1941 (and (or (not module) (not public-i))
1942 (error "no code for module" name))
1943 (if (and (not select) (null? hide) (eq? renamer identity))
1945 (let ((selection (or select (module-map (lambda (sym var) sym)
1947 (custom-i (make-module 31)))
1948 (set-module-kind! custom-i 'custom-interface)
1949 (set-module-name! custom-i name)
1950 ;; XXX - should use a lazy binder so that changes to the
1951 ;; used module are picked up automatically.
1952 (for-each (lambda (bspec)
1953 (let* ((direct? (symbol? bspec))
1954 (orig (if direct? bspec (car bspec)))
1955 (seen (if direct? bspec (cdr bspec)))
1956 (var (or (module-local-variable public-i orig)
1957 (module-local-variable module orig)
1959 ;; fixme: format manually for now
1961 #f "no binding `~A' in module ~A"
1963 (if (memq orig hide)
1964 (set! hide (delq! orig hide))
1965 (module-add! custom-i
1969 ;; Check that we are not hiding bindings which don't exist
1970 (for-each (lambda (binding)
1971 (if (not (module-local-variable public-i binding))
1974 #f "no binding `~A' to hide in module ~A"
1979 (define (symbol-prefix-proc prefix)
1981 (symbol-append prefix symbol)))
1983 ;; This function is called from "modules.c". If you change it, be
1984 ;; sure to update "modules.c" as well.
1986 (define (process-define-module args)
1987 (let* ((module-id (car args))
1988 (module (resolve-module module-id #f))
1990 (unrecognized (lambda (arg)
1991 (error "unrecognized define-module argument" arg))))
1992 (beautify-user-module! module)
1993 (let loop ((kws kws)
1994 (reversed-interfaces '())
2001 (call-with-deferred-observers
2003 (module-use-interfaces! module (reverse reversed-interfaces))
2004 (module-export! module exports)
2005 (module-replace! module replacements)
2006 (module-re-export! module re-exports)
2007 (if (not (null? autoloads))
2008 (apply module-autoload! module autoloads))))
2010 ((#:use-module #:use-syntax)
2011 (or (pair? (cdr kws))
2014 ((equal? (caadr kws) '(ice-9 syncase))
2015 (issue-deprecation-warning
2016 "(ice-9 syncase) is deprecated. Support for syntax-case is now in Guile core.")
2024 (let* ((interface-args (cadr kws))
2025 (interface (apply resolve-interface interface-args)))
2026 (and (eq? (car kws) #:use-syntax)
2027 (or (symbol? (caar interface-args))
2028 (error "invalid module name for use-syntax"
2029 (car interface-args)))
2030 (set-module-transformer!
2032 (module-ref interface
2033 (car (last-pair (car interface-args)))
2036 (cons interface reversed-interfaces)
2042 (or (and (pair? (cdr kws)) (pair? (cddr kws)))
2049 (let ((name (cadr kws))
2050 (bindings (caddr kws)))
2051 (cons* name bindings autoloads))))
2053 (set-system-module! module #t)
2054 (loop (cdr kws) reversed-interfaces exports re-exports
2055 replacements autoloads))
2057 (purify-module! module)
2058 (loop (cdr kws) reversed-interfaces exports re-exports
2059 replacements autoloads))
2061 (if (not (pair? (cdr kws)))
2063 (set-module-duplicates-handlers!
2065 (lookup-duplicates-handlers (cadr kws)))
2066 (loop (cddr kws) reversed-interfaces exports re-exports
2067 replacements autoloads))
2068 ((#:export #:export-syntax)
2069 (or (pair? (cdr kws))
2073 (append (cadr kws) exports)
2077 ((#:re-export #:re-export-syntax)
2078 (or (pair? (cdr kws))
2083 (append (cadr kws) re-exports)
2086 ((#:replace #:replace-syntax)
2087 (or (pair? (cdr kws))
2093 (append (cadr kws) replacements)
2096 (unrecognized kws)))))
2097 (run-hook module-defined-hook module)
2100 ;; `module-defined-hook' is a hook that is run whenever a new module
2101 ;; is defined. Its members are called with one argument, the new
2103 (define module-defined-hook (make-hook 1))
2110 (define (make-autoload-interface module name bindings)
2111 (let ((b (lambda (a sym definep)
2112 (and (memq sym bindings)
2113 (let ((i (module-public-interface (resolve-module name))))
2115 (error "missing interface for module" name))
2116 (let ((autoload (memq a (module-uses module))))
2117 ;; Replace autoload-interface with actual interface if
2118 ;; that has not happened yet.
2119 (if (pair? autoload)
2120 (set-car! autoload i)))
2121 (module-local-variable i sym))))))
2122 (module-constructor (make-hash-table 0) '() b #f #f name 'autoload #f
2123 (make-hash-table 0) '() (make-weak-value-hash-table 31))))
2125 (define (module-autoload! module . args)
2126 "Have @var{module} automatically load the module named @var{name} when one
2127 of the symbols listed in @var{bindings} is looked up. @var{args} should be a
2128 list of module-name/binding-list pairs, e.g., as in @code{(module-autoload!
2129 module '(ice-9 q) '(make-q q-length))}."
2130 (let loop ((args args))
2134 (error "invalid name+binding autoload list" args))
2136 (let ((name (car args))
2137 (bindings (cadr args)))
2138 (module-use! module (make-autoload-interface module
2140 (loop (cddr args)))))))
2145 ;;; {Autoloading modules}
2148 (define autoloads-in-progress '())
2150 ;; This function is called from "modules.c". If you change it, be
2151 ;; sure to update "modules.c" as well.
2153 (define (try-module-autoload module-name)
2154 (let* ((reverse-name (reverse module-name))
2155 (name (symbol->string (car reverse-name)))
2156 (dir-hint-module-name (reverse (cdr reverse-name)))
2157 (dir-hint (apply string-append
2159 (string-append (symbol->string elt) "/"))
2160 dir-hint-module-name))))
2161 (resolve-module dir-hint-module-name #f)
2162 (and (not (autoload-done-or-in-progress? dir-hint name))
2164 (define (load-file proc file)
2165 (save-module-excursion (lambda () (proc file)))
2168 (lambda () (autoload-in-progress! dir-hint name))
2170 (let ((file (in-vicinity dir-hint name)))
2171 (let ((compiled (and load-compiled
2173 (string-append file ".go"))))
2174 (source (%search-load-path file)))
2177 (< (stat:mtime (stat compiled))
2178 (stat:mtime (stat source)))))
2180 (warn "source file" source "newer than" compiled))
2181 (with-fluid* current-reader #f
2182 (lambda () (load-file primitive-load source))))
2184 (load-file load-compiled compiled))))))
2185 (lambda () (set-autoloaded! dir-hint name didit)))
2190 ;;; {Dynamic linking of modules}
2193 (define autoloads-done '((guile . guile)))
2195 (define (autoload-done-or-in-progress? p m)
2196 (let ((n (cons p m)))
2197 (->bool (or (member n autoloads-done)
2198 (member n autoloads-in-progress)))))
2200 (define (autoload-done! p m)
2201 (let ((n (cons p m)))
2202 (set! autoloads-in-progress
2203 (delete! n autoloads-in-progress))
2204 (or (member n autoloads-done)
2205 (set! autoloads-done (cons n autoloads-done)))))
2207 (define (autoload-in-progress! p m)
2208 (let ((n (cons p m)))
2209 (set! autoloads-done
2210 (delete! n autoloads-done))
2211 (set! autoloads-in-progress (cons n autoloads-in-progress))))
2213 (define (set-autoloaded! p m done?)
2215 (autoload-done! p m)
2216 (let ((n (cons p m)))
2217 (set! autoloads-done (delete! n autoloads-done))
2218 (set! autoloads-in-progress (delete! n autoloads-in-progress)))))
2222 ;;; {Run-time options}
2225 (defmacro define-option-interface (option-group)
2226 (let* ((option-name car)
2228 (option-documentation caddr)
2230 ;; Below follow the macros defining the run-time option interfaces.
2232 (make-options (lambda (interface)
2234 (cond ((null? args) (,interface))
2236 (,interface (car args)) (,interface))
2239 (display (option-name option))
2240 (if (< (string-length
2241 (symbol->string (option-name option)))
2245 (display (option-value option))
2247 (display (option-documentation option))
2249 (,interface #t)))))))
2251 (make-enable (lambda (interface)
2253 (,interface (append flags (,interface)))
2256 (make-disable (lambda (interface)
2258 (let ((options (,interface)))
2259 (for-each (lambda (flag)
2260 (set! options (delq! flag options)))
2262 (,interface options)
2264 (let* ((interface (car option-group))
2265 (options/enable/disable (cadr option-group)))
2267 (define ,(car options/enable/disable)
2268 ,(make-options interface))
2269 (define ,(cadr options/enable/disable)
2270 ,(make-enable interface))
2271 (define ,(caddr options/enable/disable)
2272 ,(make-disable interface))
2273 (defmacro ,(caaddr option-group) (opt val)
2274 `(,',(car options/enable/disable)
2275 (append (,',(car options/enable/disable))
2276 (list ',opt ,val))))))))
2278 (define-option-interface
2279 (eval-options-interface
2280 (eval-options eval-enable eval-disable)
2283 (define-option-interface
2284 (debug-options-interface
2285 (debug-options debug-enable debug-disable)
2288 (define-option-interface
2289 (evaluator-traps-interface
2290 (traps trap-enable trap-disable)
2293 (define-option-interface
2294 (read-options-interface
2295 (read-options read-enable read-disable)
2298 (define-option-interface
2299 (print-options-interface
2300 (print-options print-enable print-disable)
2308 (define (repl read evaler print)
2309 (let loop ((source (read (current-input-port))))
2310 (print (evaler source))
2311 (loop (read (current-input-port)))))
2313 ;; A provisional repl that acts like the SCM repl:
2315 (define scm-repl-silent #f)
2316 (define (assert-repl-silence v) (set! scm-repl-silent v))
2318 (define *unspecified* (if #f #f))
2319 (define (unspecified? v) (eq? v *unspecified*))
2321 (define scm-repl-print-unspecified #f)
2322 (define (assert-repl-print-unspecified v) (set! scm-repl-print-unspecified v))
2324 (define scm-repl-verbose #f)
2325 (define (assert-repl-verbosity v) (set! scm-repl-verbose v))
2327 (define scm-repl-prompt "guile> ")
2329 (define (set-repl-prompt! v) (set! scm-repl-prompt v))
2331 (define (default-pre-unwind-handler key . args)
2332 (save-stack pre-unwind-handler-dispatch)
2333 (apply throw key args))
2335 (define (pre-unwind-handler-dispatch key . args)
2336 (apply default-pre-unwind-handler key args))
2338 (define abort-hook (make-hook))
2340 ;; these definitions are used if running a script.
2341 ;; otherwise redefined in error-catching-loop.
2342 (define (set-batch-mode?! arg) #t)
2343 (define (batch-mode?) #t)
2345 (define (error-catching-loop thunk)
2348 (define (loop first)
2353 (call-with-unblocked-asyncs
2359 ;; This line is needed because mark
2360 ;; doesn't do closures quite right.
2361 ;; Unreferenced locals should be
2364 (let loop ((v (thunk)))
2368 (lambda (key . args)
2375 (apply throw 'switch-repl args))
2378 ;; This is one of the closures that require
2379 ;; (set! first #f) above
2382 (run-hook abort-hook)
2383 (force-output (current-output-port))
2384 (display "ABORT: " (current-error-port))
2385 (write args (current-error-port))
2386 (newline (current-error-port))
2390 (not has-shown-debugger-hint?)
2391 (not (memq 'backtrace
2392 (debug-options-interface)))
2393 (stack? (fluid-ref the-last-stack)))
2395 (newline (current-error-port))
2397 "Type \"(backtrace)\" to get more information or \"(debug)\" to enter the debugger.\n"
2398 (current-error-port))
2399 (set! has-shown-debugger-hint? #t)))
2400 (force-output (current-error-port)))
2402 (primitive-exit 1)))
2403 (set! stack-saved? #f)))
2406 ;; This is the other cons-leak closure...
2408 (cond ((= (length args) 4)
2409 (apply handle-system-error key args))
2411 (apply bad-throw key args)))))))
2413 ;; Note that having just `pre-unwind-handler-dispatch'
2414 ;; here is connected with the mechanism that
2415 ;; produces a nice backtrace upon error. If, for
2416 ;; example, this is replaced with (lambda args
2417 ;; (apply pre-unwind-handler-dispatch args)), the stack
2418 ;; cutting (in save-stack) goes wrong and ends up
2419 ;; saving no stack at all, so there is no
2421 pre-unwind-handler-dispatch)))
2423 (if next (loop next) status)))
2424 (set! set-batch-mode?! (lambda (arg)
2426 (set! interactive #f)
2429 (error "sorry, not implemented")))))
2430 (set! batch-mode? (lambda () (not interactive)))
2431 (call-with-blocked-asyncs
2432 (lambda () (loop (lambda () #t))))))
2434 ;;(define the-last-stack (make-fluid)) Defined by scm_init_backtrace ()
2435 (define before-signal-stack (make-fluid))
2436 (define stack-saved? #f)
2438 (define (save-stack . narrowing)
2440 (cond ((not (memq 'debug (debug-options-interface)))
2441 (fluid-set! the-last-stack #f)
2442 (set! stack-saved? #t))
2448 (apply make-stack #t save-stack primitive-eval #t 0 narrowing))
2450 (apply make-stack #t save-stack 0 #t 0 narrowing))
2452 (apply make-stack #t save-stack tk-stack-mark #t 0 narrowing))
2454 (apply make-stack #t save-stack 0 1 narrowing))
2456 (let ((id (stack-id #t)))
2457 (and (procedure? id)
2458 (apply make-stack #t save-stack id #t 0 narrowing))))))
2459 (set! stack-saved? #t)))))
2461 (define before-error-hook (make-hook))
2462 (define after-error-hook (make-hook))
2463 (define before-backtrace-hook (make-hook))
2464 (define after-backtrace-hook (make-hook))
2466 (define has-shown-debugger-hint? #f)
2468 (define (handle-system-error key . args)
2469 (let ((cep (current-error-port)))
2470 (cond ((not (stack? (fluid-ref the-last-stack))))
2471 ((memq 'backtrace (debug-options-interface))
2472 (let ((highlights (if (or (eq? key 'wrong-type-arg)
2473 (eq? key 'out-of-range))
2476 (run-hook before-backtrace-hook)
2478 (display "Backtrace:\n")
2479 (display-backtrace (fluid-ref the-last-stack) cep
2482 (run-hook after-backtrace-hook))))
2483 (run-hook before-error-hook)
2484 (apply display-error (fluid-ref the-last-stack) cep args)
2485 (run-hook after-error-hook)
2487 (throw 'abort key)))
2489 (define (quit . args)
2490 (apply throw 'quit args))
2494 ;;(define has-shown-backtrace-hint? #f) Defined by scm_init_backtrace ()
2496 ;; Replaced by C code:
2497 ;;(define (backtrace)
2498 ;; (if (fluid-ref the-last-stack)
2501 ;; (display-backtrace (fluid-ref the-last-stack) (current-output-port))
2503 ;; (if (and (not has-shown-backtrace-hint?)
2504 ;; (not (memq 'backtrace (debug-options-interface))))
2507 ;;"Type \"(debug-enable 'backtrace)\" if you would like a backtrace
2508 ;;automatically if an error occurs in the future.\n")
2509 ;; (set! has-shown-backtrace-hint? #t))))
2510 ;; (display "No backtrace available.\n")))
2512 (define (error-catching-repl r e p)
2513 (error-catching-loop
2515 (call-with-values (lambda () (e (r)))
2516 (lambda the-values (for-each p the-values))))))
2518 (define (gc-run-time)
2519 (cdr (assq 'gc-time-taken (gc-stats))))
2521 (define before-read-hook (make-hook))
2522 (define after-read-hook (make-hook))
2523 (define before-eval-hook (make-hook 1))
2524 (define after-eval-hook (make-hook 1))
2525 (define before-print-hook (make-hook 1))
2526 (define after-print-hook (make-hook 1))
2528 ;;; The default repl-reader function. We may override this if we've
2529 ;;; the readline library.
2532 (display (if (string? prompt) prompt (prompt)))
2534 (run-hook before-read-hook)
2535 ((or (fluid-ref current-reader) read) (current-input-port))))
2537 (define (scm-style-repl)
2542 (repl-report-start-timing (lambda ()
2543 (set! start-gc-rt (gc-run-time))
2544 (set! start-rt (get-internal-run-time))))
2545 (repl-report (lambda ()
2547 (display (inexact->exact
2548 (* 1000 (/ (- (get-internal-run-time) start-rt)
2549 internal-time-units-per-second))))
2551 (display (inexact->exact
2552 (* 1000 (/ (- (gc-run-time) start-gc-rt)
2553 internal-time-units-per-second))))
2554 (display " msec in gc)\n")))
2556 (consume-trailing-whitespace
2558 (let ((ch (peek-char)))
2561 ((or (char=? ch #\space) (char=? ch #\tab))
2563 (consume-trailing-whitespace))
2564 ((char=? ch #\newline)
2568 (let ((prompt (cond ((string? scm-repl-prompt)
2570 ((thunk? scm-repl-prompt)
2572 (scm-repl-prompt "> ")
2574 (repl-reader prompt))))
2576 ;; As described in R4RS, the READ procedure updates the
2577 ;; port to point to the first character past the end of
2578 ;; the external representation of the object. This
2579 ;; means that it doesn't consume the newline typically
2580 ;; found after an expression. This means that, when
2581 ;; debugging Guile with GDB, GDB gets the newline, which
2582 ;; it often interprets as a "continue" command, making
2583 ;; breakpoints kind of useless. So, consume any
2584 ;; trailing newline here, as well as any whitespace
2586 ;; But not if EOF, for control-D.
2587 (if (not (eof-object? val))
2588 (consume-trailing-whitespace))
2589 (run-hook after-read-hook)
2590 (if (eof-object? val)
2592 (repl-report-start-timing)
2593 (if scm-repl-verbose
2596 (display ";;; EOF -- quitting")
2601 (-eval (lambda (sourc)
2602 (repl-report-start-timing)
2603 (run-hook before-eval-hook sourc)
2604 (let ((val (start-stack 'repl-stack
2605 ;; If you change this procedure
2606 ;; (primitive-eval), please also
2607 ;; modify the repl-stack case in
2608 ;; save-stack so that stack cutting
2609 ;; continues to work.
2610 (primitive-eval sourc))))
2611 (run-hook after-eval-hook sourc)
2615 (-print (let ((maybe-print (lambda (result)
2616 (if (or scm-repl-print-unspecified
2617 (not (unspecified? result)))
2622 (if (not scm-repl-silent)
2624 (run-hook before-print-hook result)
2625 (maybe-print result)
2626 (run-hook after-print-hook result)
2627 (if scm-repl-verbose
2631 (-quit (lambda (args)
2632 (if scm-repl-verbose
2634 (display ";;; QUIT executed, repl exitting")
2640 (if scm-repl-verbose
2642 (display ";;; ABORT executed.")
2645 (repl -read -eval -print))))
2647 (let ((status (error-catching-repl -read
2655 ;;; {IOTA functions: generating lists of numbers}
2659 (let loop ((count (1- n)) (result '()))
2660 (if (< count 0) result
2661 (loop (1- count) (cons count result)))))
2667 ;;; Similar to `begin' but returns a list of the results of all constituent
2668 ;;; forms instead of the result of the last form.
2669 ;;; (The definition relies on the current left-to-right
2670 ;;; order of evaluation of operands in applications.)
2673 (defmacro collect forms
2681 ;; with-fluids is a convenience wrapper for the builtin procedure
2682 ;; `with-fluids*'. The syntax is just like `let':
2684 ;; (with-fluids ((fluid val)
2688 (defmacro with-fluids (bindings . body)
2689 (let ((fluids (map car bindings))
2690 (values (map cadr bindings)))
2691 (if (and (= (length fluids) 1) (= (length values) 1))
2692 `(with-fluid* ,(car fluids) ,(car values) (lambda () ,@body))
2693 `(with-fluids* (list ,@fluids) (list ,@values)
2694 (lambda () ,@body)))))
2698 ;;; with `continue' and `break'.
2701 ;; The inner `do' loop avoids re-establishing a catch every iteration,
2702 ;; that's only necessary if continue is actually used. A new key is
2703 ;; generated every time, so break and continue apply to their originating
2704 ;; `while' even when recursing.
2706 ;; FIXME: This macro is unintentionally unhygienic with respect to let,
2707 ;; make-symbol, do, throw, catch, lambda, and not.
2709 (define-macro (while cond . body)
2710 (let ((keyvar (make-symbol "while-keyvar")))
2711 `(let ((,keyvar (make-symbol "while-key")))
2715 (let ((break (lambda () (throw ,keyvar #t)))
2716 (continue (lambda () (throw ,keyvar #f))))
2727 ;;; {Module System Macros}
2730 ;; Return a list of expressions that evaluate to the appropriate
2731 ;; arguments for resolve-interface according to SPEC.
2735 (if (memq 'prefix (read-options))
2736 (error "boot-9 must be compiled with #:kw, not :kw")))
2738 (define (compile-interface-spec spec)
2739 (define (make-keyarg sym key quote?)
2740 (cond ((or (memq sym spec)
2744 (list key (list 'quote (cadr rest)))
2745 (list key (cadr rest)))))
2748 (define (map-apply func list)
2749 (map (lambda (args) (apply func args)) list))
2752 '((:select #:select #t)
2754 (:prefix #:prefix #t)
2755 (:renamer #:renamer #f)))
2756 (if (not (pair? (car spec)))
2759 ,@(apply append (map-apply make-keyarg keys)))))
2761 (define (keyword-like-symbol->keyword sym)
2762 (symbol->keyword (string->symbol (substring (symbol->string sym) 1))))
2764 (define (compile-define-module-args args)
2765 ;; Just quote everything except #:use-module and #:use-syntax. We
2766 ;; need to know about all arguments regardless since we want to turn
2767 ;; symbols that look like keywords into real keywords, and the
2768 ;; keyword args in a define-module form are not regular
2769 ;; (i.e. no-backtrace doesn't take a value).
2770 (let loop ((compiled-args `((quote ,(car args))))
2773 (reverse! compiled-args))
2774 ;; symbol in keyword position
2775 ((symbol? (car args))
2777 (cons (keyword-like-symbol->keyword (car args)) (cdr args))))
2778 ((memq (car args) '(#:no-backtrace #:pure))
2779 (loop (cons (car args) compiled-args)
2782 (error "keyword without value:" (car args)))
2783 ((memq (car args) '(#:use-module #:use-syntax))
2784 (loop (cons* `(list ,@(compile-interface-spec (cadr args)))
2788 ((eq? (car args) #:autoload)
2789 (loop (cons* `(quote ,(caddr args))
2790 `(quote ,(cadr args))
2795 (loop (cons* `(quote ,(cadr args))
2800 (defmacro define-module args
2803 (let ((m (process-define-module
2804 (list ,@(compile-define-module-args args)))))
2805 (set-current-module m)
2808 ;; The guts of the use-modules macro. Add the interfaces of the named
2809 ;; modules to the use-list of the current module, in order.
2811 ;; This function is called by "modules.c". If you change it, be sure
2812 ;; to change scm_c_use_module as well.
2814 (define (process-use-modules module-interface-args)
2815 (let ((interfaces (map (lambda (mif-args)
2816 (or (apply resolve-interface mif-args)
2817 (error "no such module" mif-args)))
2818 module-interface-args)))
2819 (call-with-deferred-observers
2821 (module-use-interfaces! (current-module) interfaces)))))
2823 (defmacro use-modules modules
2826 (process-use-modules
2827 (list ,@(map (lambda (m)
2828 `(list ,@(compile-interface-spec m)))
2832 (defmacro use-syntax (spec)
2835 (issue-deprecation-warning
2836 "`use-syntax' is deprecated. Please contact guile-devel for more info.")
2837 (process-use-modules (list (list ,@(compile-interface-spec spec))))
2840 ;; Dirk:FIXME:: This incorrect (according to R5RS) syntax needs to be changed
2841 ;; as soon as guile supports hygienic macros.
2842 (define-syntax define-private
2847 (define-syntax define-public
2849 ((_ (name . args) . body)
2850 (define-public name (lambda args . body)))
2856 (define-syntax defmacro-public
2858 ((_ name args . body)
2860 (defmacro name args . body)
2861 (export-syntax name)))))
2863 ;; Export a local variable
2865 ;; This function is called from "modules.c". If you change it, be
2866 ;; sure to update "modules.c" as well.
2868 (define (module-export! m names)
2869 (let ((public-i (module-public-interface m)))
2870 (for-each (lambda (name)
2871 (let ((var (module-ensure-local-variable! m name)))
2872 (module-add! public-i name var)))
2875 (define (module-replace! m names)
2876 (let ((public-i (module-public-interface m)))
2877 (for-each (lambda (name)
2878 (let ((var (module-ensure-local-variable! m name)))
2879 (set-object-property! var 'replace #t)
2880 (module-add! public-i name var)))
2883 ;; Re-export a imported variable
2885 (define (module-re-export! m names)
2886 (let ((public-i (module-public-interface m)))
2887 (for-each (lambda (name)
2888 (let ((var (module-variable m name)))
2890 (error "Undefined variable:" name))
2891 ((eq? var (module-local-variable m name))
2892 (error "re-exporting local variable:" name))
2894 (module-add! public-i name var)))))
2897 (defmacro export names
2898 `(call-with-deferred-observers
2900 (module-export! (current-module) ',names))))
2902 (defmacro re-export names
2903 `(call-with-deferred-observers
2905 (module-re-export! (current-module) ',names))))
2907 (defmacro export-syntax names
2910 (defmacro re-export-syntax names
2911 `(re-export ,@names))
2913 (define load load-module)
2917 ;;; {Compiler interface}
2919 ;;; The full compiler interface can be found in (system). Here we put a
2920 ;;; few useful procedures into the global namespace.
2922 (module-autoload! the-scm-module
2923 '(system base compile)
2925 compile-time-environment))
2933 (define make-mutable-parameter
2934 (let ((make (lambda (fluid converter)
2938 (fluid-set! fluid (converter (car args))))))))
2939 (lambda (init . converter)
2940 (let ((fluid (make-fluid))
2941 (converter (if (null? converter)
2944 (fluid-set! fluid (converter init))
2945 (make fluid converter)))))
2949 ;;; {Handling of duplicate imported bindings}
2952 ;; Duplicate handlers take the following arguments:
2954 ;; module importing module
2955 ;; name conflicting name
2956 ;; int1 old interface where name occurs
2957 ;; val1 value of binding in old interface
2958 ;; int2 new interface where name occurs
2959 ;; val2 value of binding in new interface
2960 ;; var previous resolution or #f
2961 ;; val value of previous resolution
2963 ;; A duplicate handler can take three alternative actions:
2965 ;; 1. return #f => leave responsibility to next handler
2966 ;; 2. exit with an error
2967 ;; 3. return a variable resolving the conflict
2970 (define duplicate-handlers
2971 (let ((m (make-module 7)))
2973 (define (check module name int1 val1 int2 val2 var val)
2974 (scm-error 'misc-error
2976 "~A: `~A' imported from both ~A and ~A"
2977 (list (module-name module)
2983 (define (warn module name int1 val1 int2 val2 var val)
2984 (format (current-error-port)
2985 "WARNING: ~A: `~A' imported from both ~A and ~A\n"
2986 (module-name module)
2992 (define (replace module name int1 val1 int2 val2 var val)
2993 (let ((old (or (and var (object-property var 'replace) var)
2994 (module-variable int1 name)))
2995 (new (module-variable int2 name)))
2996 (if (object-property old 'replace)
2997 (and (or (eq? old new)
2998 (not (object-property new 'replace)))
3000 (and (object-property new 'replace)
3003 (define (warn-override-core module name int1 val1 int2 val2 var val)
3004 (and (eq? int1 the-scm-module)
3006 (format (current-error-port)
3007 "WARNING: ~A: imported module ~A overrides core binding `~A'\n"
3008 (module-name module)
3011 (module-local-variable int2 name))))
3013 (define (first module name int1 val1 int2 val2 var val)
3014 (or var (module-local-variable int1 name)))
3016 (define (last module name int1 val1 int2 val2 var val)
3017 (module-local-variable int2 name))
3019 (define (noop module name int1 val1 int2 val2 var val)
3022 (set-module-name! m 'duplicate-handlers)
3023 (set-module-kind! m 'interface)
3024 (module-define! m 'check check)
3025 (module-define! m 'warn warn)
3026 (module-define! m 'replace replace)
3027 (module-define! m 'warn-override-core warn-override-core)
3028 (module-define! m 'first first)
3029 (module-define! m 'last last)
3030 (module-define! m 'merge-generics noop)
3031 (module-define! m 'merge-accessors noop)
3034 (define (lookup-duplicates-handlers handler-names)
3036 (map (lambda (handler-name)
3037 (or (module-symbol-local-binding
3038 duplicate-handlers handler-name #f)
3039 (error "invalid duplicate handler name:"
3041 (if (list? handler-names)
3043 (list handler-names)))))
3045 (define default-duplicate-binding-procedures
3046 (make-mutable-parameter #f))
3048 (define default-duplicate-binding-handler
3049 (make-mutable-parameter '(replace warn-override-core warn last)
3050 (lambda (handler-names)
3051 (default-duplicate-binding-procedures
3052 (lookup-duplicates-handlers handler-names))
3057 ;;; {`cond-expand' for SRFI-0 support.}
3059 ;;; This syntactic form expands into different commands or
3060 ;;; definitions, depending on the features provided by the Scheme
3066 ;;; --> (cond-expand <cond-expand-clause>+)
3067 ;;; | (cond-expand <cond-expand-clause>* (else <command-or-definition>))
3068 ;;; <cond-expand-clause>
3069 ;;; --> (<feature-requirement> <command-or-definition>*)
3070 ;;; <feature-requirement>
3071 ;;; --> <feature-identifier>
3072 ;;; | (and <feature-requirement>*)
3073 ;;; | (or <feature-requirement>*)
3074 ;;; | (not <feature-requirement>)
3075 ;;; <feature-identifier>
3076 ;;; --> <a symbol which is the name or alias of a SRFI>
3078 ;;; Additionally, this implementation provides the
3079 ;;; <feature-identifier>s `guile' and `r5rs', so that programs can
3080 ;;; determine the implementation type and the supported standard.
3082 ;;; Currently, the following feature identifiers are supported:
3084 ;;; guile r5rs srfi-0 srfi-4 srfi-6 srfi-13 srfi-14 srfi-55 srfi-61
3086 ;;; Remember to update the features list when adding more SRFIs.
3089 (define %cond-expand-features
3090 ;; Adjust the above comment when changing this.
3093 srfi-0 ;; cond-expand itself
3094 srfi-4 ;; homogenous numeric vectors
3095 srfi-6 ;; open-input-string etc, in the guile core
3096 srfi-13 ;; string library
3097 srfi-14 ;; character sets
3098 srfi-55 ;; require-extension
3099 srfi-61 ;; general cond clause
3102 ;; This table maps module public interfaces to the list of features.
3104 (define %cond-expand-table (make-hash-table 31))
3106 ;; Add one or more features to the `cond-expand' feature list of the
3109 (define (cond-expand-provide module features)
3110 (let ((mod (module-public-interface module)))
3112 (hashq-set! %cond-expand-table mod
3113 (append (hashq-ref %cond-expand-table mod '())
3117 (procedure->memoizing-macro
3119 (let ((clauses (cdr exp))
3120 (syntax-error (lambda (cl)
3121 (error "invalid clause in `cond-expand'" cl))))
3127 (or (memq clause %cond-expand-features)
3128 (let lp ((uses (module-uses (env-module env))))
3131 (hashq-ref %cond-expand-table
3137 ((eq? 'and (car clause))
3138 (let lp ((l (cdr clause)))
3142 (and (test-clause (car l)) (lp (cdr l))))
3144 (syntax-error clause)))))
3145 ((eq? 'or (car clause))
3146 (let lp ((l (cdr clause)))
3150 (or (test-clause (car l)) (lp (cdr l))))
3152 (syntax-error clause)))))
3153 ((eq? 'not (car clause))
3154 (cond ((not (pair? (cdr clause)))
3155 (syntax-error clause))
3156 ((pair? (cddr clause))
3157 ((syntax-error clause))))
3158 (not (test-clause (cadr clause))))
3160 (syntax-error clause))))
3162 (syntax-error clause))))))
3163 (let lp ((c clauses))
3166 (error "Unfulfilled `cond-expand'"))
3169 ((not (pair? (car c)))
3170 (syntax-error (car c)))
3171 ((test-clause (caar c))
3172 `(begin ,@(cdar c)))
3173 ((eq? (caar c) 'else)
3176 `(begin ,@(cdar c)))
3178 (lp (cdr c))))))))))
3180 ;; This procedure gets called from the startup code with a list of
3181 ;; numbers, which are the numbers of the SRFIs to be loaded on startup.
3183 (define (use-srfis srfis)
3184 (process-use-modules
3186 (list (list 'srfi (string->symbol
3187 (string-append "srfi-" (number->string num))))))
3192 ;;; srfi-55: require-extension
3195 (define-macro (require-extension extension-spec)
3196 ;; This macro only handles the srfi extension, which, at present, is
3197 ;; the only one defined by the standard.
3198 (if (not (pair? extension-spec))
3199 (scm-error 'wrong-type-arg "require-extension"
3200 "Not an extension: ~S" (list extension-spec) #f))
3201 (let ((extension (car extension-spec))
3202 (extension-args (cdr extension-spec)))
3205 (let ((use-list '()))
3208 (if (not (integer? i))
3209 (scm-error 'wrong-type-arg "require-extension"
3210 "Invalid srfi name: ~S" (list i) #f))
3211 (let ((srfi-sym (string->symbol
3212 (string-append "srfi-" (number->string i)))))
3213 (if (not (memq srfi-sym %cond-expand-features))
3214 (set! use-list (cons `(use-modules (srfi ,srfi-sym))
3217 (if (pair? use-list)
3218 ;; i.e. (begin (use-modules x) (use-modules y) (use-modules z))
3219 `(begin ,@(reverse! use-list)))))
3222 'wrong-type-arg "require-extension"
3223 "Not a recognized extension type: ~S" (list extension) #f)))))
3227 ;;; {Load emacs interface support if emacs option is given.}
3230 (define (named-module-use! user usee)
3231 (module-use! (resolve-module user) (resolve-interface usee)))
3233 (define (load-emacs-interface)
3234 (and (provided? 'debug-extensions)
3235 (debug-enable 'backtrace))
3236 (named-module-use! '(guile-user) '(ice-9 emacs)))
3240 (define using-readline?
3241 (let ((using-readline? (make-fluid)))
3242 (make-procedure-with-setter
3243 (lambda () (fluid-ref using-readline?))
3244 (lambda (v) (fluid-set! using-readline? v)))))
3247 (let ((guile-user-module (resolve-module '(guile-user))))
3249 ;; Load emacs interface support if emacs option is given.
3250 (if (and (module-defined? guile-user-module 'use-emacs-interface)
3251 (module-ref guile-user-module 'use-emacs-interface))
3252 (load-emacs-interface))
3254 ;; Use some convenient modules (in reverse order)
3256 (set-current-module guile-user-module)
3257 (process-use-modules
3262 (if (provided? 'regex)
3265 (if (provided? 'threads)
3266 '(((ice-9 threads)))
3268 ;; load debugger on demand
3269 (module-autoload! guile-user-module '(ice-9 debugger) '(debug))
3271 ;; Note: SIGFPE, SIGSEGV and SIGBUS are actually "query-only" (see
3272 ;; scmsigs.c scm_sigaction_for_thread), so the handlers setup here have
3274 (let ((old-handlers #f)
3275 (start-repl (module-ref (resolve-interface '(system repl repl))
3277 (signals (if (provided? 'posix)
3278 `((,SIGINT . "User interrupt")
3279 (,SIGFPE . "Arithmetic error")
3281 . "Bad memory access (Segmentation violation)"))
3283 ;; no SIGBUS on mingw
3284 (if (defined? 'SIGBUS)
3285 (set! signals (acons SIGBUS "Bad memory access (bus error)"
3292 (let ((make-handler (lambda (msg)
3294 ;; Make a backup copy of the stack
3295 (fluid-set! before-signal-stack
3296 (fluid-ref the-last-stack))
3304 (map (lambda (sig-msg)
3305 (sigaction (car sig-msg)
3306 (make-handler (cdr sig-msg))))
3309 ;; the protected thunk.
3311 (let ((status (start-repl 'scheme)))
3312 (run-hook exit-hook)
3317 (map (lambda (sig-msg old-handler)
3318 (if (not (car old-handler))
3319 ;; restore original C handler.
3320 (sigaction (car sig-msg) #f)
3321 ;; restore Scheme handler, SIG_IGN or SIG_DFL.
3322 (sigaction (car sig-msg)
3324 (cdr old-handler))))
3325 signals old-handlers))))))
3327 ;;; This hook is run at the very end of an interactive session.
3329 (define exit-hook (make-hook))
3333 ;;; {Deprecated stuff}
3337 (define (feature? sym)
3338 (issue-deprecation-warning
3339 "`feature?' is deprecated. Use `provided?' instead.")
3343 (primitive-load-path "ice-9/deprecated"))
3347 ;;; Place the user in the guile-user module.
3350 ;;; FIXME: annotate ?
3351 ;; (define (syncase exp)
3352 ;; (with-fluids ((expansion-eval-closure
3353 ;; (module-eval-closure (current-module))))
3354 ;; (deannotate/source-properties (sc-expand (annotate exp)))))
3356 (define-module (guile-user))
3358 ;;; boot-9.scm ends here