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
40 (if (not (memq sym *features*))
41 (set! *features* (cons sym *features*))))
43 ;; Return #t iff FEATURE is available to this Guile interpreter. In SLIB,
44 ;; provided? also checks to see if the module is available. We should do that
47 (define (provided? feature)
48 (and (memq feature *features*) #t))
50 ;; let format alias simple-format until the more complete version is loaded
52 (define format simple-format)
54 ;; this is scheme wrapping the C code so the final pred call is a tail call,
56 (define (string-any char_pred s . rest)
57 (let ((start (if (null? rest)
59 (end (if (or (null? rest) (null? (cdr rest)))
60 (string-length s) (cadr rest))))
61 (if (and (procedure? char_pred)
63 (<= end (string-length s))) ;; let c-code handle range error
64 (or (string-any-c-code char_pred s start (1- end))
65 (char_pred (string-ref s (1- end))))
66 (string-any-c-code char_pred s start end))))
68 ;; this is scheme wrapping the C code so the final pred call is a tail call,
70 (define (string-every char_pred s . rest)
71 (let ((start (if (null? rest)
73 (end (if (or (null? rest) (null? (cdr rest)))
74 (string-length s) (cadr rest))))
75 (if (and (procedure? char_pred)
77 (<= end (string-length s))) ;; let c-code handle range error
78 (and (string-every-c-code char_pred s start (1- end))
79 (char_pred (string-ref s (1- end))))
80 (string-every-c-code char_pred s start end))))
82 ;; A variant of string-fill! that we keep for compatability
84 (define (substring-fill! str start end fill)
85 (string-fill! str fill start end))
89 ;; (eval-when (situation...) form...)
91 ;; Evaluate certain code based on the situation that eval-when is used
92 ;; in. There are three situations defined.
94 ;; `load' triggers when a file is loaded via `load', or when a compiled
97 ;; `compile' triggers when an expression is compiled.
99 ;; `eval' triggers when code is evaluated interactively, as at the REPL
100 ;; or via the `compile' or `eval' procedures.
102 ;; NB: this macro is only ever expanded by the interpreter. The compiler
103 ;; notices it and interprets the situations differently.
105 (procedure->memoizing-macro
107 (let ((situations (cadr exp))
109 (if (or (memq 'load situations)
110 (memq 'eval situations))
111 `(begin . ,body))))))
115 ;; Before compiling, make sure any symbols are resolved in the (guile)
116 ;; module, the primary location of those symbols, rather than in
117 ;; (guile-user), the default module that we compile in.
120 (set-current-module (resolve-module '(guile))))
124 ;;; Depends on: features, eval-case
127 (define macro-table (make-weak-key-hash-table 61))
128 (define xformer-table (make-weak-key-hash-table 61))
130 (define (defmacro? m) (hashq-ref macro-table m))
131 (define (assert-defmacro?! m) (hashq-set! macro-table m #t))
132 (define (defmacro-transformer m) (hashq-ref xformer-table m))
133 (define (set-defmacro-transformer! m t) (hashq-set! xformer-table m t))
135 (define defmacro:transformer
137 (let* ((xform (lambda (exp env)
138 (copy-tree (apply f (cdr exp)))))
139 (a (procedure->memoizing-macro xform)))
140 (assert-defmacro?! a)
141 (set-defmacro-transformer! a f)
146 (let ((defmacro-transformer
147 (lambda (name parms . body)
148 (let ((transformer `(lambda ,parms ,@body)))
151 (define ,name (defmacro:transformer ,transformer)))))))
152 (defmacro:transformer defmacro-transformer)))
155 ;; XXX - should the definition of the car really be looked up in the
158 (define (macroexpand-1 e)
160 ((pair? e) (let* ((a (car e))
161 (val (and (symbol? a) (local-ref (list a)))))
163 (apply (defmacro-transformer val) (cdr e))
167 (define (macroexpand e)
169 ((pair? e) (let* ((a (car e))
170 (val (and (symbol? a) (local-ref (list a)))))
172 (macroexpand (apply (defmacro-transformer val) (cdr e)))
182 ;;; Depends on: defmacro
185 (defmacro begin-deprecated forms
186 (if (include-deprecated-features)
192 ;;; {R4RS compliance}
195 (primitive-load-path "ice-9/r4rs")
199 ;;; {Simple Debugging Tools}
202 ;; peek takes any number of arguments, writes them to the
203 ;; current ouput port, and returns the last argument.
204 ;; It is handy to wrap around an expression to look at
205 ;; a value each time is evaluated, e.g.:
207 ;; (+ 10 (troublesome-fn))
208 ;; => (+ 10 (pk 'troublesome-fn-returned (troublesome-fn)))
211 (define (peek . stuff)
216 (car (last-pair stuff)))
220 (define (warn . stuff)
221 (with-output-to-port (current-error-port)
224 (display ";;; WARNING ")
227 (car (last-pair stuff)))))
231 ;;; {Trivial Functions}
234 (define (identity x) x)
235 (define (and=> value procedure) (and value (procedure value)))
236 (define call/cc call-with-current-continuation)
238 ;;; apply-to-args is functionally redundant with apply and, worse,
239 ;;; is less general than apply since it only takes two arguments.
241 ;;; On the other hand, apply-to-args is a syntacticly convenient way to
242 ;;; perform binding in many circumstances when the "let" family of
243 ;;; of forms don't cut it. E.g.:
245 ;;; (apply-to-args (return-3d-mouse-coords)
250 (define (apply-to-args args fn) (apply fn args))
252 (defmacro false-if-exception (expr)
253 `(catch #t (lambda () ,expr)
258 ;;; {General Properties}
261 ;; This is a more modern interface to properties. It will replace all
262 ;; other property-like things eventually.
264 (define (make-object-property)
265 (let ((prop (primitive-make-property #f)))
266 (make-procedure-with-setter
267 (lambda (obj) (primitive-property-ref prop obj))
268 (lambda (obj val) (primitive-property-set! prop obj val)))))
272 ;;; {Symbol Properties}
275 (define (symbol-property sym prop)
276 (let ((pair (assoc prop (symbol-pref sym))))
277 (and pair (cdr pair))))
279 (define (set-symbol-property! sym prop val)
280 (let ((pair (assoc prop (symbol-pref sym))))
283 (symbol-pset! sym (acons prop val (symbol-pref sym))))))
285 (define (symbol-property-remove! sym prop)
286 (let ((pair (assoc prop (symbol-pref sym))))
288 (symbol-pset! sym (delq! pair (symbol-pref sym))))))
295 (define (array-shape a)
296 (map (lambda (ind) (if (number? ind) (list 0 (+ -1 ind)) ind))
297 (array-dimensions a)))
304 (define (kw-arg-ref args kw)
305 (let ((rem (member kw args)))
306 (and rem (pair? (cdr rem)) (cadr rem))))
313 (define (struct-layout s)
314 (struct-ref (struct-vtable s) vtable-index-layout))
321 ;; Printing records: by default, records are printed as
323 ;; #<type-name field1: val1 field2: val2 ...>
325 ;; You can change that by giving a custom printing function to
326 ;; MAKE-RECORD-TYPE (after the list of field symbols). This function
327 ;; will be called like
329 ;; (<printer> object port)
331 ;; It should print OBJECT to PORT.
333 (define (inherit-print-state old-port new-port)
334 (if (get-print-state old-port)
335 (port-with-print-state new-port (get-print-state old-port))
338 ;; 0: type-name, 1: fields
339 (define record-type-vtable
340 (make-vtable-vtable "prpr" 0
342 (cond ((eq? s record-type-vtable)
343 (display "#<record-type-vtable>" p))
345 (display "#<record-type " p)
346 (display (record-type-name s) p)
349 (define (record-type? obj)
350 (and (struct? obj) (eq? record-type-vtable (struct-vtable obj))))
352 (define (make-record-type type-name fields . opt)
353 (let ((printer-fn (and (pair? opt) (car opt))))
354 (let ((struct (make-struct record-type-vtable 0
357 (map (lambda (f) "pw") fields)))
361 (display type-name p)
362 (let loop ((fields fields)
365 ((not (null? fields))
367 (display (car fields) p)
369 (display (struct-ref s off) p)
370 (loop (cdr fields) (+ 1 off)))))
373 (copy-tree fields))))
374 ;; Temporary solution: Associate a name to the record type descriptor
375 ;; so that the object system can create a wrapper class for it.
376 (set-struct-vtable-name! struct (if (symbol? type-name)
378 (string->symbol type-name)))
381 (define (record-type-name obj)
382 (if (record-type? obj)
383 (struct-ref obj vtable-offset-user)
384 (error 'not-a-record-type obj)))
386 (define (record-type-fields obj)
387 (if (record-type? obj)
388 (struct-ref obj (+ 1 vtable-offset-user))
389 (error 'not-a-record-type obj)))
391 (define (record-constructor rtd . opt)
392 (let ((field-names (if (pair? opt) (car opt) (record-type-fields rtd))))
394 `(lambda ,field-names
395 (make-struct ',rtd 0 ,@(map (lambda (f)
396 (if (memq f field-names)
399 (record-type-fields rtd)))))))
401 (define (record-predicate rtd)
402 (lambda (obj) (and (struct? obj) (eq? rtd (struct-vtable obj)))))
404 (define (%record-type-error rtd obj) ;; private helper
405 (or (eq? rtd (record-type-descriptor obj))
406 (scm-error 'wrong-type-arg "%record-type-check"
407 "Wrong type record (want `~S'): ~S"
408 (list (record-type-name rtd) obj)
411 (define (record-accessor rtd field-name)
412 (let ((pos (list-index (record-type-fields rtd) field-name)))
414 (error 'no-such-field field-name))
416 (if (eq? (struct-vtable obj) rtd)
418 (%record-type-error rtd obj)))))
420 (define (record-modifier rtd field-name)
421 (let ((pos (list-index (record-type-fields rtd) field-name)))
423 (error 'no-such-field field-name))
425 (if (eq? (struct-vtable obj) rtd)
426 (struct-set! obj pos val)
427 (%record-type-error rtd obj)))))
429 (define (record? obj)
430 (and (struct? obj) (record-type? (struct-vtable obj))))
432 (define (record-type-descriptor obj)
435 (error 'not-a-record obj)))
444 (define (->bool x) (not (not x)))
451 (define (symbol-append . args)
452 (string->symbol (apply string-append (map symbol->string args))))
454 (define (list->symbol . args)
455 (string->symbol (apply list->string args)))
457 (define (symbol . args)
458 (string->symbol (apply string args)))
465 (define (list-index l k)
471 (loop (+ n 1) (cdr l))))))
475 ;;; {and-map and or-map}
477 ;;; (and-map fn lst) is like (and (fn (car lst)) (fn (cadr lst)) (fn...) ...)
478 ;;; (or-map fn lst) is like (or (fn (car lst)) (fn (cadr lst)) (fn...) ...)
483 ;; Apply f to successive elements of l until exhaustion or f returns #f.
484 ;; If returning early, return #f. Otherwise, return the last value returned
485 ;; by f. If f has never been called because l is empty, return #t.
487 (define (and-map f lst)
488 (let loop ((result #t)
493 (loop (f (car l)) (cdr l))))))
497 ;; Apply f to successive elements of l until exhaustion or while f returns #f.
498 ;; If returning early, return the return value of f.
500 (define (or-map f lst)
501 (let loop ((result #f)
505 (loop (f (car l)) (cdr l))))))
509 (if (provided? 'posix)
510 (primitive-load-path "ice-9/posix"))
512 (if (provided? 'socket)
513 (primitive-load-path "ice-9/networking"))
515 ;; For reference, Emacs file-exists-p uses stat in this same way.
516 ;; ENHANCE-ME: Catching an exception from stat is a bit wasteful, do this in
517 ;; C where all that's needed is to inspect the return from stat().
519 (if (provided? 'posix)
521 (->bool (false-if-exception (stat str))))
523 (let ((port (catch 'system-error (lambda () (open-file str OPEN_READ))
525 (if port (begin (close-port port) #t)
528 (define file-is-directory?
529 (if (provided? 'posix)
531 (eq? (stat:type (stat str)) 'directory))
533 (let ((port (catch 'system-error
534 (lambda () (open-file (string-append str "/.")
537 (if port (begin (close-port port) #t)
540 (define (has-suffix? str suffix)
541 (string-suffix? suffix str))
543 (define (system-error-errno args)
544 (if (eq? (car args) 'system-error)
545 (car (list-ref args 4))
553 (define (error . args)
556 (scm-error 'misc-error #f "?" #f #f)
557 (let loop ((msg "~A")
559 (if (not (null? rest))
560 (loop (string-append msg " ~S")
562 (scm-error 'misc-error #f msg args #f)))))
564 ;; bad-throw is the hook that is called upon a throw to a an unhandled
565 ;; key (unless the throw has four arguments, in which case
566 ;; it's usually interpreted as an error throw.)
567 ;; If the key has a default handler (a throw-handler-default property),
568 ;; it is applied to the throw.
570 (define (bad-throw key . args)
571 (let ((default (symbol-property key 'throw-handler-default)))
572 (or (and default (apply default key args))
573 (apply error "unhandled-exception:" key args))))
577 (define (tm:sec obj) (vector-ref obj 0))
578 (define (tm:min obj) (vector-ref obj 1))
579 (define (tm:hour obj) (vector-ref obj 2))
580 (define (tm:mday obj) (vector-ref obj 3))
581 (define (tm:mon obj) (vector-ref obj 4))
582 (define (tm:year obj) (vector-ref obj 5))
583 (define (tm:wday obj) (vector-ref obj 6))
584 (define (tm:yday obj) (vector-ref obj 7))
585 (define (tm:isdst obj) (vector-ref obj 8))
586 (define (tm:gmtoff obj) (vector-ref obj 9))
587 (define (tm:zone obj) (vector-ref obj 10))
589 (define (set-tm:sec obj val) (vector-set! obj 0 val))
590 (define (set-tm:min obj val) (vector-set! obj 1 val))
591 (define (set-tm:hour obj val) (vector-set! obj 2 val))
592 (define (set-tm:mday obj val) (vector-set! obj 3 val))
593 (define (set-tm:mon obj val) (vector-set! obj 4 val))
594 (define (set-tm:year obj val) (vector-set! obj 5 val))
595 (define (set-tm:wday obj val) (vector-set! obj 6 val))
596 (define (set-tm:yday obj val) (vector-set! obj 7 val))
597 (define (set-tm:isdst obj val) (vector-set! obj 8 val))
598 (define (set-tm:gmtoff obj val) (vector-set! obj 9 val))
599 (define (set-tm:zone obj val) (vector-set! obj 10 val))
601 (define (tms:clock obj) (vector-ref obj 0))
602 (define (tms:utime obj) (vector-ref obj 1))
603 (define (tms:stime obj) (vector-ref obj 2))
604 (define (tms:cutime obj) (vector-ref obj 3))
605 (define (tms:cstime obj) (vector-ref obj 4))
607 (define file-position ftell)
608 (define (file-set-position port offset . whence)
609 (let ((whence (if (eq? whence '()) SEEK_SET (car whence))))
610 (seek port offset whence)))
612 (define (move->fdes fd/port fd)
613 (cond ((integer? fd/port)
614 (dup->fdes fd/port fd)
618 (primitive-move->fdes fd/port fd)
619 (set-port-revealed! fd/port 1)
622 (define (release-port-handle port)
623 (let ((revealed (port-revealed port)))
625 (set-port-revealed! port (- revealed 1)))))
627 (define (dup->port port/fd mode . maybe-fd)
628 (let ((port (fdopen (apply dup->fdes port/fd maybe-fd)
631 (set-port-revealed! port 1))
634 (define (dup->inport port/fd . maybe-fd)
635 (apply dup->port port/fd "r" maybe-fd))
637 (define (dup->outport port/fd . maybe-fd)
638 (apply dup->port port/fd "w" maybe-fd))
640 (define (dup port/fd . maybe-fd)
641 (if (integer? port/fd)
642 (apply dup->fdes port/fd maybe-fd)
643 (apply dup->port port/fd (port-mode port/fd) maybe-fd)))
645 (define (duplicate-port port modes)
646 (dup->port port modes))
648 (define (fdes->inport fdes)
649 (let loop ((rest-ports (fdes->ports fdes)))
650 (cond ((null? rest-ports)
651 (let ((result (fdopen fdes "r")))
652 (set-port-revealed! result 1)
654 ((input-port? (car rest-ports))
655 (set-port-revealed! (car rest-ports)
656 (+ (port-revealed (car rest-ports)) 1))
659 (loop (cdr rest-ports))))))
661 (define (fdes->outport fdes)
662 (let loop ((rest-ports (fdes->ports fdes)))
663 (cond ((null? rest-ports)
664 (let ((result (fdopen fdes "w")))
665 (set-port-revealed! result 1)
667 ((output-port? (car rest-ports))
668 (set-port-revealed! (car rest-ports)
669 (+ (port-revealed (car rest-ports)) 1))
672 (loop (cdr rest-ports))))))
674 (define (port->fdes port)
675 (set-port-revealed! port (+ (port-revealed port) 1))
678 (define (setenv name value)
680 (putenv (string-append name "=" value))
683 (define (unsetenv name)
684 "Remove the entry for NAME from the environment."
692 ;;; Here for backward compatability
694 (define scheme-file-suffix (lambda () ".scm"))
696 (define (in-vicinity vicinity file)
697 (let ((tail (let ((len (string-length vicinity)))
700 (string-ref vicinity (- len 1))))))
701 (string-append vicinity
710 ;;; {Help for scm_shell}
712 ;;; The argument-processing code used by Guile-based shells generates
713 ;;; Scheme code based on the argument list. This page contains help
714 ;;; functions for the code it generates.
717 (define (command-line) (program-arguments))
719 ;; This is mostly for the internal use of the code generated by
720 ;; scm_compile_shell_switches.
722 (define (turn-on-debugging)
723 (debug-enable 'debug)
724 (debug-enable 'backtrace)
725 (read-enable 'positions))
727 (define (load-user-init)
728 (let* ((home (or (getenv "HOME")
729 (false-if-exception (passwd:dir (getpwuid (getuid))))
730 "/")) ;; fallback for cygwin etc.
731 (init-file (in-vicinity home ".guile")))
732 (if (file-exists? init-file)
733 (primitive-load init-file))))
737 ;;; {The interpreter stack}
740 (defmacro start-stack (tag exp)
741 `(%start-stack ,tag (lambda () ,exp)))
745 ;;; {Loading by paths}
748 ;;; Load a Scheme source file named NAME, searching for it in the
749 ;;; directories listed in %load-path, and applying each of the file
750 ;;; name extensions listed in %load-extensions.
751 (define (load-from-path name)
752 (start-stack 'load-stack
753 (primitive-load-path name)))
758 ;;; {Transcendental Functions}
760 ;;; Derived from "Transcen.scm", Complex trancendental functions for SCM.
761 ;;; Written by Jerry D. Hedden, (C) FSF.
762 ;;; See the file `COPYING' for terms applying to this program.
766 (let ((integer-expt integer-expt))
768 (cond ((and (exact? z2) (integer? z2))
769 (integer-expt z1 z2))
770 ((and (real? z2) (real? z1) (>= z1 0))
773 (exp (* z2 (log z1))))))))
776 (if (real? z) ($sinh z)
777 (let ((x (real-part z)) (y (imag-part z)))
778 (make-rectangular (* ($sinh x) ($cos y))
779 (* ($cosh x) ($sin y))))))
781 (if (real? z) ($cosh z)
782 (let ((x (real-part z)) (y (imag-part z)))
783 (make-rectangular (* ($cosh x) ($cos y))
784 (* ($sinh x) ($sin y))))))
786 (if (real? z) ($tanh z)
787 (let* ((x (* 2 (real-part z)))
788 (y (* 2 (imag-part z)))
789 (w (+ ($cosh x) ($cos y))))
790 (make-rectangular (/ ($sinh x) w) (/ ($sin y) w)))))
793 (if (real? z) ($asinh z)
794 (log (+ z (sqrt (+ (* z z) 1))))))
797 (if (and (real? z) (>= z 1))
799 (log (+ z (sqrt (- (* z z) 1))))))
802 (if (and (real? z) (> z -1) (< z 1))
804 (/ (log (/ (+ 1 z) (- 1 z))) 2)))
807 (if (real? z) ($sin z)
808 (let ((x (real-part z)) (y (imag-part z)))
809 (make-rectangular (* ($sin x) ($cosh y))
810 (* ($cos x) ($sinh y))))))
812 (if (real? z) ($cos z)
813 (let ((x (real-part z)) (y (imag-part z)))
814 (make-rectangular (* ($cos x) ($cosh y))
815 (- (* ($sin x) ($sinh y)))))))
817 (if (real? z) ($tan z)
818 (let* ((x (* 2 (real-part z)))
819 (y (* 2 (imag-part z)))
820 (w (+ ($cos x) ($cosh y))))
821 (make-rectangular (/ ($sin x) w) (/ ($sinh y) w)))))
824 (if (and (real? z) (>= z -1) (<= z 1))
826 (* -i (asinh (* +i z)))))
829 (if (and (real? z) (>= z -1) (<= z 1))
831 (+ (/ (angle -1) 2) (* +i (asinh (* +i z))))))
835 (if (real? z) ($atan z)
836 (/ (log (/ (- +i z) (+ +i z))) +2i))
841 ;;; {Reader Extensions}
843 ;;; Reader code for various "#c" forms.
846 (read-hash-extend #\' (lambda (c port)
849 (define read-eval? (make-fluid))
850 (fluid-set! read-eval? #f)
851 (read-hash-extend #\.
853 (if (fluid-ref read-eval?)
854 (eval (read port) (interaction-environment))
856 "#. read expansion found and read-eval? is #f."))))
860 ;;; {Command Line Options}
863 (define (get-option argv kw-opts kw-args return)
868 ((or (not (eq? #\- (string-ref (car argv) 0)))
869 (eq? (string-length (car argv)) 1))
870 (return 'normal-arg (car argv) (cdr argv)))
872 ((eq? #\- (string-ref (car argv) 1))
873 (let* ((kw-arg-pos (or (string-index (car argv) #\=)
874 (string-length (car argv))))
875 (kw (symbol->keyword (substring (car argv) 2 kw-arg-pos)))
876 (kw-opt? (member kw kw-opts))
877 (kw-arg? (member kw kw-args))
878 (arg (or (and (not (eq? kw-arg-pos (string-length (car argv))))
879 (substring (car argv)
881 (string-length (car argv))))
883 (begin (set! argv (cdr argv)) (car argv))))))
884 (if (or kw-opt? kw-arg?)
885 (return kw arg (cdr argv))
886 (return 'usage-error kw (cdr argv)))))
889 (let* ((char (substring (car argv) 1 2))
890 (kw (symbol->keyword char)))
894 (let* ((rest-car (substring (car argv) 2 (string-length (car argv))))
895 (new-argv (if (= 0 (string-length rest-car))
897 (cons (string-append "-" rest-car) (cdr argv)))))
898 (return kw #f new-argv)))
901 (let* ((rest-car (substring (car argv) 2 (string-length (car argv))))
902 (arg (if (= 0 (string-length rest-car))
905 (new-argv (if (= 0 (string-length rest-car))
908 (return kw arg new-argv)))
910 (else (return 'usage-error kw argv)))))))
912 (define (for-next-option proc argv kw-opts kw-args)
913 (let loop ((argv argv))
914 (get-option argv kw-opts kw-args
915 (lambda (opt opt-arg argv)
916 (and opt (proc opt opt-arg argv loop))))))
918 (define (display-usage-report kw-desc)
921 (or (eq? (car kw) #t)
924 (help (cadr opt-desc))
925 (opts (car opt-desc))
926 (opts-proper (if (string? (car opts)) (cdr opts) opts))
927 (arg-name (if (string? (car opts))
928 (string-append "<" (car opts) ">")
930 (left-part (string-append
931 (with-output-to-string
933 (map (lambda (x) (display (keyword->symbol x)) (display " "))
936 (middle-part (if (and (< (string-length left-part) 30)
937 (< (string-length help) 40))
938 (make-string (- 30 (string-length left-part)) #\ )
941 (display middle-part)
948 (define (transform-usage-lambda cases)
949 (let* ((raw-usage (delq! 'else (map car cases)))
950 (usage-sans-specials (map (lambda (x)
951 (or (and (not (list? x)) x)
952 (and (symbol? (car x)) #t)
953 (and (boolean? (car x)) #t)
956 (usage-desc (delq! #t usage-sans-specials))
957 (kw-desc (map car usage-desc))
958 (kw-opts (apply append (map (lambda (x) (and (not (string? (car x))) x)) kw-desc)))
959 (kw-args (apply append (map (lambda (x) (and (string? (car x)) (cdr x))) kw-desc)))
960 (transmogrified-cases (map (lambda (case)
961 (cons (let ((opts (car case)))
962 (if (or (boolean? opts) (eq? 'else opts))
965 ((symbol? (car opts)) opts)
966 ((boolean? (car opts)) opts)
967 ((string? (caar opts)) (cdar opts))
971 `(let ((%display-usage (lambda () (display-usage-report ',usage-desc))))
973 (let %next-arg ((%argv %argv))
977 (lambda (%opt %arg %new-argv)
979 ,@ transmogrified-cases))))))))
984 ;;; {Low Level Modules}
986 ;;; These are the low level data structures for modules.
988 ;;; Every module object is of the type 'module-type', which is a record
989 ;;; consisting of the following members:
991 ;;; - eval-closure: the function that defines for its module the strategy that
992 ;;; shall be followed when looking up symbols in the module.
994 ;;; An eval-closure is a function taking two arguments: the symbol to be
995 ;;; looked up and a boolean value telling whether a binding for the symbol
996 ;;; should be created if it does not exist yet. If the symbol lookup
997 ;;; succeeded (either because an existing binding was found or because a new
998 ;;; binding was created), a variable object representing the binding is
999 ;;; returned. Otherwise, the value #f is returned. Note that the eval
1000 ;;; closure does not take the module to be searched as an argument: During
1001 ;;; construction of the eval-closure, the eval-closure has to store the
1002 ;;; module it belongs to in its environment. This means, that any
1003 ;;; eval-closure can belong to only one module.
1005 ;;; The eval-closure of a module can be defined arbitrarily. However, three
1006 ;;; special cases of eval-closures are to be distinguished: During startup
1007 ;;; the module system is not yet activated. In this phase, no modules are
1008 ;;; defined and all bindings are automatically stored by the system in the
1009 ;;; pre-modules-obarray. Since no eval-closures exist at this time, the
1010 ;;; functions which require an eval-closure as their argument need to be
1011 ;;; passed the value #f.
1013 ;;; The other two special cases of eval-closures are the
1014 ;;; standard-eval-closure and the standard-interface-eval-closure. Both
1015 ;;; behave equally for the case that no new binding is to be created. The
1016 ;;; difference between the two comes in, when the boolean argument to the
1017 ;;; eval-closure indicates that a new binding shall be created if it is not
1020 ;;; Given that no new binding shall be created, both standard eval-closures
1021 ;;; define the following standard strategy of searching bindings in the
1022 ;;; module: First, the module's obarray is searched for the symbol. Second,
1023 ;;; if no binding for the symbol was found in the module's obarray, the
1024 ;;; module's binder procedure is exececuted. If this procedure did not
1025 ;;; return a binding for the symbol, the modules referenced in the module's
1026 ;;; uses list are recursively searched for a binding of the symbol. If the
1027 ;;; binding can not be found in these modules also, the symbol lookup has
1030 ;;; If a new binding shall be created, the standard-interface-eval-closure
1031 ;;; immediately returns indicating failure. That is, it does not even try
1032 ;;; to look up the symbol. In contrast, the standard-eval-closure would
1033 ;;; first search the obarray, and if no binding was found there, would
1034 ;;; create a new binding in the obarray, therefore not calling the binder
1035 ;;; procedure or searching the modules in the uses list.
1037 ;;; The explanation of the following members obarray, binder and uses
1038 ;;; assumes that the symbol lookup follows the strategy that is defined in
1039 ;;; the standard-eval-closure and the standard-interface-eval-closure.
1041 ;;; - obarray: a hash table that maps symbols to variable objects. In this
1042 ;;; hash table, the definitions are found that are local to the module (that
1043 ;;; is, not imported from other modules). When looking up bindings in the
1044 ;;; module, this hash table is searched first.
1046 ;;; - binder: either #f or a function taking a module and a symbol argument.
1047 ;;; If it is a function it is called after the obarray has been
1048 ;;; unsuccessfully searched for a binding. It then can provide bindings
1049 ;;; that would otherwise not be found locally in the module.
1051 ;;; - uses: a list of modules from which non-local bindings can be inherited.
1052 ;;; These modules are the third place queried for bindings after the obarray
1053 ;;; has been unsuccessfully searched and the binder function did not deliver
1054 ;;; a result either.
1056 ;;; - transformer: either #f or a function taking a scheme expression as
1057 ;;; delivered by read. If it is a function, it will be called to perform
1058 ;;; syntax transformations (e. g. makro expansion) on the given scheme
1059 ;;; expression. The output of the transformer function will then be passed
1060 ;;; to Guile's internal memoizer. This means that the output must be valid
1061 ;;; scheme code. The only exception is, that the output may make use of the
1062 ;;; syntax extensions provided to identify the modules that a binding
1065 ;;; - name: the name of the module. This is used for all kinds of printing
1066 ;;; outputs. In certain places the module name also serves as a way of
1067 ;;; identification. When adding a module to the uses list of another
1068 ;;; module, it is made sure that the new uses list will not contain two
1069 ;;; modules of the same name.
1071 ;;; - kind: classification of the kind of module. The value is (currently?)
1072 ;;; only used for printing. It has no influence on how a module is treated.
1073 ;;; Currently the following values are used when setting the module kind:
1074 ;;; 'module, 'directory, 'interface, 'custom-interface. If no explicit kind
1075 ;;; is set, it defaults to 'module.
1077 ;;; - duplicates-handlers: a list of procedures that get called to make a
1078 ;;; choice between two duplicate bindings when name clashes occur. See the
1079 ;;; `duplicate-handlers' global variable below.
1081 ;;; - observers: a list of procedures that get called when the module is
1084 ;;; - weak-observers: a weak-key hash table of procedures that get called
1085 ;;; when the module is modified. See `module-observe-weak' for details.
1087 ;;; In addition, the module may (must?) contain a binding for
1088 ;;; `%module-public-interface'. This variable should be bound to a module
1089 ;;; representing the exported interface of a module. See the
1090 ;;; `module-public-interface' and `module-export!' procedures.
1092 ;;; !!! warning: The interface to lazy binder procedures is going
1093 ;;; to be changed in an incompatible way to permit all the basic
1094 ;;; module ops to be virtualized.
1096 ;;; (make-module size use-list lazy-binding-proc) => module
1097 ;;; module-{obarray,uses,binder}[|-set!]
1098 ;;; (module? obj) => [#t|#f]
1099 ;;; (module-locally-bound? module symbol) => [#t|#f]
1100 ;;; (module-bound? module symbol) => [#t|#f]
1101 ;;; (module-symbol-locally-interned? module symbol) => [#t|#f]
1102 ;;; (module-symbol-interned? module symbol) => [#t|#f]
1103 ;;; (module-local-variable module symbol) => [#<variable ...> | #f]
1104 ;;; (module-variable module symbol) => [#<variable ...> | #f]
1105 ;;; (module-symbol-binding module symbol opt-value)
1106 ;;; => [ <obj> | opt-value | an error occurs ]
1107 ;;; (module-make-local-var! module symbol) => #<variable...>
1108 ;;; (module-add! module symbol var) => unspecified
1109 ;;; (module-remove! module symbol) => unspecified
1110 ;;; (module-for-each proc module) => unspecified
1111 ;;; (make-scm-module) => module ; a lazy copy of the symhash module
1112 ;;; (set-current-module module) => unspecified
1113 ;;; (current-module) => #<module...>
1119 ;;; {Printing Modules}
1122 ;; This is how modules are printed. You can re-define it.
1123 ;; (Redefining is actually more complicated than simply redefining
1124 ;; %print-module because that would only change the binding and not
1125 ;; the value stored in the vtable that determines how record are
1128 (define (%print-module mod port) ; unused args: depth length style table)
1130 (display (or (module-kind mod) "module") port)
1131 (let ((name (module-name mod)))
1135 (display name port))))
1137 (display (number->string (object-address mod) 16) port)
1142 ;; A module is characterized by an obarray in which local symbols
1143 ;; are interned, a list of modules, "uses", from which non-local
1144 ;; bindings can be inherited, and an optional lazy-binder which
1145 ;; is a (CLOSURE module symbol) which, as a last resort, can provide
1146 ;; bindings that would otherwise not be found locally in the module.
1148 ;; NOTE: If you change anything here, you also need to change
1149 ;; libguile/modules.h.
1152 (make-record-type 'module
1153 '(obarray uses binder eval-closure transformer name kind
1154 duplicates-handlers import-obarray
1155 observers weak-observers)
1158 ;; make-module &opt size uses binder
1160 ;; Create a new module, perhaps with a particular size of obarray,
1161 ;; initial uses list, or binding procedure.
1166 (define (parse-arg index default)
1167 (if (> (length args) index)
1168 (list-ref args index)
1171 (define %default-import-size
1172 ;; Typical number of imported bindings actually used by a module.
1175 (if (> (length args) 3)
1176 (error "Too many args to make-module." args))
1178 (let ((size (parse-arg 0 31))
1179 (uses (parse-arg 1 '()))
1180 (binder (parse-arg 2 #f)))
1182 (if (not (integer? size))
1183 (error "Illegal size to make-module." size))
1184 (if (not (and (list? uses)
1185 (and-map module? uses)))
1186 (error "Incorrect use list." uses))
1187 (if (and binder (not (procedure? binder)))
1189 "Lazy-binder expected to be a procedure or #f." binder))
1191 (let ((module (module-constructor (make-hash-table size)
1192 uses binder #f #f #f #f #f
1193 (make-hash-table %default-import-size)
1195 (make-weak-key-hash-table 31))))
1197 ;; We can't pass this as an argument to module-constructor,
1198 ;; because we need it to close over a pointer to the module
1200 (set-module-eval-closure! module (standard-eval-closure module))
1204 (define module-constructor (record-constructor module-type))
1205 (define module-obarray (record-accessor module-type 'obarray))
1206 (define set-module-obarray! (record-modifier module-type 'obarray))
1207 (define module-uses (record-accessor module-type 'uses))
1208 (define set-module-uses! (record-modifier module-type 'uses))
1209 (define module-binder (record-accessor module-type 'binder))
1210 (define set-module-binder! (record-modifier module-type 'binder))
1212 ;; NOTE: This binding is used in libguile/modules.c.
1213 (define module-eval-closure (record-accessor module-type 'eval-closure))
1215 (define module-transformer (record-accessor module-type 'transformer))
1216 (define set-module-transformer! (record-modifier module-type 'transformer))
1217 (define module-name (record-accessor module-type 'name))
1218 (define set-module-name! (record-modifier module-type 'name))
1219 (define module-kind (record-accessor module-type 'kind))
1220 (define set-module-kind! (record-modifier module-type 'kind))
1221 (define module-duplicates-handlers
1222 (record-accessor module-type 'duplicates-handlers))
1223 (define set-module-duplicates-handlers!
1224 (record-modifier module-type 'duplicates-handlers))
1225 (define module-observers (record-accessor module-type 'observers))
1226 (define set-module-observers! (record-modifier module-type 'observers))
1227 (define module-weak-observers (record-accessor module-type 'weak-observers))
1228 (define module? (record-predicate module-type))
1230 (define module-import-obarray (record-accessor module-type 'import-obarray))
1232 (define set-module-eval-closure!
1233 (let ((setter (record-modifier module-type 'eval-closure)))
1234 (lambda (module closure)
1235 (setter module closure)
1236 ;; Make it possible to lookup the module from the environment.
1237 ;; This implementation is correct since an eval closure can belong
1238 ;; to maximally one module.
1239 (set-procedure-property! closure 'module module))))
1243 ;;; {Observer protocol}
1246 (define (module-observe module proc)
1247 (set-module-observers! module (cons proc (module-observers module)))
1250 (define (module-observe-weak module observer-id . proc)
1251 ;; Register PROC as an observer of MODULE under name OBSERVER-ID (which can
1252 ;; be any Scheme object). PROC is invoked and passed MODULE any time
1253 ;; MODULE is modified. PROC gets unregistered when OBSERVER-ID gets GC'd
1254 ;; (thus, it is never unregistered if OBSERVER-ID is an immediate value,
1257 ;; The two-argument version is kept for backward compatibility: when called
1258 ;; with two arguments, the observer gets unregistered when closure PROC
1259 ;; gets GC'd (making it impossible to use an anonymous lambda for PROC).
1261 (let ((proc (if (null? proc) observer-id (car proc))))
1262 (hashq-set! (module-weak-observers module) observer-id proc)))
1264 (define (module-unobserve token)
1265 (let ((module (car token))
1268 (hash-remove! (module-weak-observers module) id)
1269 (set-module-observers! module (delq1! id (module-observers module)))))
1272 (define module-defer-observers #f)
1273 (define module-defer-observers-mutex (make-mutex 'recursive))
1274 (define module-defer-observers-table (make-hash-table))
1276 (define (module-modified m)
1277 (if module-defer-observers
1278 (hash-set! module-defer-observers-table m #t)
1279 (module-call-observers m)))
1281 ;;; This function can be used to delay calls to observers so that they
1282 ;;; can be called once only in the face of massive updating of modules.
1284 (define (call-with-deferred-observers thunk)
1287 (lock-mutex module-defer-observers-mutex)
1288 (set! module-defer-observers #t))
1291 (set! module-defer-observers #f)
1292 (hash-for-each (lambda (m dummy)
1293 (module-call-observers m))
1294 module-defer-observers-table)
1295 (hash-clear! module-defer-observers-table)
1296 (unlock-mutex module-defer-observers-mutex))))
1298 (define (module-call-observers m)
1299 (for-each (lambda (proc) (proc m)) (module-observers m))
1301 ;; We assume that weak observers don't (un)register themselves as they are
1302 ;; called since this would preclude proper iteration over the hash table
1304 (hash-for-each (lambda (id proc) (proc m)) (module-weak-observers m)))
1308 ;;; {Module Searching in General}
1310 ;;; We sometimes want to look for properties of a symbol
1311 ;;; just within the obarray of one module. If the property
1312 ;;; holds, then it is said to hold ``locally'' as in, ``The symbol
1313 ;;; DISPLAY is locally rebound in the module `safe-guile'.''
1316 ;;; Other times, we want to test for a symbol property in the obarray
1317 ;;; of M and, if it is not found there, try each of the modules in the
1318 ;;; uses list of M. This is the normal way of testing for some
1319 ;;; property, so we state these properties without qualification as
1320 ;;; in: ``The symbol 'fnord is interned in module M because it is
1321 ;;; interned locally in module M2 which is a member of the uses list
1325 ;; module-search fn m
1327 ;; return the first non-#f result of FN applied to M and then to
1328 ;; the modules in the uses of m, and so on recursively. If all applications
1329 ;; return #f, then so does this function.
1331 (define (module-search fn m v)
1334 (or (module-search fn (car pos) v)
1337 (loop (module-uses m))))
1340 ;;; {Is a symbol bound in a module?}
1342 ;;; Symbol S in Module M is bound if S is interned in M and if the binding
1343 ;;; of S in M has been set to some well-defined value.
1346 ;; module-locally-bound? module symbol
1348 ;; Is a symbol bound (interned and defined) locally in a given module?
1350 (define (module-locally-bound? m v)
1351 (let ((var (module-local-variable m v)))
1353 (variable-bound? var))))
1355 ;; module-bound? module symbol
1357 ;; Is a symbol bound (interned and defined) anywhere in a given module
1360 (define (module-bound? m v)
1361 (module-search module-locally-bound? m v))
1363 ;;; {Is a symbol interned in a module?}
1365 ;;; Symbol S in Module M is interned if S occurs in
1366 ;;; of S in M has been set to some well-defined value.
1368 ;;; It is possible to intern a symbol in a module without providing
1369 ;;; an initial binding for the corresponding variable. This is done
1371 ;;; (module-add! module symbol (make-undefined-variable))
1373 ;;; In that case, the symbol is interned in the module, but not
1374 ;;; bound there. The unbound symbol shadows any binding for that
1375 ;;; symbol that might otherwise be inherited from a member of the uses list.
1378 (define (module-obarray-get-handle ob key)
1379 ((if (symbol? key) hashq-get-handle hash-get-handle) ob key))
1381 (define (module-obarray-ref ob key)
1382 ((if (symbol? key) hashq-ref hash-ref) ob key))
1384 (define (module-obarray-set! ob key val)
1385 ((if (symbol? key) hashq-set! hash-set!) ob key val))
1387 (define (module-obarray-remove! ob key)
1388 ((if (symbol? key) hashq-remove! hash-remove!) ob key))
1390 ;; module-symbol-locally-interned? module symbol
1392 ;; is a symbol interned (not neccessarily defined) locally in a given module
1393 ;; or its uses? Interned symbols shadow inherited bindings even if
1394 ;; they are not themselves bound to a defined value.
1396 (define (module-symbol-locally-interned? m v)
1397 (not (not (module-obarray-get-handle (module-obarray m) v))))
1399 ;; module-symbol-interned? module symbol
1401 ;; is a symbol interned (not neccessarily defined) anywhere in a given module
1402 ;; or its uses? Interned symbols shadow inherited bindings even if
1403 ;; they are not themselves bound to a defined value.
1405 (define (module-symbol-interned? m v)
1406 (module-search module-symbol-locally-interned? m v))
1409 ;;; {Mapping modules x symbols --> variables}
1412 ;; module-local-variable module symbol
1413 ;; return the local variable associated with a MODULE and SYMBOL.
1415 ;;; This function is very important. It is the only function that can
1416 ;;; return a variable from a module other than the mutators that store
1417 ;;; new variables in modules. Therefore, this function is the location
1418 ;;; of the "lazy binder" hack.
1420 ;;; If symbol is defined in MODULE, and if the definition binds symbol
1421 ;;; to a variable, return that variable object.
1423 ;;; If the symbols is not found at first, but the module has a lazy binder,
1424 ;;; then try the binder.
1426 ;;; If the symbol is not found at all, return #f.
1428 ;;; (This is now written in C, see `modules.c'.)
1431 ;;; {Mapping modules x symbols --> bindings}
1433 ;;; These are similar to the mapping to variables, except that the
1434 ;;; variable is dereferenced.
1437 ;; module-symbol-binding module symbol opt-value
1439 ;; return the binding of a variable specified by name within
1440 ;; a given module, signalling an error if the variable is unbound.
1441 ;; If the OPT-VALUE is passed, then instead of signalling an error,
1442 ;; return OPT-VALUE.
1444 (define (module-symbol-local-binding m v . opt-val)
1445 (let ((var (module-local-variable m v)))
1446 (if (and var (variable-bound? var))
1448 (if (not (null? opt-val))
1450 (error "Locally unbound variable." v)))))
1452 ;; module-symbol-binding module symbol opt-value
1454 ;; return the binding of a variable specified by name within
1455 ;; a given module, signalling an error if the variable is unbound.
1456 ;; If the OPT-VALUE is passed, then instead of signalling an error,
1457 ;; return OPT-VALUE.
1459 (define (module-symbol-binding m v . opt-val)
1460 (let ((var (module-variable m v)))
1461 (if (and var (variable-bound? var))
1463 (if (not (null? opt-val))
1465 (error "Unbound variable." v)))))
1470 ;;; {Adding Variables to Modules}
1473 ;; module-make-local-var! module symbol
1475 ;; ensure a variable for V in the local namespace of M.
1476 ;; If no variable was already there, then create a new and uninitialzied
1479 ;; This function is used in modules.c.
1481 (define (module-make-local-var! m v)
1482 (or (let ((b (module-obarray-ref (module-obarray m) v)))
1485 ;; Mark as modified since this function is called when
1486 ;; the standard eval closure defines a binding
1490 ;; Create a new local variable.
1491 (let ((local-var (make-undefined-variable)))
1492 (module-add! m v local-var)
1495 ;; module-ensure-local-variable! module symbol
1497 ;; Ensure that there is a local variable in MODULE for SYMBOL. If
1498 ;; there is no binding for SYMBOL, create a new uninitialized
1499 ;; variable. Return the local variable.
1501 (define (module-ensure-local-variable! module symbol)
1502 (or (module-local-variable module symbol)
1503 (let ((var (make-undefined-variable)))
1504 (module-add! module symbol var)
1507 ;; module-add! module symbol var
1509 ;; ensure a particular variable for V in the local namespace of M.
1511 (define (module-add! m v var)
1512 (if (not (variable? var))
1513 (error "Bad variable to module-add!" var))
1514 (module-obarray-set! (module-obarray m) v var)
1515 (module-modified m))
1519 ;; make sure that a symbol is undefined in the local namespace of M.
1521 (define (module-remove! m v)
1522 (module-obarray-remove! (module-obarray m) v)
1523 (module-modified m))
1525 (define (module-clear! m)
1526 (hash-clear! (module-obarray m))
1527 (module-modified m))
1529 ;; MODULE-FOR-EACH -- exported
1531 ;; Call PROC on each symbol in MODULE, with arguments of (SYMBOL VARIABLE).
1533 (define (module-for-each proc module)
1534 (hash-for-each proc (module-obarray module)))
1536 (define (module-map proc module)
1537 (hash-map->list proc (module-obarray module)))
1541 ;;; {Low Level Bootstrapping}
1546 ;; A root module uses the pre-modules-obarray as its obarray. This
1547 ;; special obarray accumulates all bindings that have been established
1548 ;; before the module system is fully booted.
1550 ;; (The obarray continues to be used by code that has been closed over
1551 ;; before the module system has been booted.)
1553 (define (make-root-module)
1554 (let ((m (make-module 0)))
1555 (set-module-obarray! m (%get-pre-modules-obarray))
1560 ;; The root interface is a module that uses the same obarray as the
1561 ;; root module. It does not allow new definitions, tho.
1563 (define (make-scm-module)
1564 (let ((m (make-module 0)))
1565 (set-module-obarray! m (%get-pre-modules-obarray))
1566 (set-module-eval-closure! m (standard-interface-eval-closure m))
1572 ;;; {Module-based Loading}
1575 (define (save-module-excursion thunk)
1576 (let ((inner-module (current-module))
1578 (dynamic-wind (lambda ()
1579 (set! outer-module (current-module))
1580 (set-current-module inner-module)
1581 (set! inner-module #f))
1584 (set! inner-module (current-module))
1585 (set-current-module outer-module)
1586 (set! outer-module #f)))))
1588 (define basic-load load)
1590 (define (load-module filename . reader)
1591 (save-module-excursion
1593 (let ((oldname (and (current-load-port)
1594 (port-filename (current-load-port)))))
1597 (> (string-length filename) 0)
1598 (not (char=? (string-ref filename 0) #\/))
1599 (not (string=? (dirname oldname) ".")))
1600 (string-append (dirname oldname) "/" filename)
1607 ;;; {MODULE-REF -- exported}
1610 ;; Returns the value of a variable called NAME in MODULE or any of its
1611 ;; used modules. If there is no such variable, then if the optional third
1612 ;; argument DEFAULT is present, it is returned; otherwise an error is signaled.
1614 (define (module-ref module name . rest)
1615 (let ((variable (module-variable module name)))
1616 (if (and variable (variable-bound? variable))
1617 (variable-ref variable)
1619 (error "No variable named" name 'in module)
1620 (car rest) ; default value
1623 ;; MODULE-SET! -- exported
1625 ;; Sets the variable called NAME in MODULE (or in a module that MODULE uses)
1626 ;; to VALUE; if there is no such variable, an error is signaled.
1628 (define (module-set! module name value)
1629 (let ((variable (module-variable module name)))
1631 (variable-set! variable value)
1632 (error "No variable named" name 'in module))))
1634 ;; MODULE-DEFINE! -- exported
1636 ;; Sets the variable called NAME in MODULE to VALUE; if there is no such
1637 ;; variable, it is added first.
1639 (define (module-define! module name value)
1640 (let ((variable (module-local-variable module name)))
1643 (variable-set! variable value)
1644 (module-modified module))
1645 (let ((variable (make-variable value)))
1646 (module-add! module name variable)))))
1648 ;; MODULE-DEFINED? -- exported
1650 ;; Return #t iff NAME is defined in MODULE (or in a module that MODULE
1653 (define (module-defined? module name)
1654 (let ((variable (module-variable module name)))
1655 (and variable (variable-bound? variable))))
1657 ;; MODULE-USE! module interface
1659 ;; Add INTERFACE to the list of interfaces used by MODULE.
1661 (define (module-use! module interface)
1662 (if (not (eq? module interface))
1664 ;; Newly used modules must be appended rather than consed, so that
1665 ;; `module-variable' traverses the use list starting from the first
1667 (set-module-uses! module
1668 (append (filter (lambda (m)
1670 (equal? (module-name m)
1671 (module-name interface))))
1672 (module-uses module))
1675 (module-modified module))))
1677 ;; MODULE-USE-INTERFACES! module interfaces
1679 ;; Same as MODULE-USE! but add multiple interfaces and check for duplicates
1681 (define (module-use-interfaces! module interfaces)
1682 (set-module-uses! module
1683 (append (module-uses module) interfaces))
1684 (module-modified module))
1688 ;;; {Recursive Namespaces}
1690 ;;; A hierarchical namespace emerges if we consider some module to be
1691 ;;; root, and variables bound to modules as nested namespaces.
1693 ;;; The routines in this file manage variable names in hierarchical namespace.
1694 ;;; Each variable name is a list of elements, looked up in successively nested
1697 ;;; (nested-ref some-root-module '(foo bar baz))
1698 ;;; => <value of a variable named baz in the module bound to bar in
1699 ;;; the module bound to foo in some-root-module>
1704 ;;; ;; a-root is a module
1705 ;;; ;; name is a list of symbols
1707 ;;; nested-ref a-root name
1708 ;;; nested-set! a-root name val
1709 ;;; nested-define! a-root name val
1710 ;;; nested-remove! a-root name
1713 ;;; (current-module) is a natural choice for a-root so for convenience there are
1716 ;;; local-ref name == nested-ref (current-module) name
1717 ;;; local-set! name val == nested-set! (current-module) name val
1718 ;;; local-define! name val == nested-define! (current-module) name val
1719 ;;; local-remove! name == nested-remove! (current-module) name
1723 (define (nested-ref root names)
1724 (let loop ((cur root)
1728 ((not (module? cur)) #f)
1729 (else (loop (module-ref cur (car elts) #f) (cdr elts))))))
1731 (define (nested-set! root names val)
1732 (let loop ((cur root)
1734 (if (null? (cdr elts))
1735 (module-set! cur (car elts) val)
1736 (loop (module-ref cur (car elts)) (cdr elts)))))
1738 (define (nested-define! root names val)
1739 (let loop ((cur root)
1741 (if (null? (cdr elts))
1742 (module-define! cur (car elts) val)
1743 (loop (module-ref cur (car elts)) (cdr elts)))))
1745 (define (nested-remove! root names)
1746 (let loop ((cur root)
1748 (if (null? (cdr elts))
1749 (module-remove! cur (car elts))
1750 (loop (module-ref cur (car elts)) (cdr elts)))))
1752 (define (local-ref names) (nested-ref (current-module) names))
1753 (define (local-set! names val) (nested-set! (current-module) names val))
1754 (define (local-define names val) (nested-define! (current-module) names val))
1755 (define (local-remove names) (nested-remove! (current-module) names))
1760 ;;; {The (%app) module}
1762 ;;; The root of conventionally named objects not directly in the top level.
1765 ;;; (%app modules guile)
1767 ;;; The directory of all modules and the standard root module.
1770 ;; module-public-interface is defined in C.
1771 (define (set-module-public-interface! m i)
1772 (module-define! m '%module-public-interface i))
1773 (define (set-system-module! m s)
1774 (set-procedure-property! (module-eval-closure m) 'system-module s))
1775 (define the-root-module (make-root-module))
1776 (define the-scm-module (make-scm-module))
1777 (set-module-public-interface! the-root-module the-scm-module)
1778 (set-module-name! the-root-module '(guile))
1779 (set-module-name! the-scm-module '(guile))
1780 (set-module-kind! the-scm-module 'interface)
1781 (set-system-module! the-root-module #t)
1782 (set-system-module! the-scm-module #t)
1784 ;; NOTE: This binding is used in libguile/modules.c.
1786 (define (make-modules-in module name)
1790 (let* ((var (module-local-variable module (car name)))
1791 (val (and var (variable-bound? var) (variable-ref var))))
1794 (let ((m (make-module 31)))
1795 (set-module-kind! m 'directory)
1796 (set-module-name! m (append (or (module-name module) '())
1798 (module-define! module (car name) m)
1802 (define (beautify-user-module! module)
1803 (let ((interface (module-public-interface module)))
1804 (if (or (not interface)
1805 (eq? interface module))
1806 (let ((interface (make-module 31)))
1807 (set-module-name! interface (module-name module))
1808 (set-module-kind! interface 'interface)
1809 (set-module-public-interface! module interface))))
1810 (if (and (not (memq the-scm-module (module-uses module)))
1811 (not (eq? module the-root-module)))
1812 ;; Import the default set of bindings (from the SCM module) in MODULE.
1813 (module-use! module the-scm-module)))
1815 ;; NOTE: This binding is used in libguile/modules.c.
1817 (define resolve-module
1818 (let ((the-root-module the-root-module))
1819 (lambda (name . maybe-autoload)
1820 (if (equal? name '(guile))
1822 (let ((full-name (append '(%app modules) name)))
1823 (let ((already (nested-ref the-root-module full-name))
1824 (autoload (or (null? maybe-autoload) (car maybe-autoload))))
1826 ((and already (module? already)
1827 (or (not autoload) (module-public-interface already)))
1828 ;; A hit, a palpable hit.
1831 ;; Try to autoload the module, and recurse.
1832 (try-load-module name)
1833 (resolve-module name #f))
1835 ;; A module is not bound (but maybe something else is),
1836 ;; we're not autoloading -- here's the weird semantics,
1837 ;; we create an empty module.
1838 (make-modules-in the-root-module full-name)))))))))
1840 ;; Cheat. These bindings are needed by modules.c, but we don't want
1841 ;; to move their real definition here because that would be unnatural.
1843 (define try-module-autoload #f)
1844 (define process-define-module #f)
1845 (define process-use-modules #f)
1846 (define module-export! #f)
1847 (define default-duplicate-binding-procedures #f)
1849 (define %app (make-module 31))
1850 (define app %app) ;; for backwards compatability
1852 (local-define '(%app modules) (make-module 31))
1853 (local-define '(%app modules guile) the-root-module)
1855 ;; This boots the module system. All bindings needed by modules.c
1856 ;; must have been defined by now.
1858 (set-current-module the-root-module)
1860 ;; (define-special-value '(%app modules new-ws) (lambda () (make-scm-module)))
1862 (define (try-load-module name)
1863 (or (begin-deprecated (try-module-linked name))
1864 (try-module-autoload name)
1865 (begin-deprecated (try-module-dynamic-link name))))
1867 (define (purify-module! module)
1868 "Removes bindings in MODULE which are inherited from the (guile) module."
1869 (let ((use-list (module-uses module)))
1870 (if (and (pair? use-list)
1871 (eq? (car (last-pair use-list)) the-scm-module))
1872 (set-module-uses! module (reverse (cdr (reverse use-list)))))))
1874 ;; Return a module that is an interface to the module designated by
1877 ;; `resolve-interface' takes four keyword arguments:
1879 ;; #:select SELECTION
1881 ;; SELECTION is a list of binding-specs to be imported; A binding-spec
1882 ;; is either a symbol or a pair of symbols (ORIG . SEEN), where ORIG
1883 ;; is the name in the used module and SEEN is the name in the using
1884 ;; module. Note that SEEN is also passed through RENAMER, below. The
1885 ;; default is to select all bindings. If you specify no selection but
1886 ;; a renamer, only the bindings that already exist in the used module
1887 ;; are made available in the interface. Bindings that are added later
1888 ;; are not picked up.
1892 ;; BINDINGS is a list of bindings which should not be imported.
1896 ;; PREFIX is a symbol that will be appended to each exported name.
1897 ;; The default is to not perform any renaming.
1899 ;; #:renamer RENAMER
1901 ;; RENAMER is a procedure that takes a symbol and returns its new
1902 ;; name. The default is not perform any renaming.
1904 ;; Signal "no code for module" error if module name is not resolvable
1905 ;; or its public interface is not available. Signal "no binding"
1906 ;; error if selected binding does not exist in the used module.
1908 (define (resolve-interface name . args)
1910 (define (get-keyword-arg args kw def)
1911 (cond ((memq kw args)
1913 (if (null? (cdr kw-arg))
1914 (error "keyword without value: " kw))
1919 (let* ((select (get-keyword-arg args #:select #f))
1920 (hide (get-keyword-arg args #:hide '()))
1921 (renamer (or (get-keyword-arg args #:renamer #f)
1922 (let ((prefix (get-keyword-arg args #:prefix #f)))
1923 (and prefix (symbol-prefix-proc prefix)))
1925 (module (resolve-module name))
1926 (public-i (and module (module-public-interface module))))
1927 (and (or (not module) (not public-i))
1928 (error "no code for module" name))
1929 (if (and (not select) (null? hide) (eq? renamer identity))
1931 (let ((selection (or select (module-map (lambda (sym var) sym)
1933 (custom-i (make-module 31)))
1934 (set-module-kind! custom-i 'custom-interface)
1935 (set-module-name! custom-i name)
1936 ;; XXX - should use a lazy binder so that changes to the
1937 ;; used module are picked up automatically.
1938 (for-each (lambda (bspec)
1939 (let* ((direct? (symbol? bspec))
1940 (orig (if direct? bspec (car bspec)))
1941 (seen (if direct? bspec (cdr bspec)))
1942 (var (or (module-local-variable public-i orig)
1943 (module-local-variable module orig)
1945 ;; fixme: format manually for now
1947 #f "no binding `~A' in module ~A"
1949 (if (memq orig hide)
1950 (set! hide (delq! orig hide))
1951 (module-add! custom-i
1955 ;; Check that we are not hiding bindings which don't exist
1956 (for-each (lambda (binding)
1957 (if (not (module-local-variable public-i binding))
1960 #f "no binding `~A' to hide in module ~A"
1965 (define (symbol-prefix-proc prefix)
1967 (symbol-append prefix symbol)))
1969 ;; This function is called from "modules.c". If you change it, be
1970 ;; sure to update "modules.c" as well.
1972 (define (process-define-module args)
1973 (let* ((module-id (car args))
1974 (module (resolve-module module-id #f))
1976 (unrecognized (lambda (arg)
1977 (error "unrecognized define-module argument" arg))))
1978 (beautify-user-module! module)
1979 (let loop ((kws kws)
1980 (reversed-interfaces '())
1987 (call-with-deferred-observers
1989 (module-use-interfaces! module (reverse reversed-interfaces))
1990 (module-export! module exports)
1991 (module-replace! module replacements)
1992 (module-re-export! module re-exports)
1993 (if (not (null? autoloads))
1994 (apply module-autoload! module autoloads))))
1996 ((#:use-module #:use-syntax)
1997 (or (pair? (cdr kws))
1999 (let* ((interface-args (cadr kws))
2000 (interface (apply resolve-interface interface-args)))
2001 (and (eq? (car kws) #:use-syntax)
2002 (or (symbol? (caar interface-args))
2003 (error "invalid module name for use-syntax"
2004 (car interface-args)))
2005 (set-module-transformer!
2007 (module-ref interface
2008 (car (last-pair (car interface-args)))
2011 (cons interface reversed-interfaces)
2017 (or (and (pair? (cdr kws)) (pair? (cddr kws)))
2024 (let ((name (cadr kws))
2025 (bindings (caddr kws)))
2026 (cons* name bindings autoloads))))
2028 (set-system-module! module #t)
2029 (loop (cdr kws) reversed-interfaces exports re-exports
2030 replacements autoloads))
2032 (purify-module! module)
2033 (loop (cdr kws) reversed-interfaces exports re-exports
2034 replacements autoloads))
2036 (if (not (pair? (cdr kws)))
2038 (set-module-duplicates-handlers!
2040 (lookup-duplicates-handlers (cadr kws)))
2041 (loop (cddr kws) reversed-interfaces exports re-exports
2042 replacements autoloads))
2043 ((#:export #:export-syntax)
2044 (or (pair? (cdr kws))
2048 (append (cadr kws) exports)
2052 ((#:re-export #:re-export-syntax)
2053 (or (pair? (cdr kws))
2058 (append (cadr kws) re-exports)
2061 ((#:replace #:replace-syntax)
2062 (or (pair? (cdr kws))
2068 (append (cadr kws) replacements)
2071 (unrecognized kws)))))
2072 (run-hook module-defined-hook module)
2075 ;; `module-defined-hook' is a hook that is run whenever a new module
2076 ;; is defined. Its members are called with one argument, the new
2078 (define module-defined-hook (make-hook 1))
2085 (define (make-autoload-interface module name bindings)
2086 (let ((b (lambda (a sym definep)
2087 (and (memq sym bindings)
2088 (let ((i (module-public-interface (resolve-module name))))
2090 (error "missing interface for module" name))
2091 (let ((autoload (memq a (module-uses module))))
2092 ;; Replace autoload-interface with actual interface if
2093 ;; that has not happened yet.
2094 (if (pair? autoload)
2095 (set-car! autoload i)))
2096 (module-local-variable i sym))))))
2097 (module-constructor (make-hash-table 0) '() b #f #f name 'autoload #f
2098 (make-hash-table 0) '() (make-weak-value-hash-table 31))))
2100 (define (module-autoload! module . args)
2101 "Have @var{module} automatically load the module named @var{name} when one
2102 of the symbols listed in @var{bindings} is looked up. @var{args} should be a
2103 list of module-name/binding-list pairs, e.g., as in @code{(module-autoload!
2104 module '(ice-9 q) '(make-q q-length))}."
2105 (let loop ((args args))
2109 (error "invalid name+binding autoload list" args))
2111 (let ((name (car args))
2112 (bindings (cadr args)))
2113 (module-use! module (make-autoload-interface module
2115 (loop (cddr args)))))))
2118 ;;; {Compiled module}
2120 (if (not (defined? 'load-compiled))
2121 (define load-compiled #f))
2125 ;;; {Autoloading modules}
2128 (define autoloads-in-progress '())
2130 ;; This function is called from "modules.c". If you change it, be
2131 ;; sure to update "modules.c" as well.
2133 (define (try-module-autoload module-name)
2134 (let* ((reverse-name (reverse module-name))
2135 (name (symbol->string (car reverse-name)))
2136 (dir-hint-module-name (reverse (cdr reverse-name)))
2137 (dir-hint (apply string-append
2139 (string-append (symbol->string elt) "/"))
2140 dir-hint-module-name))))
2141 (resolve-module dir-hint-module-name #f)
2142 (and (not (autoload-done-or-in-progress? dir-hint name))
2144 (define (load-file proc file)
2145 (save-module-excursion (lambda () (proc file)))
2148 (lambda () (autoload-in-progress! dir-hint name))
2150 (let ((file (in-vicinity dir-hint name)))
2151 (let ((compiled (and load-compiled
2153 (string-append file ".go"))))
2154 (source (%search-load-path file)))
2157 (< (stat:mtime (stat compiled))
2158 (stat:mtime (stat source)))))
2160 (warn "source file" source "newer than" compiled))
2161 (with-fluids ((current-reader #f))
2162 (load-file primitive-load source)))
2164 (load-file load-compiled compiled))))))
2165 (lambda () (set-autoloaded! dir-hint name didit)))
2170 ;;; {Dynamic linking of modules}
2173 (define autoloads-done '((guile . guile)))
2175 (define (autoload-done-or-in-progress? p m)
2176 (let ((n (cons p m)))
2177 (->bool (or (member n autoloads-done)
2178 (member n autoloads-in-progress)))))
2180 (define (autoload-done! p m)
2181 (let ((n (cons p m)))
2182 (set! autoloads-in-progress
2183 (delete! n autoloads-in-progress))
2184 (or (member n autoloads-done)
2185 (set! autoloads-done (cons n autoloads-done)))))
2187 (define (autoload-in-progress! p m)
2188 (let ((n (cons p m)))
2189 (set! autoloads-done
2190 (delete! n autoloads-done))
2191 (set! autoloads-in-progress (cons n autoloads-in-progress))))
2193 (define (set-autoloaded! p m done?)
2195 (autoload-done! p m)
2196 (let ((n (cons p m)))
2197 (set! autoloads-done (delete! n autoloads-done))
2198 (set! autoloads-in-progress (delete! n autoloads-in-progress)))))
2202 ;;; {Run-time options}
2205 (defmacro define-option-interface (option-group)
2206 (let* ((option-name car)
2208 (option-documentation caddr)
2210 ;; Below follow the macros defining the run-time option interfaces.
2212 (make-options (lambda (interface)
2214 (cond ((null? args) (,interface))
2216 (,interface (car args)) (,interface))
2219 (display (option-name option))
2220 (if (< (string-length
2221 (symbol->string (option-name option)))
2225 (display (option-value option))
2227 (display (option-documentation option))
2229 (,interface #t)))))))
2231 (make-enable (lambda (interface)
2233 (,interface (append flags (,interface)))
2236 (make-disable (lambda (interface)
2238 (let ((options (,interface)))
2239 (for-each (lambda (flag)
2240 (set! options (delq! flag options)))
2242 (,interface options)
2244 (let* ((interface (car option-group))
2245 (options/enable/disable (cadr option-group)))
2247 (define ,(car options/enable/disable)
2248 ,(make-options interface))
2249 (define ,(cadr options/enable/disable)
2250 ,(make-enable interface))
2251 (define ,(caddr options/enable/disable)
2252 ,(make-disable interface))
2253 (defmacro ,(caaddr option-group) (opt val)
2254 `(,',(car options/enable/disable)
2255 (append (,',(car options/enable/disable))
2256 (list ',opt ,val))))))))
2258 (define-option-interface
2259 (eval-options-interface
2260 (eval-options eval-enable eval-disable)
2263 (define-option-interface
2264 (debug-options-interface
2265 (debug-options debug-enable debug-disable)
2268 (define-option-interface
2269 (evaluator-traps-interface
2270 (traps trap-enable trap-disable)
2273 (define-option-interface
2274 (read-options-interface
2275 (read-options read-enable read-disable)
2278 (define-option-interface
2279 (print-options-interface
2280 (print-options print-enable print-disable)
2288 (define (repl read evaler print)
2289 (let loop ((source (read (current-input-port))))
2290 (print (evaler source))
2291 (loop (read (current-input-port)))))
2293 ;; A provisional repl that acts like the SCM repl:
2295 (define scm-repl-silent #f)
2296 (define (assert-repl-silence v) (set! scm-repl-silent v))
2298 (define *unspecified* (if #f #f))
2299 (define (unspecified? v) (eq? v *unspecified*))
2301 (define scm-repl-print-unspecified #f)
2302 (define (assert-repl-print-unspecified v) (set! scm-repl-print-unspecified v))
2304 (define scm-repl-verbose #f)
2305 (define (assert-repl-verbosity v) (set! scm-repl-verbose v))
2307 (define scm-repl-prompt "guile> ")
2309 (define (set-repl-prompt! v) (set! scm-repl-prompt v))
2311 (define (default-pre-unwind-handler key . args)
2312 (save-stack pre-unwind-handler-dispatch)
2313 (apply throw key args))
2315 (define (pre-unwind-handler-dispatch key . args)
2316 (apply default-pre-unwind-handler key args))
2318 (define abort-hook (make-hook))
2320 ;; these definitions are used if running a script.
2321 ;; otherwise redefined in error-catching-loop.
2322 (define (set-batch-mode?! arg) #t)
2323 (define (batch-mode?) #t)
2325 (define (error-catching-loop thunk)
2328 (define (loop first)
2333 (call-with-unblocked-asyncs
2339 ;; This line is needed because mark
2340 ;; doesn't do closures quite right.
2341 ;; Unreferenced locals should be
2344 (let loop ((v (thunk)))
2348 (lambda (key . args)
2355 (apply throw 'switch-repl args))
2358 ;; This is one of the closures that require
2359 ;; (set! first #f) above
2362 (run-hook abort-hook)
2363 (force-output (current-output-port))
2364 (display "ABORT: " (current-error-port))
2365 (write args (current-error-port))
2366 (newline (current-error-port))
2370 (not has-shown-debugger-hint?)
2371 (not (memq 'backtrace
2372 (debug-options-interface)))
2373 (stack? (fluid-ref the-last-stack)))
2375 (newline (current-error-port))
2377 "Type \"(backtrace)\" to get more information or \"(debug)\" to enter the debugger.\n"
2378 (current-error-port))
2379 (set! has-shown-debugger-hint? #t)))
2380 (force-output (current-error-port)))
2382 (primitive-exit 1)))
2383 (set! stack-saved? #f)))
2386 ;; This is the other cons-leak closure...
2388 (cond ((= (length args) 4)
2389 (apply handle-system-error key args))
2391 (apply bad-throw key args)))))))
2393 ;; Note that having just `pre-unwind-handler-dispatch'
2394 ;; here is connected with the mechanism that
2395 ;; produces a nice backtrace upon error. If, for
2396 ;; example, this is replaced with (lambda args
2397 ;; (apply pre-unwind-handler-dispatch args)), the stack
2398 ;; cutting (in save-stack) goes wrong and ends up
2399 ;; saving no stack at all, so there is no
2401 pre-unwind-handler-dispatch)))
2403 (if next (loop next) status)))
2404 (set! set-batch-mode?! (lambda (arg)
2406 (set! interactive #f)
2409 (error "sorry, not implemented")))))
2410 (set! batch-mode? (lambda () (not interactive)))
2411 (call-with-blocked-asyncs
2412 (lambda () (loop (lambda () #t))))))
2414 ;;(define the-last-stack (make-fluid)) Defined by scm_init_backtrace ()
2415 (define before-signal-stack (make-fluid))
2416 (define stack-saved? #f)
2418 (define (save-stack . narrowing)
2420 (cond ((not (memq 'debug (debug-options-interface)))
2421 (fluid-set! the-last-stack #f)
2422 (set! stack-saved? #t))
2428 (apply make-stack #t save-stack primitive-eval #t 0 narrowing))
2430 (apply make-stack #t save-stack 0 #t 0 narrowing))
2432 (apply make-stack #t save-stack tk-stack-mark #t 0 narrowing))
2434 (apply make-stack #t save-stack 0 1 narrowing))
2436 (let ((id (stack-id #t)))
2437 (and (procedure? id)
2438 (apply make-stack #t save-stack id #t 0 narrowing))))))
2439 (set! stack-saved? #t)))))
2441 (define before-error-hook (make-hook))
2442 (define after-error-hook (make-hook))
2443 (define before-backtrace-hook (make-hook))
2444 (define after-backtrace-hook (make-hook))
2446 (define has-shown-debugger-hint? #f)
2448 (define (handle-system-error key . args)
2449 (let ((cep (current-error-port)))
2450 (cond ((not (stack? (fluid-ref the-last-stack))))
2451 ((memq 'backtrace (debug-options-interface))
2452 (let ((highlights (if (or (eq? key 'wrong-type-arg)
2453 (eq? key 'out-of-range))
2456 (run-hook before-backtrace-hook)
2458 (display "Backtrace:\n")
2459 (display-backtrace (fluid-ref the-last-stack) cep
2462 (run-hook after-backtrace-hook))))
2463 (run-hook before-error-hook)
2464 (apply display-error (fluid-ref the-last-stack) cep args)
2465 (run-hook after-error-hook)
2467 (throw 'abort key)))
2469 (define (quit . args)
2470 (apply throw 'quit args))
2474 ;;(define has-shown-backtrace-hint? #f) Defined by scm_init_backtrace ()
2476 ;; Replaced by C code:
2477 ;;(define (backtrace)
2478 ;; (if (fluid-ref the-last-stack)
2481 ;; (display-backtrace (fluid-ref the-last-stack) (current-output-port))
2483 ;; (if (and (not has-shown-backtrace-hint?)
2484 ;; (not (memq 'backtrace (debug-options-interface))))
2487 ;;"Type \"(debug-enable 'backtrace)\" if you would like a backtrace
2488 ;;automatically if an error occurs in the future.\n")
2489 ;; (set! has-shown-backtrace-hint? #t))))
2490 ;; (display "No backtrace available.\n")))
2492 (define (error-catching-repl r e p)
2493 (error-catching-loop
2495 (call-with-values (lambda () (e (r)))
2496 (lambda the-values (for-each p the-values))))))
2498 (define (gc-run-time)
2499 (cdr (assq 'gc-time-taken (gc-stats))))
2501 (define before-read-hook (make-hook))
2502 (define after-read-hook (make-hook))
2503 (define before-eval-hook (make-hook 1))
2504 (define after-eval-hook (make-hook 1))
2505 (define before-print-hook (make-hook 1))
2506 (define after-print-hook (make-hook 1))
2508 ;;; The default repl-reader function. We may override this if we've
2509 ;;; the readline library.
2512 (display (if (string? prompt) prompt (prompt)))
2514 (run-hook before-read-hook)
2515 ((or (fluid-ref current-reader) read) (current-input-port))))
2517 (define (scm-style-repl)
2522 (repl-report-start-timing (lambda ()
2523 (set! start-gc-rt (gc-run-time))
2524 (set! start-rt (get-internal-run-time))))
2525 (repl-report (lambda ()
2527 (display (inexact->exact
2528 (* 1000 (/ (- (get-internal-run-time) start-rt)
2529 internal-time-units-per-second))))
2531 (display (inexact->exact
2532 (* 1000 (/ (- (gc-run-time) start-gc-rt)
2533 internal-time-units-per-second))))
2534 (display " msec in gc)\n")))
2536 (consume-trailing-whitespace
2538 (let ((ch (peek-char)))
2541 ((or (char=? ch #\space) (char=? ch #\tab))
2543 (consume-trailing-whitespace))
2544 ((char=? ch #\newline)
2548 (let ((prompt (cond ((string? scm-repl-prompt)
2550 ((thunk? scm-repl-prompt)
2552 (scm-repl-prompt "> ")
2554 (repl-reader prompt))))
2556 ;; As described in R4RS, the READ procedure updates the
2557 ;; port to point to the first character past the end of
2558 ;; the external representation of the object. This
2559 ;; means that it doesn't consume the newline typically
2560 ;; found after an expression. This means that, when
2561 ;; debugging Guile with GDB, GDB gets the newline, which
2562 ;; it often interprets as a "continue" command, making
2563 ;; breakpoints kind of useless. So, consume any
2564 ;; trailing newline here, as well as any whitespace
2566 ;; But not if EOF, for control-D.
2567 (if (not (eof-object? val))
2568 (consume-trailing-whitespace))
2569 (run-hook after-read-hook)
2570 (if (eof-object? val)
2572 (repl-report-start-timing)
2573 (if scm-repl-verbose
2576 (display ";;; EOF -- quitting")
2581 (-eval (lambda (sourc)
2582 (repl-report-start-timing)
2583 (run-hook before-eval-hook sourc)
2584 (let ((val (start-stack 'repl-stack
2585 ;; If you change this procedure
2586 ;; (primitive-eval), please also
2587 ;; modify the repl-stack case in
2588 ;; save-stack so that stack cutting
2589 ;; continues to work.
2590 (primitive-eval sourc))))
2591 (run-hook after-eval-hook sourc)
2595 (-print (let ((maybe-print (lambda (result)
2596 (if (or scm-repl-print-unspecified
2597 (not (unspecified? result)))
2602 (if (not scm-repl-silent)
2604 (run-hook before-print-hook result)
2605 (maybe-print result)
2606 (run-hook after-print-hook result)
2607 (if scm-repl-verbose
2611 (-quit (lambda (args)
2612 (if scm-repl-verbose
2614 (display ";;; QUIT executed, repl exitting")
2620 (if scm-repl-verbose
2622 (display ";;; ABORT executed.")
2625 (repl -read -eval -print))))
2627 (let ((status (error-catching-repl -read
2635 ;;; {IOTA functions: generating lists of numbers}
2639 (let loop ((count (1- n)) (result '()))
2640 (if (< count 0) result
2641 (loop (1- count) (cons count result)))))
2647 ;;; Similar to `begin' but returns a list of the results of all constituent
2648 ;;; forms instead of the result of the last form.
2649 ;;; (The definition relies on the current left-to-right
2650 ;;; order of evaluation of operands in applications.)
2653 (defmacro collect forms
2661 ;; with-fluids is a convenience wrapper for the builtin procedure
2662 ;; `with-fluids*'. The syntax is just like `let':
2664 ;; (with-fluids ((fluid val)
2668 (defmacro with-fluids (bindings . body)
2669 (let ((fluids (map car bindings))
2670 (values (map cadr bindings)))
2671 (if (and (= (length fluids) 1) (= (length values) 1))
2672 `(with-fluid* ,(car fluids) ,(car values) (lambda () ,@body))
2673 `(with-fluids* (list ,@fluids) (list ,@values)
2674 (lambda () ,@body)))))
2681 ;; actually....hobbit might be able to hack these with a little
2685 (define (primitive-macro? m)
2687 (not (macro-transformer m))))
2689 (defmacro define-macro (first . rest)
2690 (let ((name (if (symbol? first) first (car first)))
2694 `(lambda ,(cdr first) ,@rest))))
2697 (define ,name (defmacro:transformer ,transformer)))))
2704 ;;; with `continue' and `break'.
2707 ;; The inner `do' loop avoids re-establishing a catch every iteration,
2708 ;; that's only necessary if continue is actually used. A new key is
2709 ;; generated every time, so break and continue apply to their originating
2710 ;; `while' even when recursing.
2712 ;; FIXME: This macro is unintentionally unhygienic with respect to let,
2713 ;; make-symbol, do, throw, catch, lambda, and not.
2715 (define-macro (while cond . body)
2716 (let ((keyvar (make-symbol "while-keyvar")))
2717 `(let ((,keyvar (make-symbol "while-key")))
2721 (let ((break (lambda () (throw ,keyvar #t)))
2722 (continue (lambda () (throw ,keyvar #f))))
2733 ;;; {Module System Macros}
2736 ;; Return a list of expressions that evaluate to the appropriate
2737 ;; arguments for resolve-interface according to SPEC.
2741 (if (memq 'prefix (read-options))
2742 (error "boot-9 must be compiled with #:kw, not :kw")))
2744 (define (compile-interface-spec spec)
2745 (define (make-keyarg sym key quote?)
2746 (cond ((or (memq sym spec)
2750 (list key (list 'quote (cadr rest)))
2751 (list key (cadr rest)))))
2754 (define (map-apply func list)
2755 (map (lambda (args) (apply func args)) list))
2758 '((:select #:select #t)
2760 (:prefix #:prefix #t)
2761 (:renamer #:renamer #f)))
2762 (if (not (pair? (car spec)))
2765 ,@(apply append (map-apply make-keyarg keys)))))
2767 (define (keyword-like-symbol->keyword sym)
2768 (symbol->keyword (string->symbol (substring (symbol->string sym) 1))))
2770 (define (compile-define-module-args args)
2771 ;; Just quote everything except #:use-module and #:use-syntax. We
2772 ;; need to know about all arguments regardless since we want to turn
2773 ;; symbols that look like keywords into real keywords, and the
2774 ;; keyword args in a define-module form are not regular
2775 ;; (i.e. no-backtrace doesn't take a value).
2776 (let loop ((compiled-args `((quote ,(car args))))
2779 (reverse! compiled-args))
2780 ;; symbol in keyword position
2781 ((symbol? (car args))
2783 (cons (keyword-like-symbol->keyword (car args)) (cdr args))))
2784 ((memq (car args) '(#:no-backtrace #:pure))
2785 (loop (cons (car args) compiled-args)
2788 (error "keyword without value:" (car args)))
2789 ((memq (car args) '(#:use-module #:use-syntax))
2790 (loop (cons* `(list ,@(compile-interface-spec (cadr args)))
2794 ((eq? (car args) #:autoload)
2795 (loop (cons* `(quote ,(caddr args))
2796 `(quote ,(cadr args))
2801 (loop (cons* `(quote ,(cadr args))
2806 (defmacro define-module args
2809 (let ((m (process-define-module
2810 (list ,@(compile-define-module-args args)))))
2811 (set-current-module m)
2814 ;; The guts of the use-modules macro. Add the interfaces of the named
2815 ;; modules to the use-list of the current module, in order.
2817 ;; This function is called by "modules.c". If you change it, be sure
2818 ;; to change scm_c_use_module as well.
2820 (define (process-use-modules module-interface-args)
2821 (let ((interfaces (map (lambda (mif-args)
2822 (or (apply resolve-interface mif-args)
2823 (error "no such module" mif-args)))
2824 module-interface-args)))
2825 (call-with-deferred-observers
2827 (module-use-interfaces! (current-module) interfaces)))))
2829 (defmacro use-modules modules
2832 (process-use-modules
2833 (list ,@(map (lambda (m)
2834 `(list ,@(compile-interface-spec m)))
2838 (defmacro use-syntax (spec)
2842 `((process-use-modules (list
2843 (list ,@(compile-interface-spec spec))))
2844 (set-module-transformer! (current-module)
2845 ,(car (last-pair spec))))
2846 `((set-module-transformer! (current-module) ,spec)))
2849 ;; Dirk:FIXME:: This incorrect (according to R5RS) syntax needs to be changed
2850 ;; as soon as guile supports hygienic macros.
2851 (define define-private define)
2853 (defmacro define-public args
2855 (error "bad syntax" (list 'define-public args)))
2856 (define (defined-name n)
2859 ((pair? n) (defined-name (car n)))
2865 (let ((name (defined-name (car args))))
2867 (define-private ,@args)
2870 (defmacro defmacro-public args
2872 (error "bad syntax" (list 'defmacro-public args)))
2873 (define (defined-name n)
2881 (let ((name (defined-name (car args))))
2883 (export-syntax ,name)
2884 (defmacro ,@args))))))
2886 ;; Export a local variable
2888 ;; This function is called from "modules.c". If you change it, be
2889 ;; sure to update "modules.c" as well.
2891 (define (module-export! m names)
2892 (let ((public-i (module-public-interface m)))
2893 (for-each (lambda (name)
2894 (let ((var (module-ensure-local-variable! m name)))
2895 (module-add! public-i name var)))
2898 (define (module-replace! m names)
2899 (let ((public-i (module-public-interface m)))
2900 (for-each (lambda (name)
2901 (let ((var (module-ensure-local-variable! m name)))
2902 (set-object-property! var 'replace #t)
2903 (module-add! public-i name var)))
2906 ;; Re-export a imported variable
2908 (define (module-re-export! m names)
2909 (let ((public-i (module-public-interface m)))
2910 (for-each (lambda (name)
2911 (let ((var (module-variable m name)))
2913 (error "Undefined variable:" name))
2914 ((eq? var (module-local-variable m name))
2915 (error "re-exporting local variable:" name))
2917 (module-add! public-i name var)))))
2920 (defmacro export names
2921 `(call-with-deferred-observers
2923 (module-export! (current-module) ',names))))
2925 (defmacro re-export names
2926 `(call-with-deferred-observers
2928 (module-re-export! (current-module) ',names))))
2930 (defmacro export-syntax names
2933 (defmacro re-export-syntax names
2934 `(re-export ,@names))
2936 (define load load-module)
2938 ;; The following macro allows one to write, for example,
2940 ;; (@ (ice-9 pretty-print) pretty-print)
2942 ;; to refer directly to the pretty-print variable in module (ice-9
2943 ;; pretty-print). It works by looking up the variable and inserting
2944 ;; it directly into the code. This is understood by the evaluator.
2945 ;; Indeed, all references to global variables are memoized into such
2946 ;; variable objects.
2948 (define-macro (@ mod-name var-name)
2949 (let ((var (module-variable (resolve-interface mod-name) var-name)))
2951 (error "no such public variable" (list '@ mod-name var-name)))
2954 ;; The '@@' macro is like '@' but it can also access bindings that
2955 ;; have not been explicitely exported.
2957 (define-macro (@@ mod-name var-name)
2958 (let ((var (module-variable (resolve-module mod-name) var-name)))
2960 (error "no such variable" (list '@@ mod-name var-name)))
2965 ;;; {Compiler interface}
2967 ;;; The full compiler interface can be found in (system). Here we put a
2968 ;;; few useful procedures into the global namespace.
2970 (module-autoload! the-scm-module
2971 '(system base compile)
2973 compile-time-environment))
2981 (define make-mutable-parameter
2982 (let ((make (lambda (fluid converter)
2986 (fluid-set! fluid (converter (car args))))))))
2987 (lambda (init . converter)
2988 (let ((fluid (make-fluid))
2989 (converter (if (null? converter)
2992 (fluid-set! fluid (converter init))
2993 (make fluid converter)))))
2997 ;;; {Handling of duplicate imported bindings}
3000 ;; Duplicate handlers take the following arguments:
3002 ;; module importing module
3003 ;; name conflicting name
3004 ;; int1 old interface where name occurs
3005 ;; val1 value of binding in old interface
3006 ;; int2 new interface where name occurs
3007 ;; val2 value of binding in new interface
3008 ;; var previous resolution or #f
3009 ;; val value of previous resolution
3011 ;; A duplicate handler can take three alternative actions:
3013 ;; 1. return #f => leave responsibility to next handler
3014 ;; 2. exit with an error
3015 ;; 3. return a variable resolving the conflict
3018 (define duplicate-handlers
3019 (let ((m (make-module 7)))
3021 (define (check module name int1 val1 int2 val2 var val)
3022 (scm-error 'misc-error
3024 "~A: `~A' imported from both ~A and ~A"
3025 (list (module-name module)
3031 (define (warn module name int1 val1 int2 val2 var val)
3032 (format (current-error-port)
3033 "WARNING: ~A: `~A' imported from both ~A and ~A\n"
3034 (module-name module)
3040 (define (replace module name int1 val1 int2 val2 var val)
3041 (let ((old (or (and var (object-property var 'replace) var)
3042 (module-variable int1 name)))
3043 (new (module-variable int2 name)))
3044 (if (object-property old 'replace)
3045 (and (or (eq? old new)
3046 (not (object-property new 'replace)))
3048 (and (object-property new 'replace)
3051 (define (warn-override-core module name int1 val1 int2 val2 var val)
3052 (and (eq? int1 the-scm-module)
3054 (format (current-error-port)
3055 "WARNING: ~A: imported module ~A overrides core binding `~A'\n"
3056 (module-name module)
3059 (module-local-variable int2 name))))
3061 (define (first module name int1 val1 int2 val2 var val)
3062 (or var (module-local-variable int1 name)))
3064 (define (last module name int1 val1 int2 val2 var val)
3065 (module-local-variable int2 name))
3067 (define (noop module name int1 val1 int2 val2 var val)
3070 (set-module-name! m 'duplicate-handlers)
3071 (set-module-kind! m 'interface)
3072 (module-define! m 'check check)
3073 (module-define! m 'warn warn)
3074 (module-define! m 'replace replace)
3075 (module-define! m 'warn-override-core warn-override-core)
3076 (module-define! m 'first first)
3077 (module-define! m 'last last)
3078 (module-define! m 'merge-generics noop)
3079 (module-define! m 'merge-accessors noop)
3082 (define (lookup-duplicates-handlers handler-names)
3084 (map (lambda (handler-name)
3085 (or (module-symbol-local-binding
3086 duplicate-handlers handler-name #f)
3087 (error "invalid duplicate handler name:"
3089 (if (list? handler-names)
3091 (list handler-names)))))
3093 (define default-duplicate-binding-procedures
3094 (make-mutable-parameter #f))
3096 (define default-duplicate-binding-handler
3097 (make-mutable-parameter '(replace warn-override-core warn last)
3098 (lambda (handler-names)
3099 (default-duplicate-binding-procedures
3100 (lookup-duplicates-handlers handler-names))
3105 ;;; {`cond-expand' for SRFI-0 support.}
3107 ;;; This syntactic form expands into different commands or
3108 ;;; definitions, depending on the features provided by the Scheme
3114 ;;; --> (cond-expand <cond-expand-clause>+)
3115 ;;; | (cond-expand <cond-expand-clause>* (else <command-or-definition>))
3116 ;;; <cond-expand-clause>
3117 ;;; --> (<feature-requirement> <command-or-definition>*)
3118 ;;; <feature-requirement>
3119 ;;; --> <feature-identifier>
3120 ;;; | (and <feature-requirement>*)
3121 ;;; | (or <feature-requirement>*)
3122 ;;; | (not <feature-requirement>)
3123 ;;; <feature-identifier>
3124 ;;; --> <a symbol which is the name or alias of a SRFI>
3126 ;;; Additionally, this implementation provides the
3127 ;;; <feature-identifier>s `guile' and `r5rs', so that programs can
3128 ;;; determine the implementation type and the supported standard.
3130 ;;; Currently, the following feature identifiers are supported:
3132 ;;; guile r5rs srfi-0 srfi-4 srfi-6 srfi-13 srfi-14 srfi-55 srfi-61
3134 ;;; Remember to update the features list when adding more SRFIs.
3137 (define %cond-expand-features
3138 ;; Adjust the above comment when changing this.
3141 srfi-0 ;; cond-expand itself
3142 srfi-4 ;; homogenous numeric vectors
3143 srfi-6 ;; open-input-string etc, in the guile core
3144 srfi-13 ;; string library
3145 srfi-14 ;; character sets
3146 srfi-55 ;; require-extension
3147 srfi-61 ;; general cond clause
3150 ;; This table maps module public interfaces to the list of features.
3152 (define %cond-expand-table (make-hash-table 31))
3154 ;; Add one or more features to the `cond-expand' feature list of the
3157 (define (cond-expand-provide module features)
3158 (let ((mod (module-public-interface module)))
3160 (hashq-set! %cond-expand-table mod
3161 (append (hashq-ref %cond-expand-table mod '())
3165 (procedure->memoizing-macro
3167 (let ((clauses (cdr exp))
3168 (syntax-error (lambda (cl)
3169 (error "invalid clause in `cond-expand'" cl))))
3175 (or (memq clause %cond-expand-features)
3176 (let lp ((uses (module-uses (env-module env))))
3179 (hashq-ref %cond-expand-table
3185 ((eq? 'and (car clause))
3186 (let lp ((l (cdr clause)))
3190 (and (test-clause (car l)) (lp (cdr l))))
3192 (syntax-error clause)))))
3193 ((eq? 'or (car clause))
3194 (let lp ((l (cdr clause)))
3198 (or (test-clause (car l)) (lp (cdr l))))
3200 (syntax-error clause)))))
3201 ((eq? 'not (car clause))
3202 (cond ((not (pair? (cdr clause)))
3203 (syntax-error clause))
3204 ((pair? (cddr clause))
3205 ((syntax-error clause))))
3206 (not (test-clause (cadr clause))))
3208 (syntax-error clause))))
3210 (syntax-error clause))))))
3211 (let lp ((c clauses))
3214 (error "Unfulfilled `cond-expand'"))
3217 ((not (pair? (car c)))
3218 (syntax-error (car c)))
3219 ((test-clause (caar c))
3220 `(begin ,@(cdar c)))
3221 ((eq? (caar c) 'else)
3224 `(begin ,@(cdar c)))
3226 (lp (cdr c))))))))))
3228 ;; This procedure gets called from the startup code with a list of
3229 ;; numbers, which are the numbers of the SRFIs to be loaded on startup.
3231 (define (use-srfis srfis)
3232 (process-use-modules
3234 (list (list 'srfi (string->symbol
3235 (string-append "srfi-" (number->string num))))))
3240 ;;; srfi-55: require-extension
3243 (define-macro (require-extension extension-spec)
3244 ;; This macro only handles the srfi extension, which, at present, is
3245 ;; the only one defined by the standard.
3246 (if (not (pair? extension-spec))
3247 (scm-error 'wrong-type-arg "require-extension"
3248 "Not an extension: ~S" (list extension-spec) #f))
3249 (let ((extension (car extension-spec))
3250 (extension-args (cdr extension-spec)))
3253 (let ((use-list '()))
3256 (if (not (integer? i))
3257 (scm-error 'wrong-type-arg "require-extension"
3258 "Invalid srfi name: ~S" (list i) #f))
3259 (let ((srfi-sym (string->symbol
3260 (string-append "srfi-" (number->string i)))))
3261 (if (not (memq srfi-sym %cond-expand-features))
3262 (set! use-list (cons `(use-modules (srfi ,srfi-sym))
3265 (if (pair? use-list)
3266 ;; i.e. (begin (use-modules x) (use-modules y) (use-modules z))
3267 `(begin ,@(reverse! use-list)))))
3270 'wrong-type-arg "require-extension"
3271 "Not a recognized extension type: ~S" (list extension) #f)))))
3275 ;;; {Load emacs interface support if emacs option is given.}
3278 (define (named-module-use! user usee)
3279 (module-use! (resolve-module user) (resolve-interface usee)))
3281 (define (load-emacs-interface)
3282 (and (provided? 'debug-extensions)
3283 (debug-enable 'backtrace))
3284 (named-module-use! '(guile-user) '(ice-9 emacs)))
3288 (define using-readline?
3289 (let ((using-readline? (make-fluid)))
3290 (make-procedure-with-setter
3291 (lambda () (fluid-ref using-readline?))
3292 (lambda (v) (fluid-set! using-readline? v)))))
3295 (let ((guile-user-module (resolve-module '(guile-user))))
3297 ;; Load emacs interface support if emacs option is given.
3298 (if (and (module-defined? guile-user-module 'use-emacs-interface)
3299 (module-ref guile-user-module 'use-emacs-interface))
3300 (load-emacs-interface))
3302 ;; Use some convenient modules (in reverse order)
3304 (set-current-module guile-user-module)
3305 (process-use-modules
3310 (if (provided? 'regex)
3313 (if (provided? 'threads)
3314 '(((ice-9 threads)))
3316 ;; load debugger on demand
3317 (module-autoload! guile-user-module '(ice-9 debugger) '(debug))
3319 ;; Note: SIGFPE, SIGSEGV and SIGBUS are actually "query-only" (see
3320 ;; scmsigs.c scm_sigaction_for_thread), so the handlers setup here have
3322 (let ((old-handlers #f)
3323 (start-repl (module-ref (resolve-interface '(system repl repl))
3325 (signals (if (provided? 'posix)
3326 `((,SIGINT . "User interrupt")
3327 (,SIGFPE . "Arithmetic error")
3329 . "Bad memory access (Segmentation violation)"))
3331 ;; no SIGBUS on mingw
3332 (if (defined? 'SIGBUS)
3333 (set! signals (acons SIGBUS "Bad memory access (bus error)"
3340 (let ((make-handler (lambda (msg)
3342 ;; Make a backup copy of the stack
3343 (fluid-set! before-signal-stack
3344 (fluid-ref the-last-stack))
3352 (map (lambda (sig-msg)
3353 (sigaction (car sig-msg)
3354 (make-handler (cdr sig-msg))))
3357 ;; the protected thunk.
3359 (let ((status (start-repl 'scheme)))
3360 (run-hook exit-hook)
3365 (map (lambda (sig-msg old-handler)
3366 (if (not (car old-handler))
3367 ;; restore original C handler.
3368 (sigaction (car sig-msg) #f)
3369 ;; restore Scheme handler, SIG_IGN or SIG_DFL.
3370 (sigaction (car sig-msg)
3372 (cdr old-handler))))
3373 signals old-handlers))))))
3375 ;;; This hook is run at the very end of an interactive session.
3377 (define exit-hook (make-hook))
3381 ;;; {Deprecated stuff}
3385 (define (feature? sym)
3386 (issue-deprecation-warning
3387 "`feature?' is deprecated. Use `provided?' instead.")
3391 (primitive-load-path "ice-9/deprecated"))
3395 ;;; Place the user in the guile-user module.
3398 (define-module (guile-user))
3400 ;;; boot-9.scm ends here