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
36 (define (void) (if #f #f))
38 ;; Before compiling, make sure any symbols are resolved in the (guile)
39 ;; module, the primary location of those symbols, rather than in
40 ;; (guile-user), the default module that we compile in.
43 (set-current-module (resolve-module '(guile))))
48 (primitive-load-path "ice-9/r4rs")
52 ;;; {Simple Debugging Tools}
55 ;; peek takes any number of arguments, writes them to the
56 ;; current ouput port, and returns the last argument.
57 ;; It is handy to wrap around an expression to look at
58 ;; a value each time is evaluated, e.g.:
60 ;; (+ 10 (troublesome-fn))
61 ;; => (+ 10 (pk 'troublesome-fn-returned (troublesome-fn)))
64 (define (peek . stuff)
69 (car (last-pair stuff)))
73 (define (warn . stuff)
74 (with-output-to-port (current-error-port)
77 (display ";;; WARNING ")
80 (car (last-pair stuff)))))
88 (if (not (memq sym *features*))
89 (set! *features* (cons sym *features*))))
91 ;; Return #t iff FEATURE is available to this Guile interpreter. In SLIB,
92 ;; provided? also checks to see if the module is available. We should do that
95 (define (provided? feature)
96 (and (memq feature *features*) #t))
98 ;; let format alias simple-format until the more complete version is loaded
100 (define format simple-format)
102 ;; this is scheme wrapping the C code so the final pred call is a tail call,
104 (define (string-any char_pred s . rest)
105 (let ((start (if (null? rest)
107 (end (if (or (null? rest) (null? (cdr rest)))
108 (string-length s) (cadr rest))))
109 (if (and (procedure? char_pred)
111 (<= end (string-length s))) ;; let c-code handle range error
112 (or (string-any-c-code char_pred s start (1- end))
113 (char_pred (string-ref s (1- end))))
114 (string-any-c-code char_pred s start end))))
116 ;; this is scheme wrapping the C code so the final pred call is a tail call,
118 (define (string-every char_pred s . rest)
119 (let ((start (if (null? rest)
121 (end (if (or (null? rest) (null? (cdr rest)))
122 (string-length s) (cadr rest))))
123 (if (and (procedure? char_pred)
125 (<= end (string-length s))) ;; let c-code handle range error
126 (and (string-every-c-code char_pred s start (1- end))
127 (char_pred (string-ref s (1- end))))
128 (string-every-c-code char_pred s start end))))
130 ;; A variant of string-fill! that we keep for compatability
132 (define (substring-fill! str start end fill)
133 (string-fill! str fill start end))
137 ;; Before the module system boots, there are no module names. But
138 ;; psyntax does want a module-name definition, so give it one.
139 (define (module-name x)
141 (define (module-add! module sym var)
142 (hashq-set! (%get-pre-modules-obarray) sym var))
143 (define (make-module-ref mod var kind)
145 ((public) (if mod `(@ ,mod ,var) var))
146 ((private) (if (and mod (not (equal? mod (module-name (current-module)))))
150 ((hygiene) (if (and mod
151 (not (equal? mod (module-name (current-module))))
152 (module-variable (resolve-module mod) var))
155 (else (error "foo" mod var kind))))
156 (define (resolve-module . args)
159 ;;; Here we use "keyword" in the sense that R6RS uses it, as in "a
160 ;;; definition may be a keyword definition or a variable definition".
161 ;;; Keywords are syntactic bindings; variables are value bindings.
162 (define (module-define-keyword! mod sym type val)
163 (let ((v (or (module-local-variable mod sym)
164 (let ((v (make-variable val)))
165 (module-add! mod sym v)
167 (if (or (not (variable-bound? v))
168 (not (macro? (variable-ref v))))
169 (variable-set! v val))
170 (set-object-property! v '*sc-expander* (cons type val))))
172 (define (module-lookup-keyword mod sym)
173 (let ((v (module-variable mod sym)))
174 (and v (object-property v '*sc-expander*))))
176 (define (module-undefine-keyword! mod sym)
177 (let ((v (module-local-variable mod sym)))
179 (let ((p (assq '*sc-expander* (object-properties v))))
180 ;; probably should unbind the variable too
181 (set-object-properties! v (delq p (object-properties v)))))))
183 (define sc-expand #f)
184 (define sc-expand3 #f)
185 (define install-global-transformer #f)
186 (define syntax-dispatch #f)
187 (define syntax-violation #f)
188 (define (annotation? x) #f)
190 (define datum->syntax #f)
191 (define syntax->datum #f)
193 (define identifier? #f)
194 (define generate-temporaries #f)
195 (define bound-identifier=? #f)
196 (define free-identifier=? #f)
199 (lambda (f first . rest)
202 (let andmap ((first first))
203 (let ((x (car first)) (first (cdr first)))
206 (and (f x) (andmap first)))))
207 (let andmap ((first first) (rest rest))
208 (let ((x (car first))
211 (rest (map cdr rest)))
213 (apply f (cons x xr))
214 (and (apply f (cons x xr)) (andmap first rest)))))))))
216 (define (syncase-error who format-string why what)
217 (%start-stack 'syncase-stack
219 (scm-error 'misc-error who "~A ~S" (list why what) '()))))
221 ;; Until the module system is booted, this will be the current expander.
222 (primitive-load-path "ice-9/psyntax-pp")
224 (define %pre-modules-transformer sc-expand)
230 ;;; Depends on: features, eval-case
233 (define-syntax define-macro
237 ((_ (macro . args) doc body1 body ...)
238 (string? (syntax->datum (syntax doc)))
239 (syntax (define-macro macro doc (lambda args body1 body ...))))
240 ((_ (macro . args) body ...)
241 (syntax (define-macro macro #f (lambda args body ...))))
242 ((_ macro doc transformer)
243 (or (string? (syntax->datum (syntax doc)))
244 (not (syntax->datum (syntax doc))))
251 (let ((v (syntax->datum (syntax args))))
252 (datum->syntax y (apply transformer v))))))))))))
254 (define-syntax defmacro
256 "Define a defmacro, with the old lispy defun syntax."
258 ((_ macro args doc body1 body ...)
259 (string? (syntax->datum (syntax doc)))
260 (syntax (define-macro macro doc (lambda args body1 body ...))))
261 ((_ macro args body ...)
262 (syntax (define-macro macro #f (lambda args body ...)))))))
270 ;;; Depends on: defmacro
273 (defmacro begin-deprecated forms
274 (if (include-deprecated-features)
280 ;;; {Trivial Functions}
283 (define (identity x) x)
284 (define (and=> value procedure) (and value (procedure value)))
285 (define call/cc call-with-current-continuation)
287 ;;; apply-to-args is functionally redundant with apply and, worse,
288 ;;; is less general than apply since it only takes two arguments.
290 ;;; On the other hand, apply-to-args is a syntacticly convenient way to
291 ;;; perform binding in many circumstances when the "let" family of
292 ;;; of forms don't cut it. E.g.:
294 ;;; (apply-to-args (return-3d-mouse-coords)
299 (define (apply-to-args args fn) (apply fn args))
301 (defmacro false-if-exception (expr)
302 `(catch #t (lambda () ,expr)
307 ;;; {General Properties}
310 ;; This is a more modern interface to properties. It will replace all
311 ;; other property-like things eventually.
313 (define (make-object-property)
314 (let ((prop (primitive-make-property #f)))
315 (make-procedure-with-setter
316 (lambda (obj) (primitive-property-ref prop obj))
317 (lambda (obj val) (primitive-property-set! prop obj val)))))
321 ;;; {Symbol Properties}
324 (define (symbol-property sym prop)
325 (let ((pair (assoc prop (symbol-pref sym))))
326 (and pair (cdr pair))))
328 (define (set-symbol-property! sym prop val)
329 (let ((pair (assoc prop (symbol-pref sym))))
332 (symbol-pset! sym (acons prop val (symbol-pref sym))))))
334 (define (symbol-property-remove! sym prop)
335 (let ((pair (assoc prop (symbol-pref sym))))
337 (symbol-pset! sym (delq! pair (symbol-pref sym))))))
344 (define (array-shape a)
345 (map (lambda (ind) (if (number? ind) (list 0 (+ -1 ind)) ind))
346 (array-dimensions a)))
353 (define (kw-arg-ref args kw)
354 (let ((rem (member kw args)))
355 (and rem (pair? (cdr rem)) (cadr rem))))
362 (define (struct-layout s)
363 (struct-ref (struct-vtable s) vtable-index-layout))
370 ;; Printing records: by default, records are printed as
372 ;; #<type-name field1: val1 field2: val2 ...>
374 ;; You can change that by giving a custom printing function to
375 ;; MAKE-RECORD-TYPE (after the list of field symbols). This function
376 ;; will be called like
378 ;; (<printer> object port)
380 ;; It should print OBJECT to PORT.
382 (define (inherit-print-state old-port new-port)
383 (if (get-print-state old-port)
384 (port-with-print-state new-port (get-print-state old-port))
387 ;; 0: type-name, 1: fields
388 (define record-type-vtable
389 (make-vtable-vtable "prpr" 0
391 (cond ((eq? s record-type-vtable)
392 (display "#<record-type-vtable>" p))
394 (display "#<record-type " p)
395 (display (record-type-name s) p)
398 (define (record-type? obj)
399 (and (struct? obj) (eq? record-type-vtable (struct-vtable obj))))
401 (define (make-record-type type-name fields . opt)
402 (let ((printer-fn (and (pair? opt) (car opt))))
403 (let ((struct (make-struct record-type-vtable 0
406 (map (lambda (f) "pw") fields)))
410 (display type-name p)
411 (let loop ((fields fields)
414 ((not (null? fields))
416 (display (car fields) p)
418 (display (struct-ref s off) p)
419 (loop (cdr fields) (+ 1 off)))))
422 (copy-tree fields))))
423 ;; Temporary solution: Associate a name to the record type descriptor
424 ;; so that the object system can create a wrapper class for it.
425 (set-struct-vtable-name! struct (if (symbol? type-name)
427 (string->symbol type-name)))
430 (define (record-type-name obj)
431 (if (record-type? obj)
432 (struct-ref obj vtable-offset-user)
433 (error 'not-a-record-type obj)))
435 (define (record-type-fields obj)
436 (if (record-type? obj)
437 (struct-ref obj (+ 1 vtable-offset-user))
438 (error 'not-a-record-type obj)))
440 (define (record-constructor rtd . opt)
441 (let ((field-names (if (pair? opt) (car opt) (record-type-fields rtd))))
443 `(lambda ,field-names
444 (make-struct ',rtd 0 ,@(map (lambda (f)
445 (if (memq f field-names)
448 (record-type-fields rtd)))))))
450 (define (record-predicate rtd)
451 (lambda (obj) (and (struct? obj) (eq? rtd (struct-vtable obj)))))
453 (define (%record-type-error rtd obj) ;; private helper
454 (or (eq? rtd (record-type-descriptor obj))
455 (scm-error 'wrong-type-arg "%record-type-check"
456 "Wrong type record (want `~S'): ~S"
457 (list (record-type-name rtd) obj)
460 (define (record-accessor rtd field-name)
461 (let ((pos (list-index (record-type-fields rtd) field-name)))
463 (error 'no-such-field field-name))
465 (if (eq? (struct-vtable obj) rtd)
467 (%record-type-error rtd obj)))))
469 (define (record-modifier rtd field-name)
470 (let ((pos (list-index (record-type-fields rtd) field-name)))
472 (error 'no-such-field field-name))
474 (if (eq? (struct-vtable obj) rtd)
475 (struct-set! obj pos val)
476 (%record-type-error rtd obj)))))
478 (define (record? obj)
479 (and (struct? obj) (record-type? (struct-vtable obj))))
481 (define (record-type-descriptor obj)
484 (error 'not-a-record obj)))
493 (define (->bool x) (not (not x)))
500 (define (symbol-append . args)
501 (string->symbol (apply string-append (map symbol->string args))))
503 (define (list->symbol . args)
504 (string->symbol (apply list->string args)))
506 (define (symbol . args)
507 (string->symbol (apply string args)))
514 (define (list-index l k)
520 (loop (+ n 1) (cdr l))))))
524 ;;; {and-map and or-map}
526 ;;; (and-map fn lst) is like (and (fn (car lst)) (fn (cadr lst)) (fn...) ...)
527 ;;; (or-map fn lst) is like (or (fn (car lst)) (fn (cadr lst)) (fn...) ...)
532 ;; Apply f to successive elements of l until exhaustion or f returns #f.
533 ;; If returning early, return #f. Otherwise, return the last value returned
534 ;; by f. If f has never been called because l is empty, return #t.
536 (define (and-map f lst)
537 (let loop ((result #t)
542 (loop (f (car l)) (cdr l))))))
546 ;; Apply f to successive elements of l until exhaustion or while f returns #f.
547 ;; If returning early, return the return value of f.
549 (define (or-map f lst)
550 (let loop ((result #f)
554 (loop (f (car l)) (cdr l))))))
558 (if (provided? 'posix)
559 (primitive-load-path "ice-9/posix"))
561 (if (provided? 'socket)
562 (primitive-load-path "ice-9/networking"))
564 ;; For reference, Emacs file-exists-p uses stat in this same way.
565 ;; ENHANCE-ME: Catching an exception from stat is a bit wasteful, do this in
566 ;; C where all that's needed is to inspect the return from stat().
568 (if (provided? 'posix)
570 (->bool (false-if-exception (stat str))))
572 (let ((port (catch 'system-error (lambda () (open-file str OPEN_READ))
574 (if port (begin (close-port port) #t)
577 (define file-is-directory?
578 (if (provided? 'posix)
580 (eq? (stat:type (stat str)) 'directory))
582 (let ((port (catch 'system-error
583 (lambda () (open-file (string-append str "/.")
586 (if port (begin (close-port port) #t)
589 (define (has-suffix? str suffix)
590 (string-suffix? suffix str))
592 (define (system-error-errno args)
593 (if (eq? (car args) 'system-error)
594 (car (list-ref args 4))
602 (define (error . args)
605 (scm-error 'misc-error #f "?" #f #f)
606 (let loop ((msg "~A")
608 (if (not (null? rest))
609 (loop (string-append msg " ~S")
611 (scm-error 'misc-error #f msg args #f)))))
613 ;; bad-throw is the hook that is called upon a throw to a an unhandled
614 ;; key (unless the throw has four arguments, in which case
615 ;; it's usually interpreted as an error throw.)
616 ;; If the key has a default handler (a throw-handler-default property),
617 ;; it is applied to the throw.
619 (define (bad-throw key . args)
620 (let ((default (symbol-property key 'throw-handler-default)))
621 (or (and default (apply default key args))
622 (apply error "unhandled-exception:" key args))))
626 (define (tm:sec obj) (vector-ref obj 0))
627 (define (tm:min obj) (vector-ref obj 1))
628 (define (tm:hour obj) (vector-ref obj 2))
629 (define (tm:mday obj) (vector-ref obj 3))
630 (define (tm:mon obj) (vector-ref obj 4))
631 (define (tm:year obj) (vector-ref obj 5))
632 (define (tm:wday obj) (vector-ref obj 6))
633 (define (tm:yday obj) (vector-ref obj 7))
634 (define (tm:isdst obj) (vector-ref obj 8))
635 (define (tm:gmtoff obj) (vector-ref obj 9))
636 (define (tm:zone obj) (vector-ref obj 10))
638 (define (set-tm:sec obj val) (vector-set! obj 0 val))
639 (define (set-tm:min obj val) (vector-set! obj 1 val))
640 (define (set-tm:hour obj val) (vector-set! obj 2 val))
641 (define (set-tm:mday obj val) (vector-set! obj 3 val))
642 (define (set-tm:mon obj val) (vector-set! obj 4 val))
643 (define (set-tm:year obj val) (vector-set! obj 5 val))
644 (define (set-tm:wday obj val) (vector-set! obj 6 val))
645 (define (set-tm:yday obj val) (vector-set! obj 7 val))
646 (define (set-tm:isdst obj val) (vector-set! obj 8 val))
647 (define (set-tm:gmtoff obj val) (vector-set! obj 9 val))
648 (define (set-tm:zone obj val) (vector-set! obj 10 val))
650 (define (tms:clock obj) (vector-ref obj 0))
651 (define (tms:utime obj) (vector-ref obj 1))
652 (define (tms:stime obj) (vector-ref obj 2))
653 (define (tms:cutime obj) (vector-ref obj 3))
654 (define (tms:cstime obj) (vector-ref obj 4))
656 (define file-position ftell)
657 (define (file-set-position port offset . whence)
658 (let ((whence (if (eq? whence '()) SEEK_SET (car whence))))
659 (seek port offset whence)))
661 (define (move->fdes fd/port fd)
662 (cond ((integer? fd/port)
663 (dup->fdes fd/port fd)
667 (primitive-move->fdes fd/port fd)
668 (set-port-revealed! fd/port 1)
671 (define (release-port-handle port)
672 (let ((revealed (port-revealed port)))
674 (set-port-revealed! port (- revealed 1)))))
676 (define (dup->port port/fd mode . maybe-fd)
677 (let ((port (fdopen (apply dup->fdes port/fd maybe-fd)
680 (set-port-revealed! port 1))
683 (define (dup->inport port/fd . maybe-fd)
684 (apply dup->port port/fd "r" maybe-fd))
686 (define (dup->outport port/fd . maybe-fd)
687 (apply dup->port port/fd "w" maybe-fd))
689 (define (dup port/fd . maybe-fd)
690 (if (integer? port/fd)
691 (apply dup->fdes port/fd maybe-fd)
692 (apply dup->port port/fd (port-mode port/fd) maybe-fd)))
694 (define (duplicate-port port modes)
695 (dup->port port modes))
697 (define (fdes->inport fdes)
698 (let loop ((rest-ports (fdes->ports fdes)))
699 (cond ((null? rest-ports)
700 (let ((result (fdopen fdes "r")))
701 (set-port-revealed! result 1)
703 ((input-port? (car rest-ports))
704 (set-port-revealed! (car rest-ports)
705 (+ (port-revealed (car rest-ports)) 1))
708 (loop (cdr rest-ports))))))
710 (define (fdes->outport fdes)
711 (let loop ((rest-ports (fdes->ports fdes)))
712 (cond ((null? rest-ports)
713 (let ((result (fdopen fdes "w")))
714 (set-port-revealed! result 1)
716 ((output-port? (car rest-ports))
717 (set-port-revealed! (car rest-ports)
718 (+ (port-revealed (car rest-ports)) 1))
721 (loop (cdr rest-ports))))))
723 (define (port->fdes port)
724 (set-port-revealed! port (+ (port-revealed port) 1))
727 (define (setenv name value)
729 (putenv (string-append name "=" value))
732 (define (unsetenv name)
733 "Remove the entry for NAME from the environment."
741 ;;; Here for backward compatability
743 (define scheme-file-suffix (lambda () ".scm"))
745 (define (in-vicinity vicinity file)
746 (let ((tail (let ((len (string-length vicinity)))
749 (string-ref vicinity (- len 1))))))
750 (string-append vicinity
759 ;;; {Help for scm_shell}
761 ;;; The argument-processing code used by Guile-based shells generates
762 ;;; Scheme code based on the argument list. This page contains help
763 ;;; functions for the code it generates.
766 (define (command-line) (program-arguments))
768 ;; This is mostly for the internal use of the code generated by
769 ;; scm_compile_shell_switches.
771 (define (turn-on-debugging)
772 (debug-enable 'debug)
773 (debug-enable 'backtrace)
774 (read-enable 'positions))
776 (define (load-user-init)
777 (let* ((home (or (getenv "HOME")
778 (false-if-exception (passwd:dir (getpwuid (getuid))))
779 "/")) ;; fallback for cygwin etc.
780 (init-file (in-vicinity home ".guile")))
781 (if (file-exists? init-file)
782 (primitive-load init-file))))
786 ;;; {The interpreter stack}
789 (defmacro start-stack (tag exp)
790 `(%start-stack ,tag (lambda () ,exp)))
794 ;;; {Loading by paths}
797 ;;; Load a Scheme source file named NAME, searching for it in the
798 ;;; directories listed in %load-path, and applying each of the file
799 ;;; name extensions listed in %load-extensions.
800 (define (load-from-path name)
801 (start-stack 'load-stack
802 (primitive-load-path name)))
804 (define %load-verbosely #f)
805 (define (assert-load-verbosity v) (set! %load-verbosely v))
807 (define (%load-announce file)
809 (with-output-to-port (current-error-port)
817 (set! %load-hook %load-announce)
819 (define (load name . reader)
820 (with-fluid* current-reader (and (pair? reader) (car reader))
822 (start-stack 'load-stack
823 (primitive-load name)))))
827 ;;; {Transcendental Functions}
829 ;;; Derived from "Transcen.scm", Complex trancendental functions for SCM.
830 ;;; Written by Jerry D. Hedden, (C) FSF.
831 ;;; See the file `COPYING' for terms applying to this program.
835 (let ((integer-expt integer-expt))
837 (cond ((and (exact? z2) (integer? z2))
838 (integer-expt z1 z2))
839 ((and (real? z2) (real? z1) (>= z1 0))
842 (exp (* z2 (log z1))))))))
845 (if (real? z) ($sinh z)
846 (let ((x (real-part z)) (y (imag-part z)))
847 (make-rectangular (* ($sinh x) ($cos y))
848 (* ($cosh x) ($sin y))))))
850 (if (real? z) ($cosh z)
851 (let ((x (real-part z)) (y (imag-part z)))
852 (make-rectangular (* ($cosh x) ($cos y))
853 (* ($sinh x) ($sin y))))))
855 (if (real? z) ($tanh z)
856 (let* ((x (* 2 (real-part z)))
857 (y (* 2 (imag-part z)))
858 (w (+ ($cosh x) ($cos y))))
859 (make-rectangular (/ ($sinh x) w) (/ ($sin y) w)))))
862 (if (real? z) ($asinh z)
863 (log (+ z (sqrt (+ (* z z) 1))))))
866 (if (and (real? z) (>= z 1))
868 (log (+ z (sqrt (- (* z z) 1))))))
871 (if (and (real? z) (> z -1) (< z 1))
873 (/ (log (/ (+ 1 z) (- 1 z))) 2)))
876 (if (real? z) ($sin z)
877 (let ((x (real-part z)) (y (imag-part z)))
878 (make-rectangular (* ($sin x) ($cosh y))
879 (* ($cos x) ($sinh y))))))
881 (if (real? z) ($cos z)
882 (let ((x (real-part z)) (y (imag-part z)))
883 (make-rectangular (* ($cos x) ($cosh y))
884 (- (* ($sin x) ($sinh y)))))))
886 (if (real? z) ($tan z)
887 (let* ((x (* 2 (real-part z)))
888 (y (* 2 (imag-part z)))
889 (w (+ ($cos x) ($cosh y))))
890 (make-rectangular (/ ($sin x) w) (/ ($sinh y) w)))))
893 (if (and (real? z) (>= z -1) (<= z 1))
895 (* -i (asinh (* +i z)))))
898 (if (and (real? z) (>= z -1) (<= z 1))
900 (+ (/ (angle -1) 2) (* +i (asinh (* +i z))))))
904 (if (real? z) ($atan z)
905 (/ (log (/ (- +i z) (+ +i z))) +2i))
910 ;;; {Reader Extensions}
912 ;;; Reader code for various "#c" forms.
915 (read-hash-extend #\' (lambda (c port)
918 (define read-eval? (make-fluid))
919 (fluid-set! read-eval? #f)
920 (read-hash-extend #\.
922 (if (fluid-ref read-eval?)
923 (eval (read port) (interaction-environment))
925 "#. read expansion found and read-eval? is #f."))))
929 ;;; {Command Line Options}
932 (define (get-option argv kw-opts kw-args return)
937 ((or (not (eq? #\- (string-ref (car argv) 0)))
938 (eq? (string-length (car argv)) 1))
939 (return 'normal-arg (car argv) (cdr argv)))
941 ((eq? #\- (string-ref (car argv) 1))
942 (let* ((kw-arg-pos (or (string-index (car argv) #\=)
943 (string-length (car argv))))
944 (kw (symbol->keyword (substring (car argv) 2 kw-arg-pos)))
945 (kw-opt? (member kw kw-opts))
946 (kw-arg? (member kw kw-args))
947 (arg (or (and (not (eq? kw-arg-pos (string-length (car argv))))
948 (substring (car argv)
950 (string-length (car argv))))
952 (begin (set! argv (cdr argv)) (car argv))))))
953 (if (or kw-opt? kw-arg?)
954 (return kw arg (cdr argv))
955 (return 'usage-error kw (cdr argv)))))
958 (let* ((char (substring (car argv) 1 2))
959 (kw (symbol->keyword char)))
963 (let* ((rest-car (substring (car argv) 2 (string-length (car argv))))
964 (new-argv (if (= 0 (string-length rest-car))
966 (cons (string-append "-" rest-car) (cdr argv)))))
967 (return kw #f new-argv)))
970 (let* ((rest-car (substring (car argv) 2 (string-length (car argv))))
971 (arg (if (= 0 (string-length rest-car))
974 (new-argv (if (= 0 (string-length rest-car))
977 (return kw arg new-argv)))
979 (else (return 'usage-error kw argv)))))))
981 (define (for-next-option proc argv kw-opts kw-args)
982 (let loop ((argv argv))
983 (get-option argv kw-opts kw-args
984 (lambda (opt opt-arg argv)
985 (and opt (proc opt opt-arg argv loop))))))
987 (define (display-usage-report kw-desc)
990 (or (eq? (car kw) #t)
993 (help (cadr opt-desc))
994 (opts (car opt-desc))
995 (opts-proper (if (string? (car opts)) (cdr opts) opts))
996 (arg-name (if (string? (car opts))
997 (string-append "<" (car opts) ">")
999 (left-part (string-append
1000 (with-output-to-string
1002 (map (lambda (x) (display (keyword->symbol x)) (display " "))
1005 (middle-part (if (and (< (string-length left-part) 30)
1006 (< (string-length help) 40))
1007 (make-string (- 30 (string-length left-part)) #\ )
1010 (display middle-part)
1017 (define (transform-usage-lambda cases)
1018 (let* ((raw-usage (delq! 'else (map car cases)))
1019 (usage-sans-specials (map (lambda (x)
1020 (or (and (not (list? x)) x)
1021 (and (symbol? (car x)) #t)
1022 (and (boolean? (car x)) #t)
1025 (usage-desc (delq! #t usage-sans-specials))
1026 (kw-desc (map car usage-desc))
1027 (kw-opts (apply append (map (lambda (x) (and (not (string? (car x))) x)) kw-desc)))
1028 (kw-args (apply append (map (lambda (x) (and (string? (car x)) (cdr x))) kw-desc)))
1029 (transmogrified-cases (map (lambda (case)
1030 (cons (let ((opts (car case)))
1031 (if (or (boolean? opts) (eq? 'else opts))
1034 ((symbol? (car opts)) opts)
1035 ((boolean? (car opts)) opts)
1036 ((string? (caar opts)) (cdar opts))
1037 (else (car opts)))))
1040 `(let ((%display-usage (lambda () (display-usage-report ',usage-desc))))
1042 (let %next-arg ((%argv %argv))
1046 (lambda (%opt %arg %new-argv)
1048 ,@ transmogrified-cases))))))))
1053 ;;; {Low Level Modules}
1055 ;;; These are the low level data structures for modules.
1057 ;;; Every module object is of the type 'module-type', which is a record
1058 ;;; consisting of the following members:
1060 ;;; - eval-closure: the function that defines for its module the strategy that
1061 ;;; shall be followed when looking up symbols in the module.
1063 ;;; An eval-closure is a function taking two arguments: the symbol to be
1064 ;;; looked up and a boolean value telling whether a binding for the symbol
1065 ;;; should be created if it does not exist yet. If the symbol lookup
1066 ;;; succeeded (either because an existing binding was found or because a new
1067 ;;; binding was created), a variable object representing the binding is
1068 ;;; returned. Otherwise, the value #f is returned. Note that the eval
1069 ;;; closure does not take the module to be searched as an argument: During
1070 ;;; construction of the eval-closure, the eval-closure has to store the
1071 ;;; module it belongs to in its environment. This means, that any
1072 ;;; eval-closure can belong to only one module.
1074 ;;; The eval-closure of a module can be defined arbitrarily. However, three
1075 ;;; special cases of eval-closures are to be distinguished: During startup
1076 ;;; the module system is not yet activated. In this phase, no modules are
1077 ;;; defined and all bindings are automatically stored by the system in the
1078 ;;; pre-modules-obarray. Since no eval-closures exist at this time, the
1079 ;;; functions which require an eval-closure as their argument need to be
1080 ;;; passed the value #f.
1082 ;;; The other two special cases of eval-closures are the
1083 ;;; standard-eval-closure and the standard-interface-eval-closure. Both
1084 ;;; behave equally for the case that no new binding is to be created. The
1085 ;;; difference between the two comes in, when the boolean argument to the
1086 ;;; eval-closure indicates that a new binding shall be created if it is not
1089 ;;; Given that no new binding shall be created, both standard eval-closures
1090 ;;; define the following standard strategy of searching bindings in the
1091 ;;; module: First, the module's obarray is searched for the symbol. Second,
1092 ;;; if no binding for the symbol was found in the module's obarray, the
1093 ;;; module's binder procedure is exececuted. If this procedure did not
1094 ;;; return a binding for the symbol, the modules referenced in the module's
1095 ;;; uses list are recursively searched for a binding of the symbol. If the
1096 ;;; binding can not be found in these modules also, the symbol lookup has
1099 ;;; If a new binding shall be created, the standard-interface-eval-closure
1100 ;;; immediately returns indicating failure. That is, it does not even try
1101 ;;; to look up the symbol. In contrast, the standard-eval-closure would
1102 ;;; first search the obarray, and if no binding was found there, would
1103 ;;; create a new binding in the obarray, therefore not calling the binder
1104 ;;; procedure or searching the modules in the uses list.
1106 ;;; The explanation of the following members obarray, binder and uses
1107 ;;; assumes that the symbol lookup follows the strategy that is defined in
1108 ;;; the standard-eval-closure and the standard-interface-eval-closure.
1110 ;;; - obarray: a hash table that maps symbols to variable objects. In this
1111 ;;; hash table, the definitions are found that are local to the module (that
1112 ;;; is, not imported from other modules). When looking up bindings in the
1113 ;;; module, this hash table is searched first.
1115 ;;; - binder: either #f or a function taking a module and a symbol argument.
1116 ;;; If it is a function it is called after the obarray has been
1117 ;;; unsuccessfully searched for a binding. It then can provide bindings
1118 ;;; that would otherwise not be found locally in the module.
1120 ;;; - uses: a list of modules from which non-local bindings can be inherited.
1121 ;;; These modules are the third place queried for bindings after the obarray
1122 ;;; has been unsuccessfully searched and the binder function did not deliver
1123 ;;; a result either.
1125 ;;; - transformer: either #f or a function taking a scheme expression as
1126 ;;; delivered by read. If it is a function, it will be called to perform
1127 ;;; syntax transformations (e. g. makro expansion) on the given scheme
1128 ;;; expression. The output of the transformer function will then be passed
1129 ;;; to Guile's internal memoizer. This means that the output must be valid
1130 ;;; scheme code. The only exception is, that the output may make use of the
1131 ;;; syntax extensions provided to identify the modules that a binding
1134 ;;; - name: the name of the module. This is used for all kinds of printing
1135 ;;; outputs. In certain places the module name also serves as a way of
1136 ;;; identification. When adding a module to the uses list of another
1137 ;;; module, it is made sure that the new uses list will not contain two
1138 ;;; modules of the same name.
1140 ;;; - kind: classification of the kind of module. The value is (currently?)
1141 ;;; only used for printing. It has no influence on how a module is treated.
1142 ;;; Currently the following values are used when setting the module kind:
1143 ;;; 'module, 'directory, 'interface, 'custom-interface. If no explicit kind
1144 ;;; is set, it defaults to 'module.
1146 ;;; - duplicates-handlers: a list of procedures that get called to make a
1147 ;;; choice between two duplicate bindings when name clashes occur. See the
1148 ;;; `duplicate-handlers' global variable below.
1150 ;;; - observers: a list of procedures that get called when the module is
1153 ;;; - weak-observers: a weak-key hash table of procedures that get called
1154 ;;; when the module is modified. See `module-observe-weak' for details.
1156 ;;; In addition, the module may (must?) contain a binding for
1157 ;;; `%module-public-interface'. This variable should be bound to a module
1158 ;;; representing the exported interface of a module. See the
1159 ;;; `module-public-interface' and `module-export!' procedures.
1161 ;;; !!! warning: The interface to lazy binder procedures is going
1162 ;;; to be changed in an incompatible way to permit all the basic
1163 ;;; module ops to be virtualized.
1165 ;;; (make-module size use-list lazy-binding-proc) => module
1166 ;;; module-{obarray,uses,binder}[|-set!]
1167 ;;; (module? obj) => [#t|#f]
1168 ;;; (module-locally-bound? module symbol) => [#t|#f]
1169 ;;; (module-bound? module symbol) => [#t|#f]
1170 ;;; (module-symbol-locally-interned? module symbol) => [#t|#f]
1171 ;;; (module-symbol-interned? module symbol) => [#t|#f]
1172 ;;; (module-local-variable module symbol) => [#<variable ...> | #f]
1173 ;;; (module-variable module symbol) => [#<variable ...> | #f]
1174 ;;; (module-symbol-binding module symbol opt-value)
1175 ;;; => [ <obj> | opt-value | an error occurs ]
1176 ;;; (module-make-local-var! module symbol) => #<variable...>
1177 ;;; (module-add! module symbol var) => unspecified
1178 ;;; (module-remove! module symbol) => unspecified
1179 ;;; (module-for-each proc module) => unspecified
1180 ;;; (make-scm-module) => module ; a lazy copy of the symhash module
1181 ;;; (set-current-module module) => unspecified
1182 ;;; (current-module) => #<module...>
1188 ;;; {Printing Modules}
1191 ;; This is how modules are printed. You can re-define it.
1192 ;; (Redefining is actually more complicated than simply redefining
1193 ;; %print-module because that would only change the binding and not
1194 ;; the value stored in the vtable that determines how record are
1197 (define (%print-module mod port) ; unused args: depth length style table)
1199 (display (or (module-kind mod) "module") port)
1200 (let ((name (module-name mod)))
1204 (display name port))))
1206 (display (number->string (object-address mod) 16) port)
1211 ;; A module is characterized by an obarray in which local symbols
1212 ;; are interned, a list of modules, "uses", from which non-local
1213 ;; bindings can be inherited, and an optional lazy-binder which
1214 ;; is a (CLOSURE module symbol) which, as a last resort, can provide
1215 ;; bindings that would otherwise not be found locally in the module.
1217 ;; NOTE: If you change anything here, you also need to change
1218 ;; libguile/modules.h.
1221 (make-record-type 'module
1222 '(obarray uses binder eval-closure transformer name kind
1223 duplicates-handlers import-obarray
1224 observers weak-observers)
1227 ;; make-module &opt size uses binder
1229 ;; Create a new module, perhaps with a particular size of obarray,
1230 ;; initial uses list, or binding procedure.
1235 (define (parse-arg index default)
1236 (if (> (length args) index)
1237 (list-ref args index)
1240 (define %default-import-size
1241 ;; Typical number of imported bindings actually used by a module.
1244 (if (> (length args) 3)
1245 (error "Too many args to make-module." args))
1247 (let ((size (parse-arg 0 31))
1248 (uses (parse-arg 1 '()))
1249 (binder (parse-arg 2 #f)))
1251 (if (not (integer? size))
1252 (error "Illegal size to make-module." size))
1253 (if (not (and (list? uses)
1254 (and-map module? uses)))
1255 (error "Incorrect use list." uses))
1256 (if (and binder (not (procedure? binder)))
1258 "Lazy-binder expected to be a procedure or #f." binder))
1260 (let ((module (module-constructor (make-hash-table size)
1261 uses binder #f %pre-modules-transformer
1263 (make-hash-table %default-import-size)
1265 (make-weak-key-hash-table 31))))
1267 ;; We can't pass this as an argument to module-constructor,
1268 ;; because we need it to close over a pointer to the module
1270 (set-module-eval-closure! module (standard-eval-closure module))
1274 (define module-constructor (record-constructor module-type))
1275 (define module-obarray (record-accessor module-type 'obarray))
1276 (define set-module-obarray! (record-modifier module-type 'obarray))
1277 (define module-uses (record-accessor module-type 'uses))
1278 (define set-module-uses! (record-modifier module-type 'uses))
1279 (define module-binder (record-accessor module-type 'binder))
1280 (define set-module-binder! (record-modifier module-type 'binder))
1282 ;; NOTE: This binding is used in libguile/modules.c.
1283 (define module-eval-closure (record-accessor module-type 'eval-closure))
1285 (define module-transformer (record-accessor module-type 'transformer))
1286 (define set-module-transformer! (record-modifier module-type 'transformer))
1287 ;; (define module-name (record-accessor module-type 'name)) wait until mods are booted
1288 (define set-module-name! (record-modifier module-type 'name))
1289 (define module-kind (record-accessor module-type 'kind))
1290 (define set-module-kind! (record-modifier module-type 'kind))
1291 (define module-duplicates-handlers
1292 (record-accessor module-type 'duplicates-handlers))
1293 (define set-module-duplicates-handlers!
1294 (record-modifier module-type 'duplicates-handlers))
1295 (define module-observers (record-accessor module-type 'observers))
1296 (define set-module-observers! (record-modifier module-type 'observers))
1297 (define module-weak-observers (record-accessor module-type 'weak-observers))
1298 (define module? (record-predicate module-type))
1300 (define module-import-obarray (record-accessor module-type 'import-obarray))
1302 (define set-module-eval-closure!
1303 (let ((setter (record-modifier module-type 'eval-closure)))
1304 (lambda (module closure)
1305 (setter module closure)
1306 ;; Make it possible to lookup the module from the environment.
1307 ;; This implementation is correct since an eval closure can belong
1308 ;; to maximally one module.
1309 (set-procedure-property! closure 'module module))))
1313 ;;; {Observer protocol}
1316 (define (module-observe module proc)
1317 (set-module-observers! module (cons proc (module-observers module)))
1320 (define (module-observe-weak module observer-id . proc)
1321 ;; Register PROC as an observer of MODULE under name OBSERVER-ID (which can
1322 ;; be any Scheme object). PROC is invoked and passed MODULE any time
1323 ;; MODULE is modified. PROC gets unregistered when OBSERVER-ID gets GC'd
1324 ;; (thus, it is never unregistered if OBSERVER-ID is an immediate value,
1327 ;; The two-argument version is kept for backward compatibility: when called
1328 ;; with two arguments, the observer gets unregistered when closure PROC
1329 ;; gets GC'd (making it impossible to use an anonymous lambda for PROC).
1331 (let ((proc (if (null? proc) observer-id (car proc))))
1332 (hashq-set! (module-weak-observers module) observer-id proc)))
1334 (define (module-unobserve token)
1335 (let ((module (car token))
1338 (hash-remove! (module-weak-observers module) id)
1339 (set-module-observers! module (delq1! id (module-observers module)))))
1342 (define module-defer-observers #f)
1343 (define module-defer-observers-mutex (make-mutex 'recursive))
1344 (define module-defer-observers-table (make-hash-table))
1346 (define (module-modified m)
1347 (if module-defer-observers
1348 (hash-set! module-defer-observers-table m #t)
1349 (module-call-observers m)))
1351 ;;; This function can be used to delay calls to observers so that they
1352 ;;; can be called once only in the face of massive updating of modules.
1354 (define (call-with-deferred-observers thunk)
1357 (lock-mutex module-defer-observers-mutex)
1358 (set! module-defer-observers #t))
1361 (set! module-defer-observers #f)
1362 (hash-for-each (lambda (m dummy)
1363 (module-call-observers m))
1364 module-defer-observers-table)
1365 (hash-clear! module-defer-observers-table)
1366 (unlock-mutex module-defer-observers-mutex))))
1368 (define (module-call-observers m)
1369 (for-each (lambda (proc) (proc m)) (module-observers m))
1371 ;; We assume that weak observers don't (un)register themselves as they are
1372 ;; called since this would preclude proper iteration over the hash table
1374 (hash-for-each (lambda (id proc) (proc m)) (module-weak-observers m)))
1378 ;;; {Module Searching in General}
1380 ;;; We sometimes want to look for properties of a symbol
1381 ;;; just within the obarray of one module. If the property
1382 ;;; holds, then it is said to hold ``locally'' as in, ``The symbol
1383 ;;; DISPLAY is locally rebound in the module `safe-guile'.''
1386 ;;; Other times, we want to test for a symbol property in the obarray
1387 ;;; of M and, if it is not found there, try each of the modules in the
1388 ;;; uses list of M. This is the normal way of testing for some
1389 ;;; property, so we state these properties without qualification as
1390 ;;; in: ``The symbol 'fnord is interned in module M because it is
1391 ;;; interned locally in module M2 which is a member of the uses list
1395 ;; module-search fn m
1397 ;; return the first non-#f result of FN applied to M and then to
1398 ;; the modules in the uses of m, and so on recursively. If all applications
1399 ;; return #f, then so does this function.
1401 (define (module-search fn m v)
1404 (or (module-search fn (car pos) v)
1407 (loop (module-uses m))))
1410 ;;; {Is a symbol bound in a module?}
1412 ;;; Symbol S in Module M is bound if S is interned in M and if the binding
1413 ;;; of S in M has been set to some well-defined value.
1416 ;; module-locally-bound? module symbol
1418 ;; Is a symbol bound (interned and defined) locally in a given module?
1420 (define (module-locally-bound? m v)
1421 (let ((var (module-local-variable m v)))
1423 (variable-bound? var))))
1425 ;; module-bound? module symbol
1427 ;; Is a symbol bound (interned and defined) anywhere in a given module
1430 (define (module-bound? m v)
1431 (let ((var (module-variable m v)))
1433 (variable-bound? var))))
1435 ;;; {Is a symbol interned in a module?}
1437 ;;; Symbol S in Module M is interned if S occurs in
1438 ;;; of S in M has been set to some well-defined value.
1440 ;;; It is possible to intern a symbol in a module without providing
1441 ;;; an initial binding for the corresponding variable. This is done
1443 ;;; (module-add! module symbol (make-undefined-variable))
1445 ;;; In that case, the symbol is interned in the module, but not
1446 ;;; bound there. The unbound symbol shadows any binding for that
1447 ;;; symbol that might otherwise be inherited from a member of the uses list.
1450 (define (module-obarray-get-handle ob key)
1451 ((if (symbol? key) hashq-get-handle hash-get-handle) ob key))
1453 (define (module-obarray-ref ob key)
1454 ((if (symbol? key) hashq-ref hash-ref) ob key))
1456 (define (module-obarray-set! ob key val)
1457 ((if (symbol? key) hashq-set! hash-set!) ob key val))
1459 (define (module-obarray-remove! ob key)
1460 ((if (symbol? key) hashq-remove! hash-remove!) ob key))
1462 ;; module-symbol-locally-interned? module symbol
1464 ;; is a symbol interned (not neccessarily defined) locally in a given module
1465 ;; or its uses? Interned symbols shadow inherited bindings even if
1466 ;; they are not themselves bound to a defined value.
1468 (define (module-symbol-locally-interned? m v)
1469 (not (not (module-obarray-get-handle (module-obarray m) v))))
1471 ;; module-symbol-interned? module symbol
1473 ;; is a symbol interned (not neccessarily defined) anywhere in a given module
1474 ;; or its uses? Interned symbols shadow inherited bindings even if
1475 ;; they are not themselves bound to a defined value.
1477 (define (module-symbol-interned? m v)
1478 (module-search module-symbol-locally-interned? m v))
1481 ;;; {Mapping modules x symbols --> variables}
1484 ;; module-local-variable module symbol
1485 ;; return the local variable associated with a MODULE and SYMBOL.
1487 ;;; This function is very important. It is the only function that can
1488 ;;; return a variable from a module other than the mutators that store
1489 ;;; new variables in modules. Therefore, this function is the location
1490 ;;; of the "lazy binder" hack.
1492 ;;; If symbol is defined in MODULE, and if the definition binds symbol
1493 ;;; to a variable, return that variable object.
1495 ;;; If the symbols is not found at first, but the module has a lazy binder,
1496 ;;; then try the binder.
1498 ;;; If the symbol is not found at all, return #f.
1500 ;;; (This is now written in C, see `modules.c'.)
1503 ;;; {Mapping modules x symbols --> bindings}
1505 ;;; These are similar to the mapping to variables, except that the
1506 ;;; variable is dereferenced.
1509 ;; module-symbol-binding module symbol opt-value
1511 ;; return the binding of a variable specified by name within
1512 ;; a given module, signalling an error if the variable is unbound.
1513 ;; If the OPT-VALUE is passed, then instead of signalling an error,
1514 ;; return OPT-VALUE.
1516 (define (module-symbol-local-binding m v . opt-val)
1517 (let ((var (module-local-variable m v)))
1518 (if (and var (variable-bound? var))
1520 (if (not (null? opt-val))
1522 (error "Locally unbound variable." v)))))
1524 ;; module-symbol-binding module symbol opt-value
1526 ;; return the binding of a variable specified by name within
1527 ;; a given module, signalling an error if the variable is unbound.
1528 ;; If the OPT-VALUE is passed, then instead of signalling an error,
1529 ;; return OPT-VALUE.
1531 (define (module-symbol-binding m v . opt-val)
1532 (let ((var (module-variable m v)))
1533 (if (and var (variable-bound? var))
1535 (if (not (null? opt-val))
1537 (error "Unbound variable." v)))))
1542 ;;; {Adding Variables to Modules}
1545 ;; module-make-local-var! module symbol
1547 ;; ensure a variable for V in the local namespace of M.
1548 ;; If no variable was already there, then create a new and uninitialzied
1551 ;; This function is used in modules.c.
1553 (define (module-make-local-var! m v)
1554 (or (let ((b (module-obarray-ref (module-obarray m) v)))
1557 ;; Mark as modified since this function is called when
1558 ;; the standard eval closure defines a binding
1562 ;; Create a new local variable.
1563 (let ((local-var (make-undefined-variable)))
1564 (module-add! m v local-var)
1567 ;; module-ensure-local-variable! module symbol
1569 ;; Ensure that there is a local variable in MODULE for SYMBOL. If
1570 ;; there is no binding for SYMBOL, create a new uninitialized
1571 ;; variable. Return the local variable.
1573 (define (module-ensure-local-variable! module symbol)
1574 (or (module-local-variable module symbol)
1575 (let ((var (make-undefined-variable)))
1576 (module-add! module symbol var)
1579 ;; module-add! module symbol var
1581 ;; ensure a particular variable for V in the local namespace of M.
1583 (define (module-add! m v var)
1584 (if (not (variable? var))
1585 (error "Bad variable to module-add!" var))
1586 (module-obarray-set! (module-obarray m) v var)
1587 (module-modified m))
1591 ;; make sure that a symbol is undefined in the local namespace of M.
1593 (define (module-remove! m v)
1594 (module-obarray-remove! (module-obarray m) v)
1595 (module-modified m))
1597 (define (module-clear! m)
1598 (hash-clear! (module-obarray m))
1599 (module-modified m))
1601 ;; MODULE-FOR-EACH -- exported
1603 ;; Call PROC on each symbol in MODULE, with arguments of (SYMBOL VARIABLE).
1605 (define (module-for-each proc module)
1606 (hash-for-each proc (module-obarray module)))
1608 (define (module-map proc module)
1609 (hash-map->list proc (module-obarray module)))
1613 ;;; {Low Level Bootstrapping}
1618 ;; A root module uses the pre-modules-obarray as its obarray. This
1619 ;; special obarray accumulates all bindings that have been established
1620 ;; before the module system is fully booted.
1622 ;; (The obarray continues to be used by code that has been closed over
1623 ;; before the module system has been booted.)
1625 (define (make-root-module)
1626 (let ((m (make-module 0)))
1627 (set-module-obarray! m (%get-pre-modules-obarray))
1632 ;; The root interface is a module that uses the same obarray as the
1633 ;; root module. It does not allow new definitions, tho.
1635 (define (make-scm-module)
1636 (let ((m (make-module 0)))
1637 (set-module-obarray! m (%get-pre-modules-obarray))
1638 (set-module-eval-closure! m (standard-interface-eval-closure m))
1644 ;;; {Module-based Loading}
1647 (define (save-module-excursion thunk)
1648 (let ((inner-module (current-module))
1650 (dynamic-wind (lambda ()
1651 (set! outer-module (current-module))
1652 (set-current-module inner-module)
1653 (set! inner-module #f))
1656 (set! inner-module (current-module))
1657 (set-current-module outer-module)
1658 (set! outer-module #f)))))
1660 (define basic-load load)
1662 (define (load-module filename . reader)
1663 (save-module-excursion
1665 (let ((oldname (and (current-load-port)
1666 (port-filename (current-load-port)))))
1669 (> (string-length filename) 0)
1670 (not (char=? (string-ref filename 0) #\/))
1671 (not (string=? (dirname oldname) ".")))
1672 (string-append (dirname oldname) "/" filename)
1679 ;;; {MODULE-REF -- exported}
1682 ;; Returns the value of a variable called NAME in MODULE or any of its
1683 ;; used modules. If there is no such variable, then if the optional third
1684 ;; argument DEFAULT is present, it is returned; otherwise an error is signaled.
1686 (define (module-ref module name . rest)
1687 (let ((variable (module-variable module name)))
1688 (if (and variable (variable-bound? variable))
1689 (variable-ref variable)
1691 (error "No variable named" name 'in module)
1692 (car rest) ; default value
1695 ;; MODULE-SET! -- exported
1697 ;; Sets the variable called NAME in MODULE (or in a module that MODULE uses)
1698 ;; to VALUE; if there is no such variable, an error is signaled.
1700 (define (module-set! module name value)
1701 (let ((variable (module-variable module name)))
1703 (variable-set! variable value)
1704 (error "No variable named" name 'in module))))
1706 ;; MODULE-DEFINE! -- exported
1708 ;; Sets the variable called NAME in MODULE to VALUE; if there is no such
1709 ;; variable, it is added first.
1711 (define (module-define! module name value)
1712 (let ((variable (module-local-variable module name)))
1715 (variable-set! variable value)
1716 (module-modified module))
1717 (let ((variable (make-variable value)))
1718 (module-add! module name variable)))))
1720 ;; MODULE-DEFINED? -- exported
1722 ;; Return #t iff NAME is defined in MODULE (or in a module that MODULE
1725 (define (module-defined? module name)
1726 (let ((variable (module-variable module name)))
1727 (and variable (variable-bound? variable))))
1729 ;; MODULE-USE! module interface
1731 ;; Add INTERFACE to the list of interfaces used by MODULE.
1733 (define (module-use! module interface)
1734 (if (not (or (eq? module interface)
1735 (memq interface (module-uses module))))
1737 ;; Newly used modules must be appended rather than consed, so that
1738 ;; `module-variable' traverses the use list starting from the first
1740 (set-module-uses! module
1741 (append (filter (lambda (m)
1743 (equal? (module-name m)
1744 (module-name interface))))
1745 (module-uses module))
1748 (module-modified module))))
1750 ;; MODULE-USE-INTERFACES! module interfaces
1752 ;; Same as MODULE-USE! but add multiple interfaces and check for duplicates
1754 (define (module-use-interfaces! module interfaces)
1755 (set-module-uses! module
1756 (append (module-uses module) interfaces))
1757 (module-modified module))
1761 ;;; {Recursive Namespaces}
1763 ;;; A hierarchical namespace emerges if we consider some module to be
1764 ;;; root, and variables bound to modules as nested namespaces.
1766 ;;; The routines in this file manage variable names in hierarchical namespace.
1767 ;;; Each variable name is a list of elements, looked up in successively nested
1770 ;;; (nested-ref some-root-module '(foo bar baz))
1771 ;;; => <value of a variable named baz in the module bound to bar in
1772 ;;; the module bound to foo in some-root-module>
1777 ;;; ;; a-root is a module
1778 ;;; ;; name is a list of symbols
1780 ;;; nested-ref a-root name
1781 ;;; nested-set! a-root name val
1782 ;;; nested-define! a-root name val
1783 ;;; nested-remove! a-root name
1786 ;;; (current-module) is a natural choice for a-root so for convenience there are
1789 ;;; local-ref name == nested-ref (current-module) name
1790 ;;; local-set! name val == nested-set! (current-module) name val
1791 ;;; local-define! name val == nested-define! (current-module) name val
1792 ;;; local-remove! name == nested-remove! (current-module) name
1796 (define (nested-ref root names)
1797 (let loop ((cur root)
1801 ((not (module? cur)) #f)
1802 (else (loop (module-ref cur (car elts) #f) (cdr elts))))))
1804 (define (nested-set! root names val)
1805 (let loop ((cur root)
1807 (if (null? (cdr elts))
1808 (module-set! cur (car elts) val)
1809 (loop (module-ref cur (car elts)) (cdr elts)))))
1811 (define (nested-define! root names val)
1812 (let loop ((cur root)
1814 (if (null? (cdr elts))
1815 (module-define! cur (car elts) val)
1816 (loop (module-ref cur (car elts)) (cdr elts)))))
1818 (define (nested-remove! root names)
1819 (let loop ((cur root)
1821 (if (null? (cdr elts))
1822 (module-remove! cur (car elts))
1823 (loop (module-ref cur (car elts)) (cdr elts)))))
1825 (define (local-ref names) (nested-ref (current-module) names))
1826 (define (local-set! names val) (nested-set! (current-module) names val))
1827 (define (local-define names val) (nested-define! (current-module) names val))
1828 (define (local-remove names) (nested-remove! (current-module) names))
1833 ;;; {The (%app) module}
1835 ;;; The root of conventionally named objects not directly in the top level.
1838 ;;; (%app modules guile)
1840 ;;; The directory of all modules and the standard root module.
1843 ;; module-public-interface is defined in C.
1844 (define (set-module-public-interface! m i)
1845 (module-define! m '%module-public-interface i))
1846 (define (set-system-module! m s)
1847 (set-procedure-property! (module-eval-closure m) 'system-module s))
1848 (define the-root-module (make-root-module))
1849 (define the-scm-module (make-scm-module))
1850 (set-module-public-interface! the-root-module the-scm-module)
1851 (set-module-name! the-root-module '(guile))
1852 (set-module-name! the-scm-module '(guile))
1853 (set-module-kind! the-scm-module 'interface)
1854 (set-system-module! the-root-module #t)
1855 (set-system-module! the-scm-module #t)
1857 ;; NOTE: This binding is used in libguile/modules.c.
1859 (define (make-modules-in module name)
1863 (let* ((var (module-local-variable module (car name)))
1864 (val (and var (variable-bound? var) (variable-ref var))))
1867 (let ((m (make-module 31)))
1868 (set-module-kind! m 'directory)
1869 (set-module-name! m (append (or (module-name module) '())
1871 (module-define! module (car name) m)
1875 (define (beautify-user-module! module)
1876 (let ((interface (module-public-interface module)))
1877 (if (or (not interface)
1878 (eq? interface module))
1879 (let ((interface (make-module 31)))
1880 (set-module-name! interface (module-name module))
1881 (set-module-kind! interface 'interface)
1882 (set-module-public-interface! module interface))))
1883 (if (and (not (memq the-scm-module (module-uses module)))
1884 (not (eq? module the-root-module)))
1885 ;; Import the default set of bindings (from the SCM module) in MODULE.
1886 (module-use! module the-scm-module)))
1888 ;; NOTE: This binding is used in libguile/modules.c.
1890 (define resolve-module
1891 (let ((the-root-module the-root-module))
1892 (lambda (name . maybe-autoload)
1893 (if (equal? name '(guile))
1895 (let ((full-name (append '(%app modules) name)))
1896 (let ((already (nested-ref the-root-module full-name))
1897 (autoload (or (null? maybe-autoload) (car maybe-autoload))))
1899 ((and already (module? already)
1900 (or (not autoload) (module-public-interface already)))
1901 ;; A hit, a palpable hit.
1904 ;; Try to autoload the module, and recurse.
1905 (try-load-module name)
1906 (resolve-module name #f))
1908 ;; A module is not bound (but maybe something else is),
1909 ;; we're not autoloading -- here's the weird semantics,
1910 ;; we create an empty module.
1911 (make-modules-in the-root-module full-name)))))))))
1913 ;; Cheat. These bindings are needed by modules.c, but we don't want
1914 ;; to move their real definition here because that would be unnatural.
1916 (define try-module-autoload #f)
1917 (define process-define-module #f)
1918 (define process-use-modules #f)
1919 (define module-export! #f)
1920 (define default-duplicate-binding-procedures #f)
1922 (define %app (make-module 31))
1923 (define app %app) ;; for backwards compatability
1925 (local-define '(%app modules) (make-module 31))
1926 (local-define '(%app modules guile) the-root-module)
1928 ;; This boots the module system. All bindings needed by modules.c
1929 ;; must have been defined by now.
1931 (set-current-module the-root-module)
1932 ;; definition deferred for syncase's benefit
1933 (define module-name (record-accessor module-type 'name))
1935 ;; (define-special-value '(%app modules new-ws) (lambda () (make-scm-module)))
1937 (define (try-load-module name)
1938 (try-module-autoload name))
1940 (define (purify-module! module)
1941 "Removes bindings in MODULE which are inherited from the (guile) module."
1942 (let ((use-list (module-uses module)))
1943 (if (and (pair? use-list)
1944 (eq? (car (last-pair use-list)) the-scm-module))
1945 (set-module-uses! module (reverse (cdr (reverse use-list)))))))
1947 ;; Return a module that is an interface to the module designated by
1950 ;; `resolve-interface' takes four keyword arguments:
1952 ;; #:select SELECTION
1954 ;; SELECTION is a list of binding-specs to be imported; A binding-spec
1955 ;; is either a symbol or a pair of symbols (ORIG . SEEN), where ORIG
1956 ;; is the name in the used module and SEEN is the name in the using
1957 ;; module. Note that SEEN is also passed through RENAMER, below. The
1958 ;; default is to select all bindings. If you specify no selection but
1959 ;; a renamer, only the bindings that already exist in the used module
1960 ;; are made available in the interface. Bindings that are added later
1961 ;; are not picked up.
1965 ;; BINDINGS is a list of bindings which should not be imported.
1969 ;; PREFIX is a symbol that will be appended to each exported name.
1970 ;; The default is to not perform any renaming.
1972 ;; #:renamer RENAMER
1974 ;; RENAMER is a procedure that takes a symbol and returns its new
1975 ;; name. The default is not perform any renaming.
1977 ;; Signal "no code for module" error if module name is not resolvable
1978 ;; or its public interface is not available. Signal "no binding"
1979 ;; error if selected binding does not exist in the used module.
1981 (define (resolve-interface name . args)
1983 (define (get-keyword-arg args kw def)
1984 (cond ((memq kw args)
1986 (if (null? (cdr kw-arg))
1987 (error "keyword without value: " kw))
1992 (let* ((select (get-keyword-arg args #:select #f))
1993 (hide (get-keyword-arg args #:hide '()))
1994 (renamer (or (get-keyword-arg args #:renamer #f)
1995 (let ((prefix (get-keyword-arg args #:prefix #f)))
1996 (and prefix (symbol-prefix-proc prefix)))
1998 (module (resolve-module name))
1999 (public-i (and module (module-public-interface module))))
2000 (and (or (not module) (not public-i))
2001 (error "no code for module" name))
2002 (if (and (not select) (null? hide) (eq? renamer identity))
2004 (let ((selection (or select (module-map (lambda (sym var) sym)
2006 (custom-i (make-module 31)))
2007 (set-module-kind! custom-i 'custom-interface)
2008 (set-module-name! custom-i name)
2009 ;; XXX - should use a lazy binder so that changes to the
2010 ;; used module are picked up automatically.
2011 (for-each (lambda (bspec)
2012 (let* ((direct? (symbol? bspec))
2013 (orig (if direct? bspec (car bspec)))
2014 (seen (if direct? bspec (cdr bspec)))
2015 (var (or (module-local-variable public-i orig)
2016 (module-local-variable module orig)
2018 ;; fixme: format manually for now
2020 #f "no binding `~A' in module ~A"
2022 (if (memq orig hide)
2023 (set! hide (delq! orig hide))
2024 (module-add! custom-i
2028 ;; Check that we are not hiding bindings which don't exist
2029 (for-each (lambda (binding)
2030 (if (not (module-local-variable public-i binding))
2033 #f "no binding `~A' to hide in module ~A"
2038 (define (symbol-prefix-proc prefix)
2040 (symbol-append prefix symbol)))
2042 ;; This function is called from "modules.c". If you change it, be
2043 ;; sure to update "modules.c" as well.
2045 (define (process-define-module args)
2046 (let* ((module-id (car args))
2047 (module (resolve-module module-id #f))
2049 (unrecognized (lambda (arg)
2050 (error "unrecognized define-module argument" arg))))
2051 (beautify-user-module! module)
2052 (let loop ((kws kws)
2053 (reversed-interfaces '())
2060 (call-with-deferred-observers
2062 (module-use-interfaces! module (reverse reversed-interfaces))
2063 (module-export! module exports)
2064 (module-replace! module replacements)
2065 (module-re-export! module re-exports)
2066 (if (not (null? autoloads))
2067 (apply module-autoload! module autoloads))))
2069 ((#:use-module #:use-syntax)
2070 (or (pair? (cdr kws))
2073 ((equal? (caadr kws) '(ice-9 syncase))
2074 (issue-deprecation-warning
2075 "(ice-9 syncase) is deprecated. Support for syntax-case is now in Guile core.")
2083 (let* ((interface-args (cadr kws))
2084 (interface (apply resolve-interface interface-args)))
2085 (and (eq? (car kws) #:use-syntax)
2086 (or (symbol? (caar interface-args))
2087 (error "invalid module name for use-syntax"
2088 (car interface-args)))
2089 (set-module-transformer!
2091 (module-ref interface
2092 (car (last-pair (car interface-args)))
2095 (cons interface reversed-interfaces)
2101 (or (and (pair? (cdr kws)) (pair? (cddr kws)))
2108 (let ((name (cadr kws))
2109 (bindings (caddr kws)))
2110 (cons* name bindings autoloads))))
2112 (set-system-module! module #t)
2113 (loop (cdr kws) reversed-interfaces exports re-exports
2114 replacements autoloads))
2116 (purify-module! module)
2117 (loop (cdr kws) reversed-interfaces exports re-exports
2118 replacements autoloads))
2120 (if (not (pair? (cdr kws)))
2122 (set-module-duplicates-handlers!
2124 (lookup-duplicates-handlers (cadr kws)))
2125 (loop (cddr kws) reversed-interfaces exports re-exports
2126 replacements autoloads))
2127 ((#:export #:export-syntax)
2128 (or (pair? (cdr kws))
2132 (append (cadr kws) exports)
2136 ((#:re-export #:re-export-syntax)
2137 (or (pair? (cdr kws))
2142 (append (cadr kws) re-exports)
2145 ((#:replace #:replace-syntax)
2146 (or (pair? (cdr kws))
2152 (append (cadr kws) replacements)
2155 (unrecognized kws)))))
2156 (run-hook module-defined-hook module)
2159 ;; `module-defined-hook' is a hook that is run whenever a new module
2160 ;; is defined. Its members are called with one argument, the new
2162 (define module-defined-hook (make-hook 1))
2169 (define (make-autoload-interface module name bindings)
2170 (let ((b (lambda (a sym definep)
2171 (and (memq sym bindings)
2172 (let ((i (module-public-interface (resolve-module name))))
2174 (error "missing interface for module" name))
2175 (let ((autoload (memq a (module-uses module))))
2176 ;; Replace autoload-interface with actual interface if
2177 ;; that has not happened yet.
2178 (if (pair? autoload)
2179 (set-car! autoload i)))
2180 (module-local-variable i sym))))))
2181 (module-constructor (make-hash-table 0) '() b #f #f name 'autoload #f
2182 (make-hash-table 0) '() (make-weak-value-hash-table 31))))
2184 (define (module-autoload! module . args)
2185 "Have @var{module} automatically load the module named @var{name} when one
2186 of the symbols listed in @var{bindings} is looked up. @var{args} should be a
2187 list of module-name/binding-list pairs, e.g., as in @code{(module-autoload!
2188 module '(ice-9 q) '(make-q q-length))}."
2189 (let loop ((args args))
2193 (error "invalid name+binding autoload list" args))
2195 (let ((name (car args))
2196 (bindings (cadr args)))
2197 (module-use! module (make-autoload-interface module
2199 (loop (cddr args)))))))
2204 ;;; {Autoloading modules}
2207 (define autoloads-in-progress '())
2209 ;; This function is called from "modules.c". If you change it, be
2210 ;; sure to update "modules.c" as well.
2212 (define (try-module-autoload module-name)
2213 (let* ((reverse-name (reverse module-name))
2214 (name (symbol->string (car reverse-name)))
2215 (dir-hint-module-name (reverse (cdr reverse-name)))
2216 (dir-hint (apply string-append
2218 (string-append (symbol->string elt) "/"))
2219 dir-hint-module-name))))
2220 (resolve-module dir-hint-module-name #f)
2221 (and (not (autoload-done-or-in-progress? dir-hint name))
2223 (define (load-file proc file)
2224 (save-module-excursion (lambda () (proc file)))
2227 (lambda () (autoload-in-progress! dir-hint name))
2229 (let ((file (in-vicinity dir-hint name)))
2230 (let ((compiled (and load-compiled
2232 (string-append file ".go"))))
2233 (source (%search-load-path file)))
2236 (< (stat:mtime (stat compiled))
2237 (stat:mtime (stat source)))))
2239 (warn "source file" source "newer than" compiled))
2240 (with-fluid* current-reader #f
2241 (lambda () (load-file primitive-load source))))
2243 (load-file load-compiled compiled))))))
2244 (lambda () (set-autoloaded! dir-hint name didit)))
2249 ;;; {Dynamic linking of modules}
2252 (define autoloads-done '((guile . guile)))
2254 (define (autoload-done-or-in-progress? p m)
2255 (let ((n (cons p m)))
2256 (->bool (or (member n autoloads-done)
2257 (member n autoloads-in-progress)))))
2259 (define (autoload-done! p m)
2260 (let ((n (cons p m)))
2261 (set! autoloads-in-progress
2262 (delete! n autoloads-in-progress))
2263 (or (member n autoloads-done)
2264 (set! autoloads-done (cons n autoloads-done)))))
2266 (define (autoload-in-progress! p m)
2267 (let ((n (cons p m)))
2268 (set! autoloads-done
2269 (delete! n autoloads-done))
2270 (set! autoloads-in-progress (cons n autoloads-in-progress))))
2272 (define (set-autoloaded! p m done?)
2274 (autoload-done! p m)
2275 (let ((n (cons p m)))
2276 (set! autoloads-done (delete! n autoloads-done))
2277 (set! autoloads-in-progress (delete! n autoloads-in-progress)))))
2281 ;;; {Run-time options}
2284 (defmacro define-option-interface (option-group)
2285 (let* ((option-name car)
2287 (option-documentation caddr)
2289 ;; Below follow the macros defining the run-time option interfaces.
2291 (make-options (lambda (interface)
2293 (cond ((null? args) (,interface))
2295 (,interface (car args)) (,interface))
2298 (display (option-name option))
2299 (if (< (string-length
2300 (symbol->string (option-name option)))
2304 (display (option-value option))
2306 (display (option-documentation option))
2308 (,interface #t)))))))
2310 (make-enable (lambda (interface)
2312 (,interface (append flags (,interface)))
2315 (make-disable (lambda (interface)
2317 (let ((options (,interface)))
2318 (for-each (lambda (flag)
2319 (set! options (delq! flag options)))
2321 (,interface options)
2323 (let* ((interface (car option-group))
2324 (options/enable/disable (cadr option-group)))
2326 (define ,(car options/enable/disable)
2327 ,(make-options interface))
2328 (define ,(cadr options/enable/disable)
2329 ,(make-enable interface))
2330 (define ,(caddr options/enable/disable)
2331 ,(make-disable interface))
2332 (defmacro ,(caaddr option-group) (opt val)
2333 `(,',(car options/enable/disable)
2334 (append (,',(car options/enable/disable))
2335 (list ',opt ,val))))))))
2337 (define-option-interface
2338 (eval-options-interface
2339 (eval-options eval-enable eval-disable)
2342 (define-option-interface
2343 (debug-options-interface
2344 (debug-options debug-enable debug-disable)
2347 (define-option-interface
2348 (evaluator-traps-interface
2349 (traps trap-enable trap-disable)
2352 (define-option-interface
2353 (read-options-interface
2354 (read-options read-enable read-disable)
2357 (define-option-interface
2358 (print-options-interface
2359 (print-options print-enable print-disable)
2367 (define (repl read evaler print)
2368 (let loop ((source (read (current-input-port))))
2369 (print (evaler source))
2370 (loop (read (current-input-port)))))
2372 ;; A provisional repl that acts like the SCM repl:
2374 (define scm-repl-silent #f)
2375 (define (assert-repl-silence v) (set! scm-repl-silent v))
2377 (define *unspecified* (if #f #f))
2378 (define (unspecified? v) (eq? v *unspecified*))
2380 (define scm-repl-print-unspecified #f)
2381 (define (assert-repl-print-unspecified v) (set! scm-repl-print-unspecified v))
2383 (define scm-repl-verbose #f)
2384 (define (assert-repl-verbosity v) (set! scm-repl-verbose v))
2386 (define scm-repl-prompt "guile> ")
2388 (define (set-repl-prompt! v) (set! scm-repl-prompt v))
2390 (define (default-pre-unwind-handler key . args)
2391 (save-stack pre-unwind-handler-dispatch)
2392 (apply throw key args))
2394 (define (pre-unwind-handler-dispatch key . args)
2395 (apply default-pre-unwind-handler key args))
2397 (define abort-hook (make-hook))
2399 ;; these definitions are used if running a script.
2400 ;; otherwise redefined in error-catching-loop.
2401 (define (set-batch-mode?! arg) #t)
2402 (define (batch-mode?) #t)
2404 (define (error-catching-loop thunk)
2407 (define (loop first)
2412 (call-with-unblocked-asyncs
2418 ;; This line is needed because mark
2419 ;; doesn't do closures quite right.
2420 ;; Unreferenced locals should be
2423 (let loop ((v (thunk)))
2427 (lambda (key . args)
2434 (apply throw 'switch-repl args))
2437 ;; This is one of the closures that require
2438 ;; (set! first #f) above
2441 (run-hook abort-hook)
2442 (force-output (current-output-port))
2443 (display "ABORT: " (current-error-port))
2444 (write args (current-error-port))
2445 (newline (current-error-port))
2449 (not has-shown-debugger-hint?)
2450 (not (memq 'backtrace
2451 (debug-options-interface)))
2452 (stack? (fluid-ref the-last-stack)))
2454 (newline (current-error-port))
2456 "Type \"(backtrace)\" to get more information or \"(debug)\" to enter the debugger.\n"
2457 (current-error-port))
2458 (set! has-shown-debugger-hint? #t)))
2459 (force-output (current-error-port)))
2461 (primitive-exit 1)))
2462 (set! stack-saved? #f)))
2465 ;; This is the other cons-leak closure...
2467 (cond ((= (length args) 4)
2468 (apply handle-system-error key args))
2470 (apply bad-throw key args)))))))
2472 ;; Note that having just `pre-unwind-handler-dispatch'
2473 ;; here is connected with the mechanism that
2474 ;; produces a nice backtrace upon error. If, for
2475 ;; example, this is replaced with (lambda args
2476 ;; (apply pre-unwind-handler-dispatch args)), the stack
2477 ;; cutting (in save-stack) goes wrong and ends up
2478 ;; saving no stack at all, so there is no
2480 pre-unwind-handler-dispatch)))
2482 (if next (loop next) status)))
2483 (set! set-batch-mode?! (lambda (arg)
2485 (set! interactive #f)
2488 (error "sorry, not implemented")))))
2489 (set! batch-mode? (lambda () (not interactive)))
2490 (call-with-blocked-asyncs
2491 (lambda () (loop (lambda () #t))))))
2493 ;;(define the-last-stack (make-fluid)) Defined by scm_init_backtrace ()
2494 (define before-signal-stack (make-fluid))
2495 (define stack-saved? #f)
2497 (define (save-stack . narrowing)
2499 (cond ((not (memq 'debug (debug-options-interface)))
2500 (fluid-set! the-last-stack #f)
2501 (set! stack-saved? #t))
2507 (apply make-stack #t save-stack primitive-eval #t 0 narrowing))
2509 (apply make-stack #t save-stack 0 #t 0 narrowing))
2511 (apply make-stack #t save-stack tk-stack-mark #t 0 narrowing))
2513 (apply make-stack #t save-stack 0 1 narrowing))
2515 (let ((id (stack-id #t)))
2516 (and (procedure? id)
2517 (apply make-stack #t save-stack id #t 0 narrowing))))))
2518 (set! stack-saved? #t)))))
2520 (define before-error-hook (make-hook))
2521 (define after-error-hook (make-hook))
2522 (define before-backtrace-hook (make-hook))
2523 (define after-backtrace-hook (make-hook))
2525 (define has-shown-debugger-hint? #f)
2527 (define (handle-system-error key . args)
2528 (let ((cep (current-error-port)))
2529 (cond ((not (stack? (fluid-ref the-last-stack))))
2530 ((memq 'backtrace (debug-options-interface))
2531 (let ((highlights (if (or (eq? key 'wrong-type-arg)
2532 (eq? key 'out-of-range))
2535 (run-hook before-backtrace-hook)
2537 (display "Backtrace:\n")
2538 (display-backtrace (fluid-ref the-last-stack) cep
2541 (run-hook after-backtrace-hook))))
2542 (run-hook before-error-hook)
2543 (apply display-error (fluid-ref the-last-stack) cep args)
2544 (run-hook after-error-hook)
2546 (throw 'abort key)))
2548 (define (quit . args)
2549 (apply throw 'quit args))
2553 ;;(define has-shown-backtrace-hint? #f) Defined by scm_init_backtrace ()
2555 ;; Replaced by C code:
2556 ;;(define (backtrace)
2557 ;; (if (fluid-ref the-last-stack)
2560 ;; (display-backtrace (fluid-ref the-last-stack) (current-output-port))
2562 ;; (if (and (not has-shown-backtrace-hint?)
2563 ;; (not (memq 'backtrace (debug-options-interface))))
2566 ;;"Type \"(debug-enable 'backtrace)\" if you would like a backtrace
2567 ;;automatically if an error occurs in the future.\n")
2568 ;; (set! has-shown-backtrace-hint? #t))))
2569 ;; (display "No backtrace available.\n")))
2571 (define (error-catching-repl r e p)
2572 (error-catching-loop
2574 (call-with-values (lambda () (e (r)))
2575 (lambda the-values (for-each p the-values))))))
2577 (define (gc-run-time)
2578 (cdr (assq 'gc-time-taken (gc-stats))))
2580 (define before-read-hook (make-hook))
2581 (define after-read-hook (make-hook))
2582 (define before-eval-hook (make-hook 1))
2583 (define after-eval-hook (make-hook 1))
2584 (define before-print-hook (make-hook 1))
2585 (define after-print-hook (make-hook 1))
2587 ;;; The default repl-reader function. We may override this if we've
2588 ;;; the readline library.
2591 (display (if (string? prompt) prompt (prompt)))
2593 (run-hook before-read-hook)
2594 ((or (fluid-ref current-reader) read) (current-input-port))))
2596 (define (scm-style-repl)
2601 (repl-report-start-timing (lambda ()
2602 (set! start-gc-rt (gc-run-time))
2603 (set! start-rt (get-internal-run-time))))
2604 (repl-report (lambda ()
2606 (display (inexact->exact
2607 (* 1000 (/ (- (get-internal-run-time) start-rt)
2608 internal-time-units-per-second))))
2610 (display (inexact->exact
2611 (* 1000 (/ (- (gc-run-time) start-gc-rt)
2612 internal-time-units-per-second))))
2613 (display " msec in gc)\n")))
2615 (consume-trailing-whitespace
2617 (let ((ch (peek-char)))
2620 ((or (char=? ch #\space) (char=? ch #\tab))
2622 (consume-trailing-whitespace))
2623 ((char=? ch #\newline)
2627 (let ((prompt (cond ((string? scm-repl-prompt)
2629 ((thunk? scm-repl-prompt)
2631 (scm-repl-prompt "> ")
2633 (repl-reader prompt))))
2635 ;; As described in R4RS, the READ procedure updates the
2636 ;; port to point to the first character past the end of
2637 ;; the external representation of the object. This
2638 ;; means that it doesn't consume the newline typically
2639 ;; found after an expression. This means that, when
2640 ;; debugging Guile with GDB, GDB gets the newline, which
2641 ;; it often interprets as a "continue" command, making
2642 ;; breakpoints kind of useless. So, consume any
2643 ;; trailing newline here, as well as any whitespace
2645 ;; But not if EOF, for control-D.
2646 (if (not (eof-object? val))
2647 (consume-trailing-whitespace))
2648 (run-hook after-read-hook)
2649 (if (eof-object? val)
2651 (repl-report-start-timing)
2652 (if scm-repl-verbose
2655 (display ";;; EOF -- quitting")
2660 (-eval (lambda (sourc)
2661 (repl-report-start-timing)
2662 (run-hook before-eval-hook sourc)
2663 (let ((val (start-stack 'repl-stack
2664 ;; If you change this procedure
2665 ;; (primitive-eval), please also
2666 ;; modify the repl-stack case in
2667 ;; save-stack so that stack cutting
2668 ;; continues to work.
2669 (primitive-eval sourc))))
2670 (run-hook after-eval-hook sourc)
2674 (-print (let ((maybe-print (lambda (result)
2675 (if (or scm-repl-print-unspecified
2676 (not (unspecified? result)))
2681 (if (not scm-repl-silent)
2683 (run-hook before-print-hook result)
2684 (maybe-print result)
2685 (run-hook after-print-hook result)
2686 (if scm-repl-verbose
2690 (-quit (lambda (args)
2691 (if scm-repl-verbose
2693 (display ";;; QUIT executed, repl exitting")
2699 (if scm-repl-verbose
2701 (display ";;; ABORT executed.")
2704 (repl -read -eval -print))))
2706 (let ((status (error-catching-repl -read
2714 ;;; {IOTA functions: generating lists of numbers}
2718 (let loop ((count (1- n)) (result '()))
2719 (if (< count 0) result
2720 (loop (1- count) (cons count result)))))
2726 ;;; Similar to `begin' but returns a list of the results of all constituent
2727 ;;; forms instead of the result of the last form.
2728 ;;; (The definition relies on the current left-to-right
2729 ;;; order of evaluation of operands in applications.)
2732 (defmacro collect forms
2740 ;; with-fluids is a convenience wrapper for the builtin procedure
2741 ;; `with-fluids*'. The syntax is just like `let':
2743 ;; (with-fluids ((fluid val)
2747 (defmacro with-fluids (bindings . body)
2748 (let ((fluids (map car bindings))
2749 (values (map cadr bindings)))
2750 (if (and (= (length fluids) 1) (= (length values) 1))
2751 `(with-fluid* ,(car fluids) ,(car values) (lambda () ,@body))
2752 `(with-fluids* (list ,@fluids) (list ,@values)
2753 (lambda () ,@body)))))
2757 ;;; with `continue' and `break'.
2760 ;; The inner `do' loop avoids re-establishing a catch every iteration,
2761 ;; that's only necessary if continue is actually used. A new key is
2762 ;; generated every time, so break and continue apply to their originating
2763 ;; `while' even when recursing.
2765 ;; FIXME: This macro is unintentionally unhygienic with respect to let,
2766 ;; make-symbol, do, throw, catch, lambda, and not.
2768 (define-macro (while cond . body)
2769 (let ((keyvar (make-symbol "while-keyvar")))
2770 `(let ((,keyvar (make-symbol "while-key")))
2774 (let ((break (lambda () (throw ,keyvar #t)))
2775 (continue (lambda () (throw ,keyvar #f))))
2786 ;;; {Module System Macros}
2789 ;; Return a list of expressions that evaluate to the appropriate
2790 ;; arguments for resolve-interface according to SPEC.
2794 (if (memq 'prefix (read-options))
2795 (error "boot-9 must be compiled with #:kw, not :kw")))
2797 (define (compile-interface-spec spec)
2798 (define (make-keyarg sym key quote?)
2799 (cond ((or (memq sym spec)
2803 (list key (list 'quote (cadr rest)))
2804 (list key (cadr rest)))))
2807 (define (map-apply func list)
2808 (map (lambda (args) (apply func args)) list))
2811 '((:select #:select #t)
2813 (:prefix #:prefix #t)
2814 (:renamer #:renamer #f)))
2815 (if (not (pair? (car spec)))
2818 ,@(apply append (map-apply make-keyarg keys)))))
2820 (define (keyword-like-symbol->keyword sym)
2821 (symbol->keyword (string->symbol (substring (symbol->string sym) 1))))
2823 (define (compile-define-module-args args)
2824 ;; Just quote everything except #:use-module and #:use-syntax. We
2825 ;; need to know about all arguments regardless since we want to turn
2826 ;; symbols that look like keywords into real keywords, and the
2827 ;; keyword args in a define-module form are not regular
2828 ;; (i.e. no-backtrace doesn't take a value).
2829 (let loop ((compiled-args `((quote ,(car args))))
2832 (reverse! compiled-args))
2833 ;; symbol in keyword position
2834 ((symbol? (car args))
2836 (cons (keyword-like-symbol->keyword (car args)) (cdr args))))
2837 ((memq (car args) '(#:no-backtrace #:pure))
2838 (loop (cons (car args) compiled-args)
2841 (error "keyword without value:" (car args)))
2842 ((memq (car args) '(#:use-module #:use-syntax))
2843 (loop (cons* `(list ,@(compile-interface-spec (cadr args)))
2847 ((eq? (car args) #:autoload)
2848 (loop (cons* `(quote ,(caddr args))
2849 `(quote ,(cadr args))
2854 (loop (cons* `(quote ,(cadr args))
2859 (defmacro define-module args
2862 (let ((m (process-define-module
2863 (list ,@(compile-define-module-args args)))))
2864 (set-current-module m)
2867 ;; The guts of the use-modules macro. Add the interfaces of the named
2868 ;; modules to the use-list of the current module, in order.
2870 ;; This function is called by "modules.c". If you change it, be sure
2871 ;; to change scm_c_use_module as well.
2873 (define (process-use-modules module-interface-args)
2874 (let ((interfaces (map (lambda (mif-args)
2875 (or (apply resolve-interface mif-args)
2876 (error "no such module" mif-args)))
2877 module-interface-args)))
2878 (call-with-deferred-observers
2880 (module-use-interfaces! (current-module) interfaces)))))
2882 (defmacro use-modules modules
2885 (process-use-modules
2886 (list ,@(map (lambda (m)
2887 `(list ,@(compile-interface-spec m)))
2891 (defmacro use-syntax (spec)
2894 (issue-deprecation-warning
2895 "`use-syntax' is deprecated. Please contact guile-devel for more info.")
2896 (process-use-modules (list (list ,@(compile-interface-spec spec))))
2899 ;; Dirk:FIXME:: This incorrect (according to R5RS) syntax needs to be changed
2900 ;; as soon as guile supports hygienic macros.
2901 (define-syntax define-private
2906 (define-syntax define-public
2908 ((_ (name . args) . body)
2909 (define-public name (lambda args . body)))
2915 (define-syntax defmacro-public
2917 ((_ name args . body)
2919 (defmacro name args . body)
2920 (export-syntax name)))))
2922 ;; Export a local variable
2924 ;; This function is called from "modules.c". If you change it, be
2925 ;; sure to update "modules.c" as well.
2927 (define (module-export! m names)
2928 (let ((public-i (module-public-interface m)))
2929 (for-each (lambda (name)
2930 (let ((var (module-ensure-local-variable! m name)))
2931 (module-add! public-i name var)))
2934 (define (module-replace! m names)
2935 (let ((public-i (module-public-interface m)))
2936 (for-each (lambda (name)
2937 (let ((var (module-ensure-local-variable! m name)))
2938 (set-object-property! var 'replace #t)
2939 (module-add! public-i name var)))
2942 ;; Re-export a imported variable
2944 (define (module-re-export! m names)
2945 (let ((public-i (module-public-interface m)))
2946 (for-each (lambda (name)
2947 (let ((var (module-variable m name)))
2949 (error "Undefined variable:" name))
2950 ((eq? var (module-local-variable m name))
2951 (error "re-exporting local variable:" name))
2953 (module-add! public-i name var)))))
2956 (defmacro export names
2957 `(call-with-deferred-observers
2959 (module-export! (current-module) ',names))))
2961 (defmacro re-export names
2962 `(call-with-deferred-observers
2964 (module-re-export! (current-module) ',names))))
2966 (defmacro export-syntax names
2969 (defmacro re-export-syntax names
2970 `(re-export ,@names))
2972 (define load load-module)
2976 ;;; {Compiler interface}
2978 ;;; The full compiler interface can be found in (system). Here we put a
2979 ;;; few useful procedures into the global namespace.
2981 (module-autoload! the-scm-module
2982 '(system base compile)
2984 compile-time-environment))
2992 (define make-mutable-parameter
2993 (let ((make (lambda (fluid converter)
2997 (fluid-set! fluid (converter (car args))))))))
2998 (lambda (init . converter)
2999 (let ((fluid (make-fluid))
3000 (converter (if (null? converter)
3003 (fluid-set! fluid (converter init))
3004 (make fluid converter)))))
3008 ;;; {Handling of duplicate imported bindings}
3011 ;; Duplicate handlers take the following arguments:
3013 ;; module importing module
3014 ;; name conflicting name
3015 ;; int1 old interface where name occurs
3016 ;; val1 value of binding in old interface
3017 ;; int2 new interface where name occurs
3018 ;; val2 value of binding in new interface
3019 ;; var previous resolution or #f
3020 ;; val value of previous resolution
3022 ;; A duplicate handler can take three alternative actions:
3024 ;; 1. return #f => leave responsibility to next handler
3025 ;; 2. exit with an error
3026 ;; 3. return a variable resolving the conflict
3029 (define duplicate-handlers
3030 (let ((m (make-module 7)))
3032 (define (check module name int1 val1 int2 val2 var val)
3033 (scm-error 'misc-error
3035 "~A: `~A' imported from both ~A and ~A"
3036 (list (module-name module)
3042 (define (warn module name int1 val1 int2 val2 var val)
3043 (format (current-error-port)
3044 "WARNING: ~A: `~A' imported from both ~A and ~A\n"
3045 (module-name module)
3051 (define (replace module name int1 val1 int2 val2 var val)
3052 (let ((old (or (and var (object-property var 'replace) var)
3053 (module-variable int1 name)))
3054 (new (module-variable int2 name)))
3055 (if (object-property old 'replace)
3056 (and (or (eq? old new)
3057 (not (object-property new 'replace)))
3059 (and (object-property new 'replace)
3062 (define (warn-override-core module name int1 val1 int2 val2 var val)
3063 (and (eq? int1 the-scm-module)
3065 (format (current-error-port)
3066 "WARNING: ~A: imported module ~A overrides core binding `~A'\n"
3067 (module-name module)
3070 (module-local-variable int2 name))))
3072 (define (first module name int1 val1 int2 val2 var val)
3073 (or var (module-local-variable int1 name)))
3075 (define (last module name int1 val1 int2 val2 var val)
3076 (module-local-variable int2 name))
3078 (define (noop module name int1 val1 int2 val2 var val)
3081 (set-module-name! m 'duplicate-handlers)
3082 (set-module-kind! m 'interface)
3083 (module-define! m 'check check)
3084 (module-define! m 'warn warn)
3085 (module-define! m 'replace replace)
3086 (module-define! m 'warn-override-core warn-override-core)
3087 (module-define! m 'first first)
3088 (module-define! m 'last last)
3089 (module-define! m 'merge-generics noop)
3090 (module-define! m 'merge-accessors noop)
3093 (define (lookup-duplicates-handlers handler-names)
3095 (map (lambda (handler-name)
3096 (or (module-symbol-local-binding
3097 duplicate-handlers handler-name #f)
3098 (error "invalid duplicate handler name:"
3100 (if (list? handler-names)
3102 (list handler-names)))))
3104 (define default-duplicate-binding-procedures
3105 (make-mutable-parameter #f))
3107 (define default-duplicate-binding-handler
3108 (make-mutable-parameter '(replace warn-override-core warn last)
3109 (lambda (handler-names)
3110 (default-duplicate-binding-procedures
3111 (lookup-duplicates-handlers handler-names))
3116 ;;; {`cond-expand' for SRFI-0 support.}
3118 ;;; This syntactic form expands into different commands or
3119 ;;; definitions, depending on the features provided by the Scheme
3125 ;;; --> (cond-expand <cond-expand-clause>+)
3126 ;;; | (cond-expand <cond-expand-clause>* (else <command-or-definition>))
3127 ;;; <cond-expand-clause>
3128 ;;; --> (<feature-requirement> <command-or-definition>*)
3129 ;;; <feature-requirement>
3130 ;;; --> <feature-identifier>
3131 ;;; | (and <feature-requirement>*)
3132 ;;; | (or <feature-requirement>*)
3133 ;;; | (not <feature-requirement>)
3134 ;;; <feature-identifier>
3135 ;;; --> <a symbol which is the name or alias of a SRFI>
3137 ;;; Additionally, this implementation provides the
3138 ;;; <feature-identifier>s `guile' and `r5rs', so that programs can
3139 ;;; determine the implementation type and the supported standard.
3141 ;;; Currently, the following feature identifiers are supported:
3143 ;;; guile r5rs srfi-0 srfi-4 srfi-6 srfi-13 srfi-14 srfi-55 srfi-61
3145 ;;; Remember to update the features list when adding more SRFIs.
3148 (define %cond-expand-features
3149 ;; Adjust the above comment when changing this.
3152 srfi-0 ;; cond-expand itself
3153 srfi-4 ;; homogenous numeric vectors
3154 srfi-6 ;; open-input-string etc, in the guile core
3155 srfi-13 ;; string library
3156 srfi-14 ;; character sets
3157 srfi-55 ;; require-extension
3158 srfi-61 ;; general cond clause
3161 ;; This table maps module public interfaces to the list of features.
3163 (define %cond-expand-table (make-hash-table 31))
3165 ;; Add one or more features to the `cond-expand' feature list of the
3168 (define (cond-expand-provide module features)
3169 (let ((mod (module-public-interface module)))
3171 (hashq-set! %cond-expand-table mod
3172 (append (hashq-ref %cond-expand-table mod '())
3176 (procedure->memoizing-macro
3178 (let ((clauses (cdr exp))
3179 (syntax-error (lambda (cl)
3180 (error "invalid clause in `cond-expand'" cl))))
3186 (or (memq clause %cond-expand-features)
3187 (let lp ((uses (module-uses (env-module env))))
3190 (hashq-ref %cond-expand-table
3196 ((eq? 'and (car clause))
3197 (let lp ((l (cdr clause)))
3201 (and (test-clause (car l)) (lp (cdr l))))
3203 (syntax-error clause)))))
3204 ((eq? 'or (car clause))
3205 (let lp ((l (cdr clause)))
3209 (or (test-clause (car l)) (lp (cdr l))))
3211 (syntax-error clause)))))
3212 ((eq? 'not (car clause))
3213 (cond ((not (pair? (cdr clause)))
3214 (syntax-error clause))
3215 ((pair? (cddr clause))
3216 ((syntax-error clause))))
3217 (not (test-clause (cadr clause))))
3219 (syntax-error clause))))
3221 (syntax-error clause))))))
3222 (let lp ((c clauses))
3225 (error "Unfulfilled `cond-expand'"))
3228 ((not (pair? (car c)))
3229 (syntax-error (car c)))
3230 ((test-clause (caar c))
3231 `(begin ,@(cdar c)))
3232 ((eq? (caar c) 'else)
3235 `(begin ,@(cdar c)))
3237 (lp (cdr c))))))))))
3239 ;; This procedure gets called from the startup code with a list of
3240 ;; numbers, which are the numbers of the SRFIs to be loaded on startup.
3242 (define (use-srfis srfis)
3243 (process-use-modules
3245 (list (list 'srfi (string->symbol
3246 (string-append "srfi-" (number->string num))))))
3251 ;;; srfi-55: require-extension
3254 (define-macro (require-extension extension-spec)
3255 ;; This macro only handles the srfi extension, which, at present, is
3256 ;; the only one defined by the standard.
3257 (if (not (pair? extension-spec))
3258 (scm-error 'wrong-type-arg "require-extension"
3259 "Not an extension: ~S" (list extension-spec) #f))
3260 (let ((extension (car extension-spec))
3261 (extension-args (cdr extension-spec)))
3264 (let ((use-list '()))
3267 (if (not (integer? i))
3268 (scm-error 'wrong-type-arg "require-extension"
3269 "Invalid srfi name: ~S" (list i) #f))
3270 (let ((srfi-sym (string->symbol
3271 (string-append "srfi-" (number->string i)))))
3272 (if (not (memq srfi-sym %cond-expand-features))
3273 (set! use-list (cons `(use-modules (srfi ,srfi-sym))
3276 (if (pair? use-list)
3277 ;; i.e. (begin (use-modules x) (use-modules y) (use-modules z))
3278 `(begin ,@(reverse! use-list)))))
3281 'wrong-type-arg "require-extension"
3282 "Not a recognized extension type: ~S" (list extension) #f)))))
3286 ;;; {Load emacs interface support if emacs option is given.}
3289 (define (named-module-use! user usee)
3290 (module-use! (resolve-module user) (resolve-interface usee)))
3292 (define (load-emacs-interface)
3293 (and (provided? 'debug-extensions)
3294 (debug-enable 'backtrace))
3295 (named-module-use! '(guile-user) '(ice-9 emacs)))
3299 (define using-readline?
3300 (let ((using-readline? (make-fluid)))
3301 (make-procedure-with-setter
3302 (lambda () (fluid-ref using-readline?))
3303 (lambda (v) (fluid-set! using-readline? v)))))
3306 (let ((guile-user-module (resolve-module '(guile-user))))
3308 ;; Load emacs interface support if emacs option is given.
3309 (if (and (module-defined? guile-user-module 'use-emacs-interface)
3310 (module-ref guile-user-module 'use-emacs-interface))
3311 (load-emacs-interface))
3313 ;; Use some convenient modules (in reverse order)
3315 (set-current-module guile-user-module)
3316 (process-use-modules
3321 (if (provided? 'regex)
3324 (if (provided? 'threads)
3325 '(((ice-9 threads)))
3327 ;; load debugger on demand
3328 (module-autoload! guile-user-module '(ice-9 debugger) '(debug))
3330 ;; Note: SIGFPE, SIGSEGV and SIGBUS are actually "query-only" (see
3331 ;; scmsigs.c scm_sigaction_for_thread), so the handlers setup here have
3333 (let ((old-handlers #f)
3334 (start-repl (module-ref (resolve-interface '(system repl repl))
3336 (signals (if (provided? 'posix)
3337 `((,SIGINT . "User interrupt")
3338 (,SIGFPE . "Arithmetic error")
3340 . "Bad memory access (Segmentation violation)"))
3342 ;; no SIGBUS on mingw
3343 (if (defined? 'SIGBUS)
3344 (set! signals (acons SIGBUS "Bad memory access (bus error)"
3351 (let ((make-handler (lambda (msg)
3353 ;; Make a backup copy of the stack
3354 (fluid-set! before-signal-stack
3355 (fluid-ref the-last-stack))
3363 (map (lambda (sig-msg)
3364 (sigaction (car sig-msg)
3365 (make-handler (cdr sig-msg))))
3368 ;; the protected thunk.
3370 (let ((status (start-repl 'scheme)))
3371 (run-hook exit-hook)
3376 (map (lambda (sig-msg old-handler)
3377 (if (not (car old-handler))
3378 ;; restore original C handler.
3379 (sigaction (car sig-msg) #f)
3380 ;; restore Scheme handler, SIG_IGN or SIG_DFL.
3381 (sigaction (car sig-msg)
3383 (cdr old-handler))))
3384 signals old-handlers))))))
3386 ;;; This hook is run at the very end of an interactive session.
3388 (define exit-hook (make-hook))
3392 ;;; {Deprecated stuff}
3396 (define (feature? sym)
3397 (issue-deprecation-warning
3398 "`feature?' is deprecated. Use `provided?' instead.")
3402 (primitive-load-path "ice-9/deprecated"))
3406 ;;; Place the user in the guile-user module.
3409 ;;; FIXME: annotate ?
3410 ;; (define (syncase exp)
3411 ;; (with-fluids ((expansion-eval-closure
3412 ;; (module-eval-closure (current-module))))
3413 ;; (deannotate/source-properties (sc-expand (annotate exp)))))
3415 (define-module (guile-user))
3417 ;;; boot-9.scm ends here