3 ;;;; Copyright (C) 1995,1996,1997,1998,1999,2000,2001,2002,2003,2004,2005,2006,2007,2009
4 ;;;; Free Software Foundation, Inc.
6 ;;;; This library is free software; you can redistribute it and/or
7 ;;;; modify it under the terms of the GNU Lesser General Public
8 ;;;; License as published by the Free Software Foundation; either
9 ;;;; version 2.1 of the License, or (at your option) any later version.
11 ;;;; This library is distributed in the hope that it will be useful,
12 ;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
13 ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 ;;;; Lesser General Public License for more details.
16 ;;;; You should have received a copy of the GNU Lesser General Public
17 ;;;; License along with this library; if not, write to the Free Software
18 ;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
25 ;;; This file is the first thing loaded into Guile. It adds many mundane
26 ;;; definitions and a few that are interesting.
28 ;;; The module system (hence the hierarchical namespace) are defined in this
39 (primitive-load-path "ice-9/r4rs")
43 ;;; {Simple Debugging Tools}
46 ;; peek takes any number of arguments, writes them to the
47 ;; current ouput port, and returns the last argument.
48 ;; It is handy to wrap around an expression to look at
49 ;; a value each time is evaluated, e.g.:
51 ;; (+ 10 (troublesome-fn))
52 ;; => (+ 10 (pk 'troublesome-fn-returned (troublesome-fn)))
55 (define (peek . stuff)
60 (car (last-pair stuff)))
64 (define (warn . stuff)
65 (with-output-to-port (current-error-port)
68 (display ";;; WARNING ")
71 (car (last-pair stuff)))))
79 (if (not (memq sym *features*))
80 (set! *features* (cons sym *features*))))
82 ;; Return #t iff FEATURE is available to this Guile interpreter. In SLIB,
83 ;; provided? also checks to see if the module is available. We should do that
86 (define (provided? feature)
87 (and (memq feature *features*) #t))
89 ;; let format alias simple-format until the more complete version is loaded
91 (define format simple-format)
93 ;; this is scheme wrapping the C code so the final pred call is a tail call,
95 (define (string-any char_pred s . rest)
96 (let ((start (if (null? rest)
98 (end (if (or (null? rest) (null? (cdr rest)))
99 (string-length s) (cadr rest))))
100 (if (and (procedure? char_pred)
102 (<= end (string-length s))) ;; let c-code handle range error
103 (or (string-any-c-code char_pred s start (1- end))
104 (char_pred (string-ref s (1- end))))
105 (string-any-c-code char_pred s start end))))
107 ;; this is scheme wrapping the C code so the final pred call is a tail call,
109 (define (string-every char_pred s . rest)
110 (let ((start (if (null? rest)
112 (end (if (or (null? rest) (null? (cdr rest)))
113 (string-length s) (cadr rest))))
114 (if (and (procedure? char_pred)
116 (<= end (string-length s))) ;; let c-code handle range error
117 (and (string-every-c-code char_pred s start (1- end))
118 (char_pred (string-ref s (1- end))))
119 (string-every-c-code char_pred s start end))))
121 ;; A variant of string-fill! that we keep for compatability
123 (define (substring-fill! str start end fill)
124 (string-fill! str fill start end))
128 ;; Before the module system boots, there are no module names. But
129 ;; psyntax does want a module-name definition, so give it one.
130 (define (module-name x)
133 ;; (eval-when (situation...) form...)
135 ;; Evaluate certain code based on the situation that eval-when is used
136 ;; in. There are three situations defined.
138 ;; `load' triggers when a file is loaded via `load', or when a compiled
141 ;; `compile' triggers when an expression is compiled.
143 ;; `eval' triggers when code is evaluated interactively, as at the REPL
144 ;; or via the `compile' or `eval' procedures.
146 ;; NB: this macro is only ever expanded by the interpreter. The compiler
147 ;; notices it and interprets the situations differently.
149 (procedure->memoizing-macro
151 (let ((situations (cadr exp))
153 (if (or (memq 'load situations)
154 (memq 'eval situations))
155 `(begin . ,body))))))
159 ;; Before compiling, make sure any symbols are resolved in the (guile)
160 ;; module, the primary location of those symbols, rather than in
161 ;; (guile-user), the default module that we compile in.
164 (set-current-module (resolve-module '(guile))))
168 ;;; Depends on: features, eval-case
171 (define macro-table (make-weak-key-hash-table 61))
172 (define xformer-table (make-weak-key-hash-table 61))
174 (define (defmacro? m) (hashq-ref macro-table m))
175 (define (assert-defmacro?! m) (hashq-set! macro-table m #t))
176 (define (defmacro-transformer m) (hashq-ref xformer-table m))
177 (define (set-defmacro-transformer! m t) (hashq-set! xformer-table m t))
179 (define defmacro:transformer
181 (let* ((xform (lambda (exp env)
182 (copy-tree (apply f (cdr exp)))))
183 (a (procedure->memoizing-macro xform)))
184 (assert-defmacro?! a)
185 (set-defmacro-transformer! a f)
190 (let ((defmacro-transformer
191 (lambda (name parms . body)
192 (let ((transformer `(lambda ,parms ,@body)))
195 (define ,name (defmacro:transformer ,transformer)))))))
196 (defmacro:transformer defmacro-transformer)))
199 ;; XXX - should the definition of the car really be looked up in the
202 (define (macroexpand-1 e)
204 ((pair? e) (let* ((a (car e))
205 (val (and (symbol? a) (local-ref (list a)))))
207 (apply (defmacro-transformer val) (cdr e))
211 (define (macroexpand e)
213 ((pair? e) (let* ((a (car e))
214 (val (and (symbol? a) (local-ref (list a)))))
216 (macroexpand (apply (defmacro-transformer val) (cdr e)))
226 ;;; Depends on: defmacro
229 (defmacro begin-deprecated forms
230 (if (include-deprecated-features)
236 ;;; {Trivial Functions}
239 (define (identity x) x)
240 (define (and=> value procedure) (and value (procedure value)))
241 (define call/cc call-with-current-continuation)
243 ;;; apply-to-args is functionally redundant with apply and, worse,
244 ;;; is less general than apply since it only takes two arguments.
246 ;;; On the other hand, apply-to-args is a syntacticly convenient way to
247 ;;; perform binding in many circumstances when the "let" family of
248 ;;; of forms don't cut it. E.g.:
250 ;;; (apply-to-args (return-3d-mouse-coords)
255 (define (apply-to-args args fn) (apply fn args))
257 (defmacro false-if-exception (expr)
258 `(catch #t (lambda () ,expr)
263 ;;; {General Properties}
266 ;; This is a more modern interface to properties. It will replace all
267 ;; other property-like things eventually.
269 (define (make-object-property)
270 (let ((prop (primitive-make-property #f)))
271 (make-procedure-with-setter
272 (lambda (obj) (primitive-property-ref prop obj))
273 (lambda (obj val) (primitive-property-set! prop obj val)))))
277 ;;; {Symbol Properties}
280 (define (symbol-property sym prop)
281 (let ((pair (assoc prop (symbol-pref sym))))
282 (and pair (cdr pair))))
284 (define (set-symbol-property! sym prop val)
285 (let ((pair (assoc prop (symbol-pref sym))))
288 (symbol-pset! sym (acons prop val (symbol-pref sym))))))
290 (define (symbol-property-remove! sym prop)
291 (let ((pair (assoc prop (symbol-pref sym))))
293 (symbol-pset! sym (delq! pair (symbol-pref sym))))))
300 (define (array-shape a)
301 (map (lambda (ind) (if (number? ind) (list 0 (+ -1 ind)) ind))
302 (array-dimensions a)))
309 (define (kw-arg-ref args kw)
310 (let ((rem (member kw args)))
311 (and rem (pair? (cdr rem)) (cadr rem))))
318 (define (struct-layout s)
319 (struct-ref (struct-vtable s) vtable-index-layout))
326 ;; Printing records: by default, records are printed as
328 ;; #<type-name field1: val1 field2: val2 ...>
330 ;; You can change that by giving a custom printing function to
331 ;; MAKE-RECORD-TYPE (after the list of field symbols). This function
332 ;; will be called like
334 ;; (<printer> object port)
336 ;; It should print OBJECT to PORT.
338 (define (inherit-print-state old-port new-port)
339 (if (get-print-state old-port)
340 (port-with-print-state new-port (get-print-state old-port))
343 ;; 0: type-name, 1: fields
344 (define record-type-vtable
345 (make-vtable-vtable "prpr" 0
347 (cond ((eq? s record-type-vtable)
348 (display "#<record-type-vtable>" p))
350 (display "#<record-type " p)
351 (display (record-type-name s) p)
354 (define (record-type? obj)
355 (and (struct? obj) (eq? record-type-vtable (struct-vtable obj))))
357 (define (make-record-type type-name fields . opt)
358 (let ((printer-fn (and (pair? opt) (car opt))))
359 (let ((struct (make-struct record-type-vtable 0
362 (map (lambda (f) "pw") fields)))
366 (display type-name p)
367 (let loop ((fields fields)
370 ((not (null? fields))
372 (display (car fields) p)
374 (display (struct-ref s off) p)
375 (loop (cdr fields) (+ 1 off)))))
378 (copy-tree fields))))
379 ;; Temporary solution: Associate a name to the record type descriptor
380 ;; so that the object system can create a wrapper class for it.
381 (set-struct-vtable-name! struct (if (symbol? type-name)
383 (string->symbol type-name)))
386 (define (record-type-name obj)
387 (if (record-type? obj)
388 (struct-ref obj vtable-offset-user)
389 (error 'not-a-record-type obj)))
391 (define (record-type-fields obj)
392 (if (record-type? obj)
393 (struct-ref obj (+ 1 vtable-offset-user))
394 (error 'not-a-record-type obj)))
396 (define (record-constructor rtd . opt)
397 (let ((field-names (if (pair? opt) (car opt) (record-type-fields rtd))))
399 `(lambda ,field-names
400 (make-struct ',rtd 0 ,@(map (lambda (f)
401 (if (memq f field-names)
404 (record-type-fields rtd)))))))
406 (define (record-predicate rtd)
407 (lambda (obj) (and (struct? obj) (eq? rtd (struct-vtable obj)))))
409 (define (%record-type-error rtd obj) ;; private helper
410 (or (eq? rtd (record-type-descriptor obj))
411 (scm-error 'wrong-type-arg "%record-type-check"
412 "Wrong type record (want `~S'): ~S"
413 (list (record-type-name rtd) obj)
416 (define (record-accessor rtd field-name)
417 (let ((pos (list-index (record-type-fields rtd) field-name)))
419 (error 'no-such-field field-name))
421 (if (eq? (struct-vtable obj) rtd)
423 (%record-type-error rtd obj)))))
425 (define (record-modifier rtd field-name)
426 (let ((pos (list-index (record-type-fields rtd) field-name)))
428 (error 'no-such-field field-name))
430 (if (eq? (struct-vtable obj) rtd)
431 (struct-set! obj pos val)
432 (%record-type-error rtd obj)))))
434 (define (record? obj)
435 (and (struct? obj) (record-type? (struct-vtable obj))))
437 (define (record-type-descriptor obj)
440 (error 'not-a-record obj)))
449 (define (->bool x) (not (not x)))
456 (define (symbol-append . args)
457 (string->symbol (apply string-append (map symbol->string args))))
459 (define (list->symbol . args)
460 (string->symbol (apply list->string args)))
462 (define (symbol . args)
463 (string->symbol (apply string args)))
470 (define (list-index l k)
476 (loop (+ n 1) (cdr l))))))
480 ;;; {and-map and or-map}
482 ;;; (and-map fn lst) is like (and (fn (car lst)) (fn (cadr lst)) (fn...) ...)
483 ;;; (or-map fn lst) is like (or (fn (car lst)) (fn (cadr lst)) (fn...) ...)
488 ;; Apply f to successive elements of l until exhaustion or f returns #f.
489 ;; If returning early, return #f. Otherwise, return the last value returned
490 ;; by f. If f has never been called because l is empty, return #t.
492 (define (and-map f lst)
493 (let loop ((result #t)
498 (loop (f (car l)) (cdr l))))))
502 ;; Apply f to successive elements of l until exhaustion or while f returns #f.
503 ;; If returning early, return the return value of f.
505 (define (or-map f lst)
506 (let loop ((result #f)
510 (loop (f (car l)) (cdr l))))))
514 (if (provided? 'posix)
515 (primitive-load-path "ice-9/posix"))
517 (if (provided? 'socket)
518 (primitive-load-path "ice-9/networking"))
520 ;; For reference, Emacs file-exists-p uses stat in this same way.
521 ;; ENHANCE-ME: Catching an exception from stat is a bit wasteful, do this in
522 ;; C where all that's needed is to inspect the return from stat().
524 (if (provided? 'posix)
526 (->bool (false-if-exception (stat str))))
528 (let ((port (catch 'system-error (lambda () (open-file str OPEN_READ))
530 (if port (begin (close-port port) #t)
533 (define file-is-directory?
534 (if (provided? 'posix)
536 (eq? (stat:type (stat str)) 'directory))
538 (let ((port (catch 'system-error
539 (lambda () (open-file (string-append str "/.")
542 (if port (begin (close-port port) #t)
545 (define (has-suffix? str suffix)
546 (string-suffix? suffix str))
548 (define (system-error-errno args)
549 (if (eq? (car args) 'system-error)
550 (car (list-ref args 4))
558 (define (error . args)
561 (scm-error 'misc-error #f "?" #f #f)
562 (let loop ((msg "~A")
564 (if (not (null? rest))
565 (loop (string-append msg " ~S")
567 (scm-error 'misc-error #f msg args #f)))))
569 ;; bad-throw is the hook that is called upon a throw to a an unhandled
570 ;; key (unless the throw has four arguments, in which case
571 ;; it's usually interpreted as an error throw.)
572 ;; If the key has a default handler (a throw-handler-default property),
573 ;; it is applied to the throw.
575 (define (bad-throw key . args)
576 (let ((default (symbol-property key 'throw-handler-default)))
577 (or (and default (apply default key args))
578 (apply error "unhandled-exception:" key args))))
582 (define (tm:sec obj) (vector-ref obj 0))
583 (define (tm:min obj) (vector-ref obj 1))
584 (define (tm:hour obj) (vector-ref obj 2))
585 (define (tm:mday obj) (vector-ref obj 3))
586 (define (tm:mon obj) (vector-ref obj 4))
587 (define (tm:year obj) (vector-ref obj 5))
588 (define (tm:wday obj) (vector-ref obj 6))
589 (define (tm:yday obj) (vector-ref obj 7))
590 (define (tm:isdst obj) (vector-ref obj 8))
591 (define (tm:gmtoff obj) (vector-ref obj 9))
592 (define (tm:zone obj) (vector-ref obj 10))
594 (define (set-tm:sec obj val) (vector-set! obj 0 val))
595 (define (set-tm:min obj val) (vector-set! obj 1 val))
596 (define (set-tm:hour obj val) (vector-set! obj 2 val))
597 (define (set-tm:mday obj val) (vector-set! obj 3 val))
598 (define (set-tm:mon obj val) (vector-set! obj 4 val))
599 (define (set-tm:year obj val) (vector-set! obj 5 val))
600 (define (set-tm:wday obj val) (vector-set! obj 6 val))
601 (define (set-tm:yday obj val) (vector-set! obj 7 val))
602 (define (set-tm:isdst obj val) (vector-set! obj 8 val))
603 (define (set-tm:gmtoff obj val) (vector-set! obj 9 val))
604 (define (set-tm:zone obj val) (vector-set! obj 10 val))
606 (define (tms:clock obj) (vector-ref obj 0))
607 (define (tms:utime obj) (vector-ref obj 1))
608 (define (tms:stime obj) (vector-ref obj 2))
609 (define (tms:cutime obj) (vector-ref obj 3))
610 (define (tms:cstime obj) (vector-ref obj 4))
612 (define file-position ftell)
613 (define (file-set-position port offset . whence)
614 (let ((whence (if (eq? whence '()) SEEK_SET (car whence))))
615 (seek port offset whence)))
617 (define (move->fdes fd/port fd)
618 (cond ((integer? fd/port)
619 (dup->fdes fd/port fd)
623 (primitive-move->fdes fd/port fd)
624 (set-port-revealed! fd/port 1)
627 (define (release-port-handle port)
628 (let ((revealed (port-revealed port)))
630 (set-port-revealed! port (- revealed 1)))))
632 (define (dup->port port/fd mode . maybe-fd)
633 (let ((port (fdopen (apply dup->fdes port/fd maybe-fd)
636 (set-port-revealed! port 1))
639 (define (dup->inport port/fd . maybe-fd)
640 (apply dup->port port/fd "r" maybe-fd))
642 (define (dup->outport port/fd . maybe-fd)
643 (apply dup->port port/fd "w" maybe-fd))
645 (define (dup port/fd . maybe-fd)
646 (if (integer? port/fd)
647 (apply dup->fdes port/fd maybe-fd)
648 (apply dup->port port/fd (port-mode port/fd) maybe-fd)))
650 (define (duplicate-port port modes)
651 (dup->port port modes))
653 (define (fdes->inport fdes)
654 (let loop ((rest-ports (fdes->ports fdes)))
655 (cond ((null? rest-ports)
656 (let ((result (fdopen fdes "r")))
657 (set-port-revealed! result 1)
659 ((input-port? (car rest-ports))
660 (set-port-revealed! (car rest-ports)
661 (+ (port-revealed (car rest-ports)) 1))
664 (loop (cdr rest-ports))))))
666 (define (fdes->outport fdes)
667 (let loop ((rest-ports (fdes->ports fdes)))
668 (cond ((null? rest-ports)
669 (let ((result (fdopen fdes "w")))
670 (set-port-revealed! result 1)
672 ((output-port? (car rest-ports))
673 (set-port-revealed! (car rest-ports)
674 (+ (port-revealed (car rest-ports)) 1))
677 (loop (cdr rest-ports))))))
679 (define (port->fdes port)
680 (set-port-revealed! port (+ (port-revealed port) 1))
683 (define (setenv name value)
685 (putenv (string-append name "=" value))
688 (define (unsetenv name)
689 "Remove the entry for NAME from the environment."
697 ;;; Here for backward compatability
699 (define scheme-file-suffix (lambda () ".scm"))
701 (define (in-vicinity vicinity file)
702 (let ((tail (let ((len (string-length vicinity)))
705 (string-ref vicinity (- len 1))))))
706 (string-append vicinity
715 ;;; {Help for scm_shell}
717 ;;; The argument-processing code used by Guile-based shells generates
718 ;;; Scheme code based on the argument list. This page contains help
719 ;;; functions for the code it generates.
722 (define (command-line) (program-arguments))
724 ;; This is mostly for the internal use of the code generated by
725 ;; scm_compile_shell_switches.
727 (define (turn-on-debugging)
728 (debug-enable 'debug)
729 (debug-enable 'backtrace)
730 (read-enable 'positions))
732 (define (load-user-init)
733 (let* ((home (or (getenv "HOME")
734 (false-if-exception (passwd:dir (getpwuid (getuid))))
735 "/")) ;; fallback for cygwin etc.
736 (init-file (in-vicinity home ".guile")))
737 (if (file-exists? init-file)
738 (primitive-load init-file))))
742 ;;; {The interpreter stack}
745 (defmacro start-stack (tag exp)
746 `(%start-stack ,tag (lambda () ,exp)))
750 ;;; {Loading by paths}
753 ;;; Load a Scheme source file named NAME, searching for it in the
754 ;;; directories listed in %load-path, and applying each of the file
755 ;;; name extensions listed in %load-extensions.
756 (define (load-from-path name)
757 (start-stack 'load-stack
758 (primitive-load-path name)))
763 ;;; {Transcendental Functions}
765 ;;; Derived from "Transcen.scm", Complex trancendental functions for SCM.
766 ;;; Written by Jerry D. Hedden, (C) FSF.
767 ;;; See the file `COPYING' for terms applying to this program.
771 (let ((integer-expt integer-expt))
773 (cond ((and (exact? z2) (integer? z2))
774 (integer-expt z1 z2))
775 ((and (real? z2) (real? z1) (>= z1 0))
778 (exp (* z2 (log z1))))))))
781 (if (real? z) ($sinh z)
782 (let ((x (real-part z)) (y (imag-part z)))
783 (make-rectangular (* ($sinh x) ($cos y))
784 (* ($cosh x) ($sin y))))))
786 (if (real? z) ($cosh z)
787 (let ((x (real-part z)) (y (imag-part z)))
788 (make-rectangular (* ($cosh x) ($cos y))
789 (* ($sinh x) ($sin y))))))
791 (if (real? z) ($tanh z)
792 (let* ((x (* 2 (real-part z)))
793 (y (* 2 (imag-part z)))
794 (w (+ ($cosh x) ($cos y))))
795 (make-rectangular (/ ($sinh x) w) (/ ($sin y) w)))))
798 (if (real? z) ($asinh z)
799 (log (+ z (sqrt (+ (* z z) 1))))))
802 (if (and (real? z) (>= z 1))
804 (log (+ z (sqrt (- (* z z) 1))))))
807 (if (and (real? z) (> z -1) (< z 1))
809 (/ (log (/ (+ 1 z) (- 1 z))) 2)))
812 (if (real? z) ($sin z)
813 (let ((x (real-part z)) (y (imag-part z)))
814 (make-rectangular (* ($sin x) ($cosh y))
815 (* ($cos x) ($sinh y))))))
817 (if (real? z) ($cos z)
818 (let ((x (real-part z)) (y (imag-part z)))
819 (make-rectangular (* ($cos x) ($cosh y))
820 (- (* ($sin x) ($sinh y)))))))
822 (if (real? z) ($tan z)
823 (let* ((x (* 2 (real-part z)))
824 (y (* 2 (imag-part z)))
825 (w (+ ($cos x) ($cosh y))))
826 (make-rectangular (/ ($sin x) w) (/ ($sinh y) w)))))
829 (if (and (real? z) (>= z -1) (<= z 1))
831 (* -i (asinh (* +i z)))))
834 (if (and (real? z) (>= z -1) (<= z 1))
836 (+ (/ (angle -1) 2) (* +i (asinh (* +i z))))))
840 (if (real? z) ($atan z)
841 (/ (log (/ (- +i z) (+ +i z))) +2i))
846 ;;; {Reader Extensions}
848 ;;; Reader code for various "#c" forms.
851 (read-hash-extend #\' (lambda (c port)
854 (define read-eval? (make-fluid))
855 (fluid-set! read-eval? #f)
856 (read-hash-extend #\.
858 (if (fluid-ref read-eval?)
859 (eval (read port) (interaction-environment))
861 "#. read expansion found and read-eval? is #f."))))
865 ;;; {Command Line Options}
868 (define (get-option argv kw-opts kw-args return)
873 ((or (not (eq? #\- (string-ref (car argv) 0)))
874 (eq? (string-length (car argv)) 1))
875 (return 'normal-arg (car argv) (cdr argv)))
877 ((eq? #\- (string-ref (car argv) 1))
878 (let* ((kw-arg-pos (or (string-index (car argv) #\=)
879 (string-length (car argv))))
880 (kw (symbol->keyword (substring (car argv) 2 kw-arg-pos)))
881 (kw-opt? (member kw kw-opts))
882 (kw-arg? (member kw kw-args))
883 (arg (or (and (not (eq? kw-arg-pos (string-length (car argv))))
884 (substring (car argv)
886 (string-length (car argv))))
888 (begin (set! argv (cdr argv)) (car argv))))))
889 (if (or kw-opt? kw-arg?)
890 (return kw arg (cdr argv))
891 (return 'usage-error kw (cdr argv)))))
894 (let* ((char (substring (car argv) 1 2))
895 (kw (symbol->keyword char)))
899 (let* ((rest-car (substring (car argv) 2 (string-length (car argv))))
900 (new-argv (if (= 0 (string-length rest-car))
902 (cons (string-append "-" rest-car) (cdr argv)))))
903 (return kw #f new-argv)))
906 (let* ((rest-car (substring (car argv) 2 (string-length (car argv))))
907 (arg (if (= 0 (string-length rest-car))
910 (new-argv (if (= 0 (string-length rest-car))
913 (return kw arg new-argv)))
915 (else (return 'usage-error kw argv)))))))
917 (define (for-next-option proc argv kw-opts kw-args)
918 (let loop ((argv argv))
919 (get-option argv kw-opts kw-args
920 (lambda (opt opt-arg argv)
921 (and opt (proc opt opt-arg argv loop))))))
923 (define (display-usage-report kw-desc)
926 (or (eq? (car kw) #t)
929 (help (cadr opt-desc))
930 (opts (car opt-desc))
931 (opts-proper (if (string? (car opts)) (cdr opts) opts))
932 (arg-name (if (string? (car opts))
933 (string-append "<" (car opts) ">")
935 (left-part (string-append
936 (with-output-to-string
938 (map (lambda (x) (display (keyword->symbol x)) (display " "))
941 (middle-part (if (and (< (string-length left-part) 30)
942 (< (string-length help) 40))
943 (make-string (- 30 (string-length left-part)) #\ )
946 (display middle-part)
953 (define (transform-usage-lambda cases)
954 (let* ((raw-usage (delq! 'else (map car cases)))
955 (usage-sans-specials (map (lambda (x)
956 (or (and (not (list? x)) x)
957 (and (symbol? (car x)) #t)
958 (and (boolean? (car x)) #t)
961 (usage-desc (delq! #t usage-sans-specials))
962 (kw-desc (map car usage-desc))
963 (kw-opts (apply append (map (lambda (x) (and (not (string? (car x))) x)) kw-desc)))
964 (kw-args (apply append (map (lambda (x) (and (string? (car x)) (cdr x))) kw-desc)))
965 (transmogrified-cases (map (lambda (case)
966 (cons (let ((opts (car case)))
967 (if (or (boolean? opts) (eq? 'else opts))
970 ((symbol? (car opts)) opts)
971 ((boolean? (car opts)) opts)
972 ((string? (caar opts)) (cdar opts))
976 `(let ((%display-usage (lambda () (display-usage-report ',usage-desc))))
978 (let %next-arg ((%argv %argv))
982 (lambda (%opt %arg %new-argv)
984 ,@ transmogrified-cases))))))))
989 ;;; {Low Level Modules}
991 ;;; These are the low level data structures for modules.
993 ;;; Every module object is of the type 'module-type', which is a record
994 ;;; consisting of the following members:
996 ;;; - eval-closure: the function that defines for its module the strategy that
997 ;;; shall be followed when looking up symbols in the module.
999 ;;; An eval-closure is a function taking two arguments: the symbol to be
1000 ;;; looked up and a boolean value telling whether a binding for the symbol
1001 ;;; should be created if it does not exist yet. If the symbol lookup
1002 ;;; succeeded (either because an existing binding was found or because a new
1003 ;;; binding was created), a variable object representing the binding is
1004 ;;; returned. Otherwise, the value #f is returned. Note that the eval
1005 ;;; closure does not take the module to be searched as an argument: During
1006 ;;; construction of the eval-closure, the eval-closure has to store the
1007 ;;; module it belongs to in its environment. This means, that any
1008 ;;; eval-closure can belong to only one module.
1010 ;;; The eval-closure of a module can be defined arbitrarily. However, three
1011 ;;; special cases of eval-closures are to be distinguished: During startup
1012 ;;; the module system is not yet activated. In this phase, no modules are
1013 ;;; defined and all bindings are automatically stored by the system in the
1014 ;;; pre-modules-obarray. Since no eval-closures exist at this time, the
1015 ;;; functions which require an eval-closure as their argument need to be
1016 ;;; passed the value #f.
1018 ;;; The other two special cases of eval-closures are the
1019 ;;; standard-eval-closure and the standard-interface-eval-closure. Both
1020 ;;; behave equally for the case that no new binding is to be created. The
1021 ;;; difference between the two comes in, when the boolean argument to the
1022 ;;; eval-closure indicates that a new binding shall be created if it is not
1025 ;;; Given that no new binding shall be created, both standard eval-closures
1026 ;;; define the following standard strategy of searching bindings in the
1027 ;;; module: First, the module's obarray is searched for the symbol. Second,
1028 ;;; if no binding for the symbol was found in the module's obarray, the
1029 ;;; module's binder procedure is exececuted. If this procedure did not
1030 ;;; return a binding for the symbol, the modules referenced in the module's
1031 ;;; uses list are recursively searched for a binding of the symbol. If the
1032 ;;; binding can not be found in these modules also, the symbol lookup has
1035 ;;; If a new binding shall be created, the standard-interface-eval-closure
1036 ;;; immediately returns indicating failure. That is, it does not even try
1037 ;;; to look up the symbol. In contrast, the standard-eval-closure would
1038 ;;; first search the obarray, and if no binding was found there, would
1039 ;;; create a new binding in the obarray, therefore not calling the binder
1040 ;;; procedure or searching the modules in the uses list.
1042 ;;; The explanation of the following members obarray, binder and uses
1043 ;;; assumes that the symbol lookup follows the strategy that is defined in
1044 ;;; the standard-eval-closure and the standard-interface-eval-closure.
1046 ;;; - obarray: a hash table that maps symbols to variable objects. In this
1047 ;;; hash table, the definitions are found that are local to the module (that
1048 ;;; is, not imported from other modules). When looking up bindings in the
1049 ;;; module, this hash table is searched first.
1051 ;;; - binder: either #f or a function taking a module and a symbol argument.
1052 ;;; If it is a function it is called after the obarray has been
1053 ;;; unsuccessfully searched for a binding. It then can provide bindings
1054 ;;; that would otherwise not be found locally in the module.
1056 ;;; - uses: a list of modules from which non-local bindings can be inherited.
1057 ;;; These modules are the third place queried for bindings after the obarray
1058 ;;; has been unsuccessfully searched and the binder function did not deliver
1059 ;;; a result either.
1061 ;;; - transformer: either #f or a function taking a scheme expression as
1062 ;;; delivered by read. If it is a function, it will be called to perform
1063 ;;; syntax transformations (e. g. makro expansion) on the given scheme
1064 ;;; expression. The output of the transformer function will then be passed
1065 ;;; to Guile's internal memoizer. This means that the output must be valid
1066 ;;; scheme code. The only exception is, that the output may make use of the
1067 ;;; syntax extensions provided to identify the modules that a binding
1070 ;;; - name: the name of the module. This is used for all kinds of printing
1071 ;;; outputs. In certain places the module name also serves as a way of
1072 ;;; identification. When adding a module to the uses list of another
1073 ;;; module, it is made sure that the new uses list will not contain two
1074 ;;; modules of the same name.
1076 ;;; - kind: classification of the kind of module. The value is (currently?)
1077 ;;; only used for printing. It has no influence on how a module is treated.
1078 ;;; Currently the following values are used when setting the module kind:
1079 ;;; 'module, 'directory, 'interface, 'custom-interface. If no explicit kind
1080 ;;; is set, it defaults to 'module.
1082 ;;; - duplicates-handlers: a list of procedures that get called to make a
1083 ;;; choice between two duplicate bindings when name clashes occur. See the
1084 ;;; `duplicate-handlers' global variable below.
1086 ;;; - observers: a list of procedures that get called when the module is
1089 ;;; - weak-observers: a weak-key hash table of procedures that get called
1090 ;;; when the module is modified. See `module-observe-weak' for details.
1092 ;;; In addition, the module may (must?) contain a binding for
1093 ;;; `%module-public-interface'. This variable should be bound to a module
1094 ;;; representing the exported interface of a module. See the
1095 ;;; `module-public-interface' and `module-export!' procedures.
1097 ;;; !!! warning: The interface to lazy binder procedures is going
1098 ;;; to be changed in an incompatible way to permit all the basic
1099 ;;; module ops to be virtualized.
1101 ;;; (make-module size use-list lazy-binding-proc) => module
1102 ;;; module-{obarray,uses,binder}[|-set!]
1103 ;;; (module? obj) => [#t|#f]
1104 ;;; (module-locally-bound? module symbol) => [#t|#f]
1105 ;;; (module-bound? module symbol) => [#t|#f]
1106 ;;; (module-symbol-locally-interned? module symbol) => [#t|#f]
1107 ;;; (module-symbol-interned? module symbol) => [#t|#f]
1108 ;;; (module-local-variable module symbol) => [#<variable ...> | #f]
1109 ;;; (module-variable module symbol) => [#<variable ...> | #f]
1110 ;;; (module-symbol-binding module symbol opt-value)
1111 ;;; => [ <obj> | opt-value | an error occurs ]
1112 ;;; (module-make-local-var! module symbol) => #<variable...>
1113 ;;; (module-add! module symbol var) => unspecified
1114 ;;; (module-remove! module symbol) => unspecified
1115 ;;; (module-for-each proc module) => unspecified
1116 ;;; (make-scm-module) => module ; a lazy copy of the symhash module
1117 ;;; (set-current-module module) => unspecified
1118 ;;; (current-module) => #<module...>
1124 ;;; {Printing Modules}
1127 ;; This is how modules are printed. You can re-define it.
1128 ;; (Redefining is actually more complicated than simply redefining
1129 ;; %print-module because that would only change the binding and not
1130 ;; the value stored in the vtable that determines how record are
1133 (define (%print-module mod port) ; unused args: depth length style table)
1135 (display (or (module-kind mod) "module") port)
1136 (let ((name (module-name mod)))
1140 (display name port))))
1142 (display (number->string (object-address mod) 16) port)
1147 ;; A module is characterized by an obarray in which local symbols
1148 ;; are interned, a list of modules, "uses", from which non-local
1149 ;; bindings can be inherited, and an optional lazy-binder which
1150 ;; is a (CLOSURE module symbol) which, as a last resort, can provide
1151 ;; bindings that would otherwise not be found locally in the module.
1153 ;; NOTE: If you change anything here, you also need to change
1154 ;; libguile/modules.h.
1157 (make-record-type 'module
1158 '(obarray uses binder eval-closure transformer name kind
1159 duplicates-handlers import-obarray
1160 observers weak-observers)
1163 ;; make-module &opt size uses binder
1165 ;; Create a new module, perhaps with a particular size of obarray,
1166 ;; initial uses list, or binding procedure.
1171 (define (parse-arg index default)
1172 (if (> (length args) index)
1173 (list-ref args index)
1176 (define %default-import-size
1177 ;; Typical number of imported bindings actually used by a module.
1180 (if (> (length args) 3)
1181 (error "Too many args to make-module." args))
1183 (let ((size (parse-arg 0 31))
1184 (uses (parse-arg 1 '()))
1185 (binder (parse-arg 2 #f)))
1187 (if (not (integer? size))
1188 (error "Illegal size to make-module." size))
1189 (if (not (and (list? uses)
1190 (and-map module? uses)))
1191 (error "Incorrect use list." uses))
1192 (if (and binder (not (procedure? binder)))
1194 "Lazy-binder expected to be a procedure or #f." binder))
1196 (let ((module (module-constructor (make-hash-table size)
1197 uses binder #f #f #f #f #f
1198 (make-hash-table %default-import-size)
1200 (make-weak-key-hash-table 31))))
1202 ;; We can't pass this as an argument to module-constructor,
1203 ;; because we need it to close over a pointer to the module
1205 (set-module-eval-closure! module (standard-eval-closure module))
1209 (define module-constructor (record-constructor module-type))
1210 (define module-obarray (record-accessor module-type 'obarray))
1211 (define set-module-obarray! (record-modifier module-type 'obarray))
1212 (define module-uses (record-accessor module-type 'uses))
1213 (define set-module-uses! (record-modifier module-type 'uses))
1214 (define module-binder (record-accessor module-type 'binder))
1215 (define set-module-binder! (record-modifier module-type 'binder))
1217 ;; NOTE: This binding is used in libguile/modules.c.
1218 (define module-eval-closure (record-accessor module-type 'eval-closure))
1220 (define module-transformer (record-accessor module-type 'transformer))
1221 (define set-module-transformer! (record-modifier module-type 'transformer))
1222 (define module-name (record-accessor module-type 'name))
1223 (define set-module-name! (record-modifier module-type 'name))
1224 (define module-kind (record-accessor module-type 'kind))
1225 (define set-module-kind! (record-modifier module-type 'kind))
1226 (define module-duplicates-handlers
1227 (record-accessor module-type 'duplicates-handlers))
1228 (define set-module-duplicates-handlers!
1229 (record-modifier module-type 'duplicates-handlers))
1230 (define module-observers (record-accessor module-type 'observers))
1231 (define set-module-observers! (record-modifier module-type 'observers))
1232 (define module-weak-observers (record-accessor module-type 'weak-observers))
1233 (define module? (record-predicate module-type))
1235 (define module-import-obarray (record-accessor module-type 'import-obarray))
1237 (define set-module-eval-closure!
1238 (let ((setter (record-modifier module-type 'eval-closure)))
1239 (lambda (module closure)
1240 (setter module closure)
1241 ;; Make it possible to lookup the module from the environment.
1242 ;; This implementation is correct since an eval closure can belong
1243 ;; to maximally one module.
1244 (set-procedure-property! closure 'module module))))
1248 ;;; {Observer protocol}
1251 (define (module-observe module proc)
1252 (set-module-observers! module (cons proc (module-observers module)))
1255 (define (module-observe-weak module observer-id . proc)
1256 ;; Register PROC as an observer of MODULE under name OBSERVER-ID (which can
1257 ;; be any Scheme object). PROC is invoked and passed MODULE any time
1258 ;; MODULE is modified. PROC gets unregistered when OBSERVER-ID gets GC'd
1259 ;; (thus, it is never unregistered if OBSERVER-ID is an immediate value,
1262 ;; The two-argument version is kept for backward compatibility: when called
1263 ;; with two arguments, the observer gets unregistered when closure PROC
1264 ;; gets GC'd (making it impossible to use an anonymous lambda for PROC).
1266 (let ((proc (if (null? proc) observer-id (car proc))))
1267 (hashq-set! (module-weak-observers module) observer-id proc)))
1269 (define (module-unobserve token)
1270 (let ((module (car token))
1273 (hash-remove! (module-weak-observers module) id)
1274 (set-module-observers! module (delq1! id (module-observers module)))))
1277 (define module-defer-observers #f)
1278 (define module-defer-observers-mutex (make-mutex 'recursive))
1279 (define module-defer-observers-table (make-hash-table))
1281 (define (module-modified m)
1282 (if module-defer-observers
1283 (hash-set! module-defer-observers-table m #t)
1284 (module-call-observers m)))
1286 ;;; This function can be used to delay calls to observers so that they
1287 ;;; can be called once only in the face of massive updating of modules.
1289 (define (call-with-deferred-observers thunk)
1292 (lock-mutex module-defer-observers-mutex)
1293 (set! module-defer-observers #t))
1296 (set! module-defer-observers #f)
1297 (hash-for-each (lambda (m dummy)
1298 (module-call-observers m))
1299 module-defer-observers-table)
1300 (hash-clear! module-defer-observers-table)
1301 (unlock-mutex module-defer-observers-mutex))))
1303 (define (module-call-observers m)
1304 (for-each (lambda (proc) (proc m)) (module-observers m))
1306 ;; We assume that weak observers don't (un)register themselves as they are
1307 ;; called since this would preclude proper iteration over the hash table
1309 (hash-for-each (lambda (id proc) (proc m)) (module-weak-observers m)))
1313 ;;; {Module Searching in General}
1315 ;;; We sometimes want to look for properties of a symbol
1316 ;;; just within the obarray of one module. If the property
1317 ;;; holds, then it is said to hold ``locally'' as in, ``The symbol
1318 ;;; DISPLAY is locally rebound in the module `safe-guile'.''
1321 ;;; Other times, we want to test for a symbol property in the obarray
1322 ;;; of M and, if it is not found there, try each of the modules in the
1323 ;;; uses list of M. This is the normal way of testing for some
1324 ;;; property, so we state these properties without qualification as
1325 ;;; in: ``The symbol 'fnord is interned in module M because it is
1326 ;;; interned locally in module M2 which is a member of the uses list
1330 ;; module-search fn m
1332 ;; return the first non-#f result of FN applied to M and then to
1333 ;; the modules in the uses of m, and so on recursively. If all applications
1334 ;; return #f, then so does this function.
1336 (define (module-search fn m v)
1339 (or (module-search fn (car pos) v)
1342 (loop (module-uses m))))
1345 ;;; {Is a symbol bound in a module?}
1347 ;;; Symbol S in Module M is bound if S is interned in M and if the binding
1348 ;;; of S in M has been set to some well-defined value.
1351 ;; module-locally-bound? module symbol
1353 ;; Is a symbol bound (interned and defined) locally in a given module?
1355 (define (module-locally-bound? m v)
1356 (let ((var (module-local-variable m v)))
1358 (variable-bound? var))))
1360 ;; module-bound? module symbol
1362 ;; Is a symbol bound (interned and defined) anywhere in a given module
1365 (define (module-bound? m v)
1366 (module-search module-locally-bound? m v))
1368 ;;; {Is a symbol interned in a module?}
1370 ;;; Symbol S in Module M is interned if S occurs in
1371 ;;; of S in M has been set to some well-defined value.
1373 ;;; It is possible to intern a symbol in a module without providing
1374 ;;; an initial binding for the corresponding variable. This is done
1376 ;;; (module-add! module symbol (make-undefined-variable))
1378 ;;; In that case, the symbol is interned in the module, but not
1379 ;;; bound there. The unbound symbol shadows any binding for that
1380 ;;; symbol that might otherwise be inherited from a member of the uses list.
1383 (define (module-obarray-get-handle ob key)
1384 ((if (symbol? key) hashq-get-handle hash-get-handle) ob key))
1386 (define (module-obarray-ref ob key)
1387 ((if (symbol? key) hashq-ref hash-ref) ob key))
1389 (define (module-obarray-set! ob key val)
1390 ((if (symbol? key) hashq-set! hash-set!) ob key val))
1392 (define (module-obarray-remove! ob key)
1393 ((if (symbol? key) hashq-remove! hash-remove!) ob key))
1395 ;; module-symbol-locally-interned? module symbol
1397 ;; is a symbol interned (not neccessarily defined) locally in a given module
1398 ;; or its uses? Interned symbols shadow inherited bindings even if
1399 ;; they are not themselves bound to a defined value.
1401 (define (module-symbol-locally-interned? m v)
1402 (not (not (module-obarray-get-handle (module-obarray m) v))))
1404 ;; module-symbol-interned? module symbol
1406 ;; is a symbol interned (not neccessarily defined) anywhere in a given module
1407 ;; or its uses? Interned symbols shadow inherited bindings even if
1408 ;; they are not themselves bound to a defined value.
1410 (define (module-symbol-interned? m v)
1411 (module-search module-symbol-locally-interned? m v))
1414 ;;; {Mapping modules x symbols --> variables}
1417 ;; module-local-variable module symbol
1418 ;; return the local variable associated with a MODULE and SYMBOL.
1420 ;;; This function is very important. It is the only function that can
1421 ;;; return a variable from a module other than the mutators that store
1422 ;;; new variables in modules. Therefore, this function is the location
1423 ;;; of the "lazy binder" hack.
1425 ;;; If symbol is defined in MODULE, and if the definition binds symbol
1426 ;;; to a variable, return that variable object.
1428 ;;; If the symbols is not found at first, but the module has a lazy binder,
1429 ;;; then try the binder.
1431 ;;; If the symbol is not found at all, return #f.
1433 ;;; (This is now written in C, see `modules.c'.)
1436 ;;; {Mapping modules x symbols --> bindings}
1438 ;;; These are similar to the mapping to variables, except that the
1439 ;;; variable is dereferenced.
1442 ;; module-symbol-binding module symbol opt-value
1444 ;; return the binding of a variable specified by name within
1445 ;; a given module, signalling an error if the variable is unbound.
1446 ;; If the OPT-VALUE is passed, then instead of signalling an error,
1447 ;; return OPT-VALUE.
1449 (define (module-symbol-local-binding m v . opt-val)
1450 (let ((var (module-local-variable m v)))
1451 (if (and var (variable-bound? var))
1453 (if (not (null? opt-val))
1455 (error "Locally unbound variable." v)))))
1457 ;; module-symbol-binding module symbol opt-value
1459 ;; return the binding of a variable specified by name within
1460 ;; a given module, signalling an error if the variable is unbound.
1461 ;; If the OPT-VALUE is passed, then instead of signalling an error,
1462 ;; return OPT-VALUE.
1464 (define (module-symbol-binding m v . opt-val)
1465 (let ((var (module-variable m v)))
1466 (if (and var (variable-bound? var))
1468 (if (not (null? opt-val))
1470 (error "Unbound variable." v)))))
1475 ;;; {Adding Variables to Modules}
1478 ;; module-make-local-var! module symbol
1480 ;; ensure a variable for V in the local namespace of M.
1481 ;; If no variable was already there, then create a new and uninitialzied
1484 ;; This function is used in modules.c.
1486 (define (module-make-local-var! m v)
1487 (or (let ((b (module-obarray-ref (module-obarray m) v)))
1490 ;; Mark as modified since this function is called when
1491 ;; the standard eval closure defines a binding
1495 ;; Create a new local variable.
1496 (let ((local-var (make-undefined-variable)))
1497 (module-add! m v local-var)
1500 ;; module-ensure-local-variable! module symbol
1502 ;; Ensure that there is a local variable in MODULE for SYMBOL. If
1503 ;; there is no binding for SYMBOL, create a new uninitialized
1504 ;; variable. Return the local variable.
1506 (define (module-ensure-local-variable! module symbol)
1507 (or (module-local-variable module symbol)
1508 (let ((var (make-undefined-variable)))
1509 (module-add! module symbol var)
1512 ;; module-add! module symbol var
1514 ;; ensure a particular variable for V in the local namespace of M.
1516 (define (module-add! m v var)
1517 (if (not (variable? var))
1518 (error "Bad variable to module-add!" var))
1519 (module-obarray-set! (module-obarray m) v var)
1520 (module-modified m))
1524 ;; make sure that a symbol is undefined in the local namespace of M.
1526 (define (module-remove! m v)
1527 (module-obarray-remove! (module-obarray m) v)
1528 (module-modified m))
1530 (define (module-clear! m)
1531 (hash-clear! (module-obarray m))
1532 (module-modified m))
1534 ;; MODULE-FOR-EACH -- exported
1536 ;; Call PROC on each symbol in MODULE, with arguments of (SYMBOL VARIABLE).
1538 (define (module-for-each proc module)
1539 (hash-for-each proc (module-obarray module)))
1541 (define (module-map proc module)
1542 (hash-map->list proc (module-obarray module)))
1546 ;;; {Low Level Bootstrapping}
1551 ;; A root module uses the pre-modules-obarray as its obarray. This
1552 ;; special obarray accumulates all bindings that have been established
1553 ;; before the module system is fully booted.
1555 ;; (The obarray continues to be used by code that has been closed over
1556 ;; before the module system has been booted.)
1558 (define (make-root-module)
1559 (let ((m (make-module 0)))
1560 (set-module-obarray! m (%get-pre-modules-obarray))
1565 ;; The root interface is a module that uses the same obarray as the
1566 ;; root module. It does not allow new definitions, tho.
1568 (define (make-scm-module)
1569 (let ((m (make-module 0)))
1570 (set-module-obarray! m (%get-pre-modules-obarray))
1571 (set-module-eval-closure! m (standard-interface-eval-closure m))
1577 ;;; {Module-based Loading}
1580 (define (save-module-excursion thunk)
1581 (let ((inner-module (current-module))
1583 (dynamic-wind (lambda ()
1584 (set! outer-module (current-module))
1585 (set-current-module inner-module)
1586 (set! inner-module #f))
1589 (set! inner-module (current-module))
1590 (set-current-module outer-module)
1591 (set! outer-module #f)))))
1593 (define basic-load load)
1595 (define (load-module filename . reader)
1596 (save-module-excursion
1598 (let ((oldname (and (current-load-port)
1599 (port-filename (current-load-port)))))
1602 (> (string-length filename) 0)
1603 (not (char=? (string-ref filename 0) #\/))
1604 (not (string=? (dirname oldname) ".")))
1605 (string-append (dirname oldname) "/" filename)
1612 ;;; {MODULE-REF -- exported}
1615 ;; Returns the value of a variable called NAME in MODULE or any of its
1616 ;; used modules. If there is no such variable, then if the optional third
1617 ;; argument DEFAULT is present, it is returned; otherwise an error is signaled.
1619 (define (module-ref module name . rest)
1620 (let ((variable (module-variable module name)))
1621 (if (and variable (variable-bound? variable))
1622 (variable-ref variable)
1624 (error "No variable named" name 'in module)
1625 (car rest) ; default value
1628 ;; MODULE-SET! -- exported
1630 ;; Sets the variable called NAME in MODULE (or in a module that MODULE uses)
1631 ;; to VALUE; if there is no such variable, an error is signaled.
1633 (define (module-set! module name value)
1634 (let ((variable (module-variable module name)))
1636 (variable-set! variable value)
1637 (error "No variable named" name 'in module))))
1639 ;; MODULE-DEFINE! -- exported
1641 ;; Sets the variable called NAME in MODULE to VALUE; if there is no such
1642 ;; variable, it is added first.
1644 (define (module-define! module name value)
1645 (let ((variable (module-local-variable module name)))
1648 (variable-set! variable value)
1649 (module-modified module))
1650 (let ((variable (make-variable value)))
1651 (module-add! module name variable)))))
1653 ;; MODULE-DEFINED? -- exported
1655 ;; Return #t iff NAME is defined in MODULE (or in a module that MODULE
1658 (define (module-defined? module name)
1659 (let ((variable (module-variable module name)))
1660 (and variable (variable-bound? variable))))
1662 ;; MODULE-USE! module interface
1664 ;; Add INTERFACE to the list of interfaces used by MODULE.
1666 (define (module-use! module interface)
1667 (if (not (or (eq? module interface)
1668 (memq interface (module-uses module))))
1670 ;; Newly used modules must be appended rather than consed, so that
1671 ;; `module-variable' traverses the use list starting from the first
1673 (set-module-uses! module
1674 (append (filter (lambda (m)
1676 (equal? (module-name m)
1677 (module-name interface))))
1678 (module-uses module))
1681 (module-modified module))))
1683 ;; MODULE-USE-INTERFACES! module interfaces
1685 ;; Same as MODULE-USE! but add multiple interfaces and check for duplicates
1687 (define (module-use-interfaces! module interfaces)
1688 (set-module-uses! module
1689 (append (module-uses module) interfaces))
1690 (module-modified module))
1694 ;;; {Recursive Namespaces}
1696 ;;; A hierarchical namespace emerges if we consider some module to be
1697 ;;; root, and variables bound to modules as nested namespaces.
1699 ;;; The routines in this file manage variable names in hierarchical namespace.
1700 ;;; Each variable name is a list of elements, looked up in successively nested
1703 ;;; (nested-ref some-root-module '(foo bar baz))
1704 ;;; => <value of a variable named baz in the module bound to bar in
1705 ;;; the module bound to foo in some-root-module>
1710 ;;; ;; a-root is a module
1711 ;;; ;; name is a list of symbols
1713 ;;; nested-ref a-root name
1714 ;;; nested-set! a-root name val
1715 ;;; nested-define! a-root name val
1716 ;;; nested-remove! a-root name
1719 ;;; (current-module) is a natural choice for a-root so for convenience there are
1722 ;;; local-ref name == nested-ref (current-module) name
1723 ;;; local-set! name val == nested-set! (current-module) name val
1724 ;;; local-define! name val == nested-define! (current-module) name val
1725 ;;; local-remove! name == nested-remove! (current-module) name
1729 (define (nested-ref root names)
1730 (let loop ((cur root)
1734 ((not (module? cur)) #f)
1735 (else (loop (module-ref cur (car elts) #f) (cdr elts))))))
1737 (define (nested-set! root names val)
1738 (let loop ((cur root)
1740 (if (null? (cdr elts))
1741 (module-set! cur (car elts) val)
1742 (loop (module-ref cur (car elts)) (cdr elts)))))
1744 (define (nested-define! root names val)
1745 (let loop ((cur root)
1747 (if (null? (cdr elts))
1748 (module-define! cur (car elts) val)
1749 (loop (module-ref cur (car elts)) (cdr elts)))))
1751 (define (nested-remove! root names)
1752 (let loop ((cur root)
1754 (if (null? (cdr elts))
1755 (module-remove! cur (car elts))
1756 (loop (module-ref cur (car elts)) (cdr elts)))))
1758 (define (local-ref names) (nested-ref (current-module) names))
1759 (define (local-set! names val) (nested-set! (current-module) names val))
1760 (define (local-define names val) (nested-define! (current-module) names val))
1761 (define (local-remove names) (nested-remove! (current-module) names))
1766 ;;; {The (%app) module}
1768 ;;; The root of conventionally named objects not directly in the top level.
1771 ;;; (%app modules guile)
1773 ;;; The directory of all modules and the standard root module.
1776 ;; module-public-interface is defined in C.
1777 (define (set-module-public-interface! m i)
1778 (module-define! m '%module-public-interface i))
1779 (define (set-system-module! m s)
1780 (set-procedure-property! (module-eval-closure m) 'system-module s))
1781 (define the-root-module (make-root-module))
1782 (define the-scm-module (make-scm-module))
1783 (set-module-public-interface! the-root-module the-scm-module)
1784 (set-module-name! the-root-module '(guile))
1785 (set-module-name! the-scm-module '(guile))
1786 (set-module-kind! the-scm-module 'interface)
1787 (set-system-module! the-root-module #t)
1788 (set-system-module! the-scm-module #t)
1790 ;; NOTE: This binding is used in libguile/modules.c.
1792 (define (make-modules-in module name)
1796 (let* ((var (module-local-variable module (car name)))
1797 (val (and var (variable-bound? var) (variable-ref var))))
1800 (let ((m (make-module 31)))
1801 (set-module-kind! m 'directory)
1802 (set-module-name! m (append (or (module-name module) '())
1804 (module-define! module (car name) m)
1808 (define (beautify-user-module! module)
1809 (let ((interface (module-public-interface module)))
1810 (if (or (not interface)
1811 (eq? interface module))
1812 (let ((interface (make-module 31)))
1813 (set-module-name! interface (module-name module))
1814 (set-module-kind! interface 'interface)
1815 (set-module-public-interface! module interface))))
1816 (if (and (not (memq the-scm-module (module-uses module)))
1817 (not (eq? module the-root-module)))
1818 ;; Import the default set of bindings (from the SCM module) in MODULE.
1819 (module-use! module the-scm-module)))
1821 ;; NOTE: This binding is used in libguile/modules.c.
1823 (define resolve-module
1824 (let ((the-root-module the-root-module))
1825 (lambda (name . maybe-autoload)
1826 (if (equal? name '(guile))
1828 (let ((full-name (append '(%app modules) name)))
1829 (let ((already (nested-ref the-root-module full-name))
1830 (autoload (or (null? maybe-autoload) (car maybe-autoload))))
1832 ((and already (module? already)
1833 (or (not autoload) (module-public-interface already)))
1834 ;; A hit, a palpable hit.
1837 ;; Try to autoload the module, and recurse.
1838 (try-load-module name)
1839 (resolve-module name #f))
1841 ;; A module is not bound (but maybe something else is),
1842 ;; we're not autoloading -- here's the weird semantics,
1843 ;; we create an empty module.
1844 (make-modules-in the-root-module full-name)))))))))
1846 ;; Cheat. These bindings are needed by modules.c, but we don't want
1847 ;; to move their real definition here because that would be unnatural.
1849 (define try-module-autoload #f)
1850 (define process-define-module #f)
1851 (define process-use-modules #f)
1852 (define module-export! #f)
1853 (define default-duplicate-binding-procedures #f)
1855 (define %app (make-module 31))
1856 (define app %app) ;; for backwards compatability
1858 (local-define '(%app modules) (make-module 31))
1859 (local-define '(%app modules guile) the-root-module)
1861 ;; This boots the module system. All bindings needed by modules.c
1862 ;; must have been defined by now.
1864 (set-current-module the-root-module)
1866 ;; (define-special-value '(%app modules new-ws) (lambda () (make-scm-module)))
1868 (define (try-load-module name)
1869 (or (begin-deprecated (try-module-linked name))
1870 (try-module-autoload name)
1871 (begin-deprecated (try-module-dynamic-link name))))
1873 (define (purify-module! module)
1874 "Removes bindings in MODULE which are inherited from the (guile) module."
1875 (let ((use-list (module-uses module)))
1876 (if (and (pair? use-list)
1877 (eq? (car (last-pair use-list)) the-scm-module))
1878 (set-module-uses! module (reverse (cdr (reverse use-list)))))))
1880 ;; Return a module that is an interface to the module designated by
1883 ;; `resolve-interface' takes four keyword arguments:
1885 ;; #:select SELECTION
1887 ;; SELECTION is a list of binding-specs to be imported; A binding-spec
1888 ;; is either a symbol or a pair of symbols (ORIG . SEEN), where ORIG
1889 ;; is the name in the used module and SEEN is the name in the using
1890 ;; module. Note that SEEN is also passed through RENAMER, below. The
1891 ;; default is to select all bindings. If you specify no selection but
1892 ;; a renamer, only the bindings that already exist in the used module
1893 ;; are made available in the interface. Bindings that are added later
1894 ;; are not picked up.
1898 ;; BINDINGS is a list of bindings which should not be imported.
1902 ;; PREFIX is a symbol that will be appended to each exported name.
1903 ;; The default is to not perform any renaming.
1905 ;; #:renamer RENAMER
1907 ;; RENAMER is a procedure that takes a symbol and returns its new
1908 ;; name. The default is not perform any renaming.
1910 ;; Signal "no code for module" error if module name is not resolvable
1911 ;; or its public interface is not available. Signal "no binding"
1912 ;; error if selected binding does not exist in the used module.
1914 (define (resolve-interface name . args)
1916 (define (get-keyword-arg args kw def)
1917 (cond ((memq kw args)
1919 (if (null? (cdr kw-arg))
1920 (error "keyword without value: " kw))
1925 (let* ((select (get-keyword-arg args #:select #f))
1926 (hide (get-keyword-arg args #:hide '()))
1927 (renamer (or (get-keyword-arg args #:renamer #f)
1928 (let ((prefix (get-keyword-arg args #:prefix #f)))
1929 (and prefix (symbol-prefix-proc prefix)))
1931 (module (resolve-module name))
1932 (public-i (and module (module-public-interface module))))
1933 (and (or (not module) (not public-i))
1934 (error "no code for module" name))
1935 (if (and (not select) (null? hide) (eq? renamer identity))
1937 (let ((selection (or select (module-map (lambda (sym var) sym)
1939 (custom-i (make-module 31)))
1940 (set-module-kind! custom-i 'custom-interface)
1941 (set-module-name! custom-i name)
1942 ;; XXX - should use a lazy binder so that changes to the
1943 ;; used module are picked up automatically.
1944 (for-each (lambda (bspec)
1945 (let* ((direct? (symbol? bspec))
1946 (orig (if direct? bspec (car bspec)))
1947 (seen (if direct? bspec (cdr bspec)))
1948 (var (or (module-local-variable public-i orig)
1949 (module-local-variable module orig)
1951 ;; fixme: format manually for now
1953 #f "no binding `~A' in module ~A"
1955 (if (memq orig hide)
1956 (set! hide (delq! orig hide))
1957 (module-add! custom-i
1961 ;; Check that we are not hiding bindings which don't exist
1962 (for-each (lambda (binding)
1963 (if (not (module-local-variable public-i binding))
1966 #f "no binding `~A' to hide in module ~A"
1971 (define (symbol-prefix-proc prefix)
1973 (symbol-append prefix symbol)))
1975 ;; This function is called from "modules.c". If you change it, be
1976 ;; sure to update "modules.c" as well.
1978 (define (process-define-module args)
1979 (let* ((module-id (car args))
1980 (module (resolve-module module-id #f))
1982 (unrecognized (lambda (arg)
1983 (error "unrecognized define-module argument" arg))))
1984 (beautify-user-module! module)
1985 (let loop ((kws kws)
1986 (reversed-interfaces '())
1993 (call-with-deferred-observers
1995 (module-use-interfaces! module (reverse reversed-interfaces))
1996 (module-export! module exports)
1997 (module-replace! module replacements)
1998 (module-re-export! module re-exports)
1999 (if (not (null? autoloads))
2000 (apply module-autoload! module autoloads))))
2002 ((#:use-module #:use-syntax)
2003 (or (pair? (cdr kws))
2005 (let* ((interface-args (cadr kws))
2006 (interface (apply resolve-interface interface-args)))
2007 (and (eq? (car kws) #:use-syntax)
2008 (or (symbol? (caar interface-args))
2009 (error "invalid module name for use-syntax"
2010 (car interface-args)))
2011 (set-module-transformer!
2013 (module-ref interface
2014 (car (last-pair (car interface-args)))
2017 (cons interface reversed-interfaces)
2023 (or (and (pair? (cdr kws)) (pair? (cddr kws)))
2030 (let ((name (cadr kws))
2031 (bindings (caddr kws)))
2032 (cons* name bindings autoloads))))
2034 (set-system-module! module #t)
2035 (loop (cdr kws) reversed-interfaces exports re-exports
2036 replacements autoloads))
2038 (purify-module! module)
2039 (loop (cdr kws) reversed-interfaces exports re-exports
2040 replacements autoloads))
2042 (if (not (pair? (cdr kws)))
2044 (set-module-duplicates-handlers!
2046 (lookup-duplicates-handlers (cadr kws)))
2047 (loop (cddr kws) reversed-interfaces exports re-exports
2048 replacements autoloads))
2049 ((#:export #:export-syntax)
2050 (or (pair? (cdr kws))
2054 (append (cadr kws) exports)
2058 ((#:re-export #:re-export-syntax)
2059 (or (pair? (cdr kws))
2064 (append (cadr kws) re-exports)
2067 ((#:replace #:replace-syntax)
2068 (or (pair? (cdr kws))
2074 (append (cadr kws) replacements)
2077 (unrecognized kws)))))
2078 (run-hook module-defined-hook module)
2081 ;; `module-defined-hook' is a hook that is run whenever a new module
2082 ;; is defined. Its members are called with one argument, the new
2084 (define module-defined-hook (make-hook 1))
2091 (define (make-autoload-interface module name bindings)
2092 (let ((b (lambda (a sym definep)
2093 (and (memq sym bindings)
2094 (let ((i (module-public-interface (resolve-module name))))
2096 (error "missing interface for module" name))
2097 (let ((autoload (memq a (module-uses module))))
2098 ;; Replace autoload-interface with actual interface if
2099 ;; that has not happened yet.
2100 (if (pair? autoload)
2101 (set-car! autoload i)))
2102 (module-local-variable i sym))))))
2103 (module-constructor (make-hash-table 0) '() b #f #f name 'autoload #f
2104 (make-hash-table 0) '() (make-weak-value-hash-table 31))))
2106 (define (module-autoload! module . args)
2107 "Have @var{module} automatically load the module named @var{name} when one
2108 of the symbols listed in @var{bindings} is looked up. @var{args} should be a
2109 list of module-name/binding-list pairs, e.g., as in @code{(module-autoload!
2110 module '(ice-9 q) '(make-q q-length))}."
2111 (let loop ((args args))
2115 (error "invalid name+binding autoload list" args))
2117 (let ((name (car args))
2118 (bindings (cadr args)))
2119 (module-use! module (make-autoload-interface module
2121 (loop (cddr args)))))))
2126 ;;; {Autoloading modules}
2129 (define autoloads-in-progress '())
2131 ;; This function is called from "modules.c". If you change it, be
2132 ;; sure to update "modules.c" as well.
2134 (define (try-module-autoload module-name)
2135 (let* ((reverse-name (reverse module-name))
2136 (name (symbol->string (car reverse-name)))
2137 (dir-hint-module-name (reverse (cdr reverse-name)))
2138 (dir-hint (apply string-append
2140 (string-append (symbol->string elt) "/"))
2141 dir-hint-module-name))))
2142 (resolve-module dir-hint-module-name #f)
2143 (and (not (autoload-done-or-in-progress? dir-hint name))
2145 (define (load-file proc file)
2146 (save-module-excursion (lambda () (proc file)))
2149 (lambda () (autoload-in-progress! dir-hint name))
2151 (let ((file (in-vicinity dir-hint name)))
2152 (let ((compiled (and load-compiled
2154 (string-append file ".go"))))
2155 (source (%search-load-path file)))
2158 (< (stat:mtime (stat compiled))
2159 (stat:mtime (stat source)))))
2161 (warn "source file" source "newer than" compiled))
2162 (with-fluid* current-reader #f
2163 (lambda () (load-file primitive-load source))))
2165 (load-file load-compiled compiled))))))
2166 (lambda () (set-autoloaded! dir-hint name didit)))
2171 ;;; {Dynamic linking of modules}
2174 (define autoloads-done '((guile . guile)))
2176 (define (autoload-done-or-in-progress? p m)
2177 (let ((n (cons p m)))
2178 (->bool (or (member n autoloads-done)
2179 (member n autoloads-in-progress)))))
2181 (define (autoload-done! p m)
2182 (let ((n (cons p m)))
2183 (set! autoloads-in-progress
2184 (delete! n autoloads-in-progress))
2185 (or (member n autoloads-done)
2186 (set! autoloads-done (cons n autoloads-done)))))
2188 (define (autoload-in-progress! p m)
2189 (let ((n (cons p m)))
2190 (set! autoloads-done
2191 (delete! n autoloads-done))
2192 (set! autoloads-in-progress (cons n autoloads-in-progress))))
2194 (define (set-autoloaded! p m done?)
2196 (autoload-done! p m)
2197 (let ((n (cons p m)))
2198 (set! autoloads-done (delete! n autoloads-done))
2199 (set! autoloads-in-progress (delete! n autoloads-in-progress)))))
2203 ;;; {Run-time options}
2206 (defmacro define-option-interface (option-group)
2207 (let* ((option-name car)
2209 (option-documentation caddr)
2211 ;; Below follow the macros defining the run-time option interfaces.
2213 (make-options (lambda (interface)
2215 (cond ((null? args) (,interface))
2217 (,interface (car args)) (,interface))
2220 (display (option-name option))
2221 (if (< (string-length
2222 (symbol->string (option-name option)))
2226 (display (option-value option))
2228 (display (option-documentation option))
2230 (,interface #t)))))))
2232 (make-enable (lambda (interface)
2234 (,interface (append flags (,interface)))
2237 (make-disable (lambda (interface)
2239 (let ((options (,interface)))
2240 (for-each (lambda (flag)
2241 (set! options (delq! flag options)))
2243 (,interface options)
2245 (let* ((interface (car option-group))
2246 (options/enable/disable (cadr option-group)))
2248 (define ,(car options/enable/disable)
2249 ,(make-options interface))
2250 (define ,(cadr options/enable/disable)
2251 ,(make-enable interface))
2252 (define ,(caddr options/enable/disable)
2253 ,(make-disable interface))
2254 (defmacro ,(caaddr option-group) (opt val)
2255 `(,',(car options/enable/disable)
2256 (append (,',(car options/enable/disable))
2257 (list ',opt ,val))))))))
2259 (define-option-interface
2260 (eval-options-interface
2261 (eval-options eval-enable eval-disable)
2264 (define-option-interface
2265 (debug-options-interface
2266 (debug-options debug-enable debug-disable)
2269 (define-option-interface
2270 (evaluator-traps-interface
2271 (traps trap-enable trap-disable)
2274 (define-option-interface
2275 (read-options-interface
2276 (read-options read-enable read-disable)
2279 (define-option-interface
2280 (print-options-interface
2281 (print-options print-enable print-disable)
2289 (define (repl read evaler print)
2290 (let loop ((source (read (current-input-port))))
2291 (print (evaler source))
2292 (loop (read (current-input-port)))))
2294 ;; A provisional repl that acts like the SCM repl:
2296 (define scm-repl-silent #f)
2297 (define (assert-repl-silence v) (set! scm-repl-silent v))
2299 (define *unspecified* (if #f #f))
2300 (define (unspecified? v) (eq? v *unspecified*))
2302 (define scm-repl-print-unspecified #f)
2303 (define (assert-repl-print-unspecified v) (set! scm-repl-print-unspecified v))
2305 (define scm-repl-verbose #f)
2306 (define (assert-repl-verbosity v) (set! scm-repl-verbose v))
2308 (define scm-repl-prompt "guile> ")
2310 (define (set-repl-prompt! v) (set! scm-repl-prompt v))
2312 (define (default-pre-unwind-handler key . args)
2313 (save-stack pre-unwind-handler-dispatch)
2314 (apply throw key args))
2316 (define (pre-unwind-handler-dispatch key . args)
2317 (apply default-pre-unwind-handler key args))
2319 (define abort-hook (make-hook))
2321 ;; these definitions are used if running a script.
2322 ;; otherwise redefined in error-catching-loop.
2323 (define (set-batch-mode?! arg) #t)
2324 (define (batch-mode?) #t)
2326 (define (error-catching-loop thunk)
2329 (define (loop first)
2334 (call-with-unblocked-asyncs
2340 ;; This line is needed because mark
2341 ;; doesn't do closures quite right.
2342 ;; Unreferenced locals should be
2345 (let loop ((v (thunk)))
2349 (lambda (key . args)
2356 (apply throw 'switch-repl args))
2359 ;; This is one of the closures that require
2360 ;; (set! first #f) above
2363 (run-hook abort-hook)
2364 (force-output (current-output-port))
2365 (display "ABORT: " (current-error-port))
2366 (write args (current-error-port))
2367 (newline (current-error-port))
2371 (not has-shown-debugger-hint?)
2372 (not (memq 'backtrace
2373 (debug-options-interface)))
2374 (stack? (fluid-ref the-last-stack)))
2376 (newline (current-error-port))
2378 "Type \"(backtrace)\" to get more information or \"(debug)\" to enter the debugger.\n"
2379 (current-error-port))
2380 (set! has-shown-debugger-hint? #t)))
2381 (force-output (current-error-port)))
2383 (primitive-exit 1)))
2384 (set! stack-saved? #f)))
2387 ;; This is the other cons-leak closure...
2389 (cond ((= (length args) 4)
2390 (apply handle-system-error key args))
2392 (apply bad-throw key args)))))))
2394 ;; Note that having just `pre-unwind-handler-dispatch'
2395 ;; here is connected with the mechanism that
2396 ;; produces a nice backtrace upon error. If, for
2397 ;; example, this is replaced with (lambda args
2398 ;; (apply pre-unwind-handler-dispatch args)), the stack
2399 ;; cutting (in save-stack) goes wrong and ends up
2400 ;; saving no stack at all, so there is no
2402 pre-unwind-handler-dispatch)))
2404 (if next (loop next) status)))
2405 (set! set-batch-mode?! (lambda (arg)
2407 (set! interactive #f)
2410 (error "sorry, not implemented")))))
2411 (set! batch-mode? (lambda () (not interactive)))
2412 (call-with-blocked-asyncs
2413 (lambda () (loop (lambda () #t))))))
2415 ;;(define the-last-stack (make-fluid)) Defined by scm_init_backtrace ()
2416 (define before-signal-stack (make-fluid))
2417 (define stack-saved? #f)
2419 (define (save-stack . narrowing)
2421 (cond ((not (memq 'debug (debug-options-interface)))
2422 (fluid-set! the-last-stack #f)
2423 (set! stack-saved? #t))
2429 (apply make-stack #t save-stack primitive-eval #t 0 narrowing))
2431 (apply make-stack #t save-stack 0 #t 0 narrowing))
2433 (apply make-stack #t save-stack tk-stack-mark #t 0 narrowing))
2435 (apply make-stack #t save-stack 0 1 narrowing))
2437 (let ((id (stack-id #t)))
2438 (and (procedure? id)
2439 (apply make-stack #t save-stack id #t 0 narrowing))))))
2440 (set! stack-saved? #t)))))
2442 (define before-error-hook (make-hook))
2443 (define after-error-hook (make-hook))
2444 (define before-backtrace-hook (make-hook))
2445 (define after-backtrace-hook (make-hook))
2447 (define has-shown-debugger-hint? #f)
2449 (define (handle-system-error key . args)
2450 (let ((cep (current-error-port)))
2451 (cond ((not (stack? (fluid-ref the-last-stack))))
2452 ((memq 'backtrace (debug-options-interface))
2453 (let ((highlights (if (or (eq? key 'wrong-type-arg)
2454 (eq? key 'out-of-range))
2457 (run-hook before-backtrace-hook)
2459 (display "Backtrace:\n")
2460 (display-backtrace (fluid-ref the-last-stack) cep
2463 (run-hook after-backtrace-hook))))
2464 (run-hook before-error-hook)
2465 (apply display-error (fluid-ref the-last-stack) cep args)
2466 (run-hook after-error-hook)
2468 (throw 'abort key)))
2470 (define (quit . args)
2471 (apply throw 'quit args))
2475 ;;(define has-shown-backtrace-hint? #f) Defined by scm_init_backtrace ()
2477 ;; Replaced by C code:
2478 ;;(define (backtrace)
2479 ;; (if (fluid-ref the-last-stack)
2482 ;; (display-backtrace (fluid-ref the-last-stack) (current-output-port))
2484 ;; (if (and (not has-shown-backtrace-hint?)
2485 ;; (not (memq 'backtrace (debug-options-interface))))
2488 ;;"Type \"(debug-enable 'backtrace)\" if you would like a backtrace
2489 ;;automatically if an error occurs in the future.\n")
2490 ;; (set! has-shown-backtrace-hint? #t))))
2491 ;; (display "No backtrace available.\n")))
2493 (define (error-catching-repl r e p)
2494 (error-catching-loop
2496 (call-with-values (lambda () (e (r)))
2497 (lambda the-values (for-each p the-values))))))
2499 (define (gc-run-time)
2500 (cdr (assq 'gc-time-taken (gc-stats))))
2502 (define before-read-hook (make-hook))
2503 (define after-read-hook (make-hook))
2504 (define before-eval-hook (make-hook 1))
2505 (define after-eval-hook (make-hook 1))
2506 (define before-print-hook (make-hook 1))
2507 (define after-print-hook (make-hook 1))
2509 ;;; The default repl-reader function. We may override this if we've
2510 ;;; the readline library.
2513 (display (if (string? prompt) prompt (prompt)))
2515 (run-hook before-read-hook)
2516 ((or (fluid-ref current-reader) read) (current-input-port))))
2518 (define (scm-style-repl)
2523 (repl-report-start-timing (lambda ()
2524 (set! start-gc-rt (gc-run-time))
2525 (set! start-rt (get-internal-run-time))))
2526 (repl-report (lambda ()
2528 (display (inexact->exact
2529 (* 1000 (/ (- (get-internal-run-time) start-rt)
2530 internal-time-units-per-second))))
2532 (display (inexact->exact
2533 (* 1000 (/ (- (gc-run-time) start-gc-rt)
2534 internal-time-units-per-second))))
2535 (display " msec in gc)\n")))
2537 (consume-trailing-whitespace
2539 (let ((ch (peek-char)))
2542 ((or (char=? ch #\space) (char=? ch #\tab))
2544 (consume-trailing-whitespace))
2545 ((char=? ch #\newline)
2549 (let ((prompt (cond ((string? scm-repl-prompt)
2551 ((thunk? scm-repl-prompt)
2553 (scm-repl-prompt "> ")
2555 (repl-reader prompt))))
2557 ;; As described in R4RS, the READ procedure updates the
2558 ;; port to point to the first character past the end of
2559 ;; the external representation of the object. This
2560 ;; means that it doesn't consume the newline typically
2561 ;; found after an expression. This means that, when
2562 ;; debugging Guile with GDB, GDB gets the newline, which
2563 ;; it often interprets as a "continue" command, making
2564 ;; breakpoints kind of useless. So, consume any
2565 ;; trailing newline here, as well as any whitespace
2567 ;; But not if EOF, for control-D.
2568 (if (not (eof-object? val))
2569 (consume-trailing-whitespace))
2570 (run-hook after-read-hook)
2571 (if (eof-object? val)
2573 (repl-report-start-timing)
2574 (if scm-repl-verbose
2577 (display ";;; EOF -- quitting")
2582 (-eval (lambda (sourc)
2583 (repl-report-start-timing)
2584 (run-hook before-eval-hook sourc)
2585 (let ((val (start-stack 'repl-stack
2586 ;; If you change this procedure
2587 ;; (primitive-eval), please also
2588 ;; modify the repl-stack case in
2589 ;; save-stack so that stack cutting
2590 ;; continues to work.
2591 (primitive-eval sourc))))
2592 (run-hook after-eval-hook sourc)
2596 (-print (let ((maybe-print (lambda (result)
2597 (if (or scm-repl-print-unspecified
2598 (not (unspecified? result)))
2603 (if (not scm-repl-silent)
2605 (run-hook before-print-hook result)
2606 (maybe-print result)
2607 (run-hook after-print-hook result)
2608 (if scm-repl-verbose
2612 (-quit (lambda (args)
2613 (if scm-repl-verbose
2615 (display ";;; QUIT executed, repl exitting")
2621 (if scm-repl-verbose
2623 (display ";;; ABORT executed.")
2626 (repl -read -eval -print))))
2628 (let ((status (error-catching-repl -read
2636 ;;; {IOTA functions: generating lists of numbers}
2640 (let loop ((count (1- n)) (result '()))
2641 (if (< count 0) result
2642 (loop (1- count) (cons count result)))))
2648 ;;; Similar to `begin' but returns a list of the results of all constituent
2649 ;;; forms instead of the result of the last form.
2650 ;;; (The definition relies on the current left-to-right
2651 ;;; order of evaluation of operands in applications.)
2654 (defmacro collect forms
2662 ;; with-fluids is a convenience wrapper for the builtin procedure
2663 ;; `with-fluids*'. The syntax is just like `let':
2665 ;; (with-fluids ((fluid val)
2669 (defmacro with-fluids (bindings . body)
2670 (let ((fluids (map car bindings))
2671 (values (map cadr bindings)))
2672 (if (and (= (length fluids) 1) (= (length values) 1))
2673 `(with-fluid* ,(car fluids) ,(car values) (lambda () ,@body))
2674 `(with-fluids* (list ,@fluids) (list ,@values)
2675 (lambda () ,@body)))))
2682 ;; actually....hobbit might be able to hack these with a little
2686 (define (primitive-macro? m)
2688 (not (macro-transformer m))))
2690 (defmacro define-macro (first . rest)
2691 (let ((name (if (symbol? first) first (car first)))
2695 `(lambda ,(cdr first) ,@rest))))
2698 (define ,name (defmacro:transformer ,transformer)))))
2705 ;;; with `continue' and `break'.
2708 ;; The inner `do' loop avoids re-establishing a catch every iteration,
2709 ;; that's only necessary if continue is actually used. A new key is
2710 ;; generated every time, so break and continue apply to their originating
2711 ;; `while' even when recursing.
2713 ;; FIXME: This macro is unintentionally unhygienic with respect to let,
2714 ;; make-symbol, do, throw, catch, lambda, and not.
2716 (define-macro (while cond . body)
2717 (let ((keyvar (make-symbol "while-keyvar")))
2718 `(let ((,keyvar (make-symbol "while-key")))
2722 (let ((break (lambda () (throw ,keyvar #t)))
2723 (continue (lambda () (throw ,keyvar #f))))
2734 ;;; {Module System Macros}
2737 ;; Return a list of expressions that evaluate to the appropriate
2738 ;; arguments for resolve-interface according to SPEC.
2742 (if (memq 'prefix (read-options))
2743 (error "boot-9 must be compiled with #:kw, not :kw")))
2745 (define (compile-interface-spec spec)
2746 (define (make-keyarg sym key quote?)
2747 (cond ((or (memq sym spec)
2751 (list key (list 'quote (cadr rest)))
2752 (list key (cadr rest)))))
2755 (define (map-apply func list)
2756 (map (lambda (args) (apply func args)) list))
2759 '((:select #:select #t)
2761 (:prefix #:prefix #t)
2762 (:renamer #:renamer #f)))
2763 (if (not (pair? (car spec)))
2766 ,@(apply append (map-apply make-keyarg keys)))))
2768 (define (keyword-like-symbol->keyword sym)
2769 (symbol->keyword (string->symbol (substring (symbol->string sym) 1))))
2771 (define (compile-define-module-args args)
2772 ;; Just quote everything except #:use-module and #:use-syntax. We
2773 ;; need to know about all arguments regardless since we want to turn
2774 ;; symbols that look like keywords into real keywords, and the
2775 ;; keyword args in a define-module form are not regular
2776 ;; (i.e. no-backtrace doesn't take a value).
2777 (let loop ((compiled-args `((quote ,(car args))))
2780 (reverse! compiled-args))
2781 ;; symbol in keyword position
2782 ((symbol? (car args))
2784 (cons (keyword-like-symbol->keyword (car args)) (cdr args))))
2785 ((memq (car args) '(#:no-backtrace #:pure))
2786 (loop (cons (car args) compiled-args)
2789 (error "keyword without value:" (car args)))
2790 ((memq (car args) '(#:use-module #:use-syntax))
2791 (loop (cons* `(list ,@(compile-interface-spec (cadr args)))
2795 ((eq? (car args) #:autoload)
2796 (loop (cons* `(quote ,(caddr args))
2797 `(quote ,(cadr args))
2802 (loop (cons* `(quote ,(cadr args))
2807 (defmacro define-module args
2810 (let ((m (process-define-module
2811 (list ,@(compile-define-module-args args)))))
2812 (set-current-module m)
2815 ;; The guts of the use-modules macro. Add the interfaces of the named
2816 ;; modules to the use-list of the current module, in order.
2818 ;; This function is called by "modules.c". If you change it, be sure
2819 ;; to change scm_c_use_module as well.
2821 (define (process-use-modules module-interface-args)
2822 (let ((interfaces (map (lambda (mif-args)
2823 (or (apply resolve-interface mif-args)
2824 (error "no such module" mif-args)))
2825 module-interface-args)))
2826 (call-with-deferred-observers
2828 (module-use-interfaces! (current-module) interfaces)))))
2830 (defmacro use-modules modules
2833 (process-use-modules
2834 (list ,@(map (lambda (m)
2835 `(list ,@(compile-interface-spec m)))
2839 (defmacro use-syntax (spec)
2843 `((process-use-modules (list
2844 (list ,@(compile-interface-spec spec))))
2845 (set-module-transformer! (current-module)
2846 ,(car (last-pair spec))))
2847 `((set-module-transformer! (current-module) ,spec)))
2850 ;; Dirk:FIXME:: This incorrect (according to R5RS) syntax needs to be changed
2851 ;; as soon as guile supports hygienic macros.
2852 (define define-private define)
2854 (defmacro define-public args
2856 (error "bad syntax" (list 'define-public args)))
2857 (define (defined-name n)
2860 ((pair? n) (defined-name (car n)))
2866 (let ((name (defined-name (car args))))
2868 (define-private ,@args)
2871 (defmacro defmacro-public args
2873 (error "bad syntax" (list 'defmacro-public args)))
2874 (define (defined-name n)
2882 (let ((name (defined-name (car args))))
2884 (export-syntax ,name)
2885 (defmacro ,@args))))))
2887 ;; Export a local variable
2889 ;; This function is called from "modules.c". If you change it, be
2890 ;; sure to update "modules.c" as well.
2892 (define (module-export! m names)
2893 (let ((public-i (module-public-interface m)))
2894 (for-each (lambda (name)
2895 (let ((var (module-ensure-local-variable! m name)))
2896 (module-add! public-i name var)))
2899 (define (module-replace! m names)
2900 (let ((public-i (module-public-interface m)))
2901 (for-each (lambda (name)
2902 (let ((var (module-ensure-local-variable! m name)))
2903 (set-object-property! var 'replace #t)
2904 (module-add! public-i name var)))
2907 ;; Re-export a imported variable
2909 (define (module-re-export! m names)
2910 (let ((public-i (module-public-interface m)))
2911 (for-each (lambda (name)
2912 (let ((var (module-variable m name)))
2914 (error "Undefined variable:" name))
2915 ((eq? var (module-local-variable m name))
2916 (error "re-exporting local variable:" name))
2918 (module-add! public-i name var)))))
2921 (defmacro export names
2922 `(call-with-deferred-observers
2924 (module-export! (current-module) ',names))))
2926 (defmacro re-export names
2927 `(call-with-deferred-observers
2929 (module-re-export! (current-module) ',names))))
2931 (defmacro export-syntax names
2934 (defmacro re-export-syntax names
2935 `(re-export ,@names))
2937 (define load load-module)
2941 ;;; {Compiler interface}
2943 ;;; The full compiler interface can be found in (system). Here we put a
2944 ;;; few useful procedures into the global namespace.
2946 (module-autoload! the-scm-module
2947 '(system base compile)
2949 compile-time-environment))
2957 (define make-mutable-parameter
2958 (let ((make (lambda (fluid converter)
2962 (fluid-set! fluid (converter (car args))))))))
2963 (lambda (init . converter)
2964 (let ((fluid (make-fluid))
2965 (converter (if (null? converter)
2968 (fluid-set! fluid (converter init))
2969 (make fluid converter)))))
2973 ;;; {Handling of duplicate imported bindings}
2976 ;; Duplicate handlers take the following arguments:
2978 ;; module importing module
2979 ;; name conflicting name
2980 ;; int1 old interface where name occurs
2981 ;; val1 value of binding in old interface
2982 ;; int2 new interface where name occurs
2983 ;; val2 value of binding in new interface
2984 ;; var previous resolution or #f
2985 ;; val value of previous resolution
2987 ;; A duplicate handler can take three alternative actions:
2989 ;; 1. return #f => leave responsibility to next handler
2990 ;; 2. exit with an error
2991 ;; 3. return a variable resolving the conflict
2994 (define duplicate-handlers
2995 (let ((m (make-module 7)))
2997 (define (check module name int1 val1 int2 val2 var val)
2998 (scm-error 'misc-error
3000 "~A: `~A' imported from both ~A and ~A"
3001 (list (module-name module)
3007 (define (warn module name int1 val1 int2 val2 var val)
3008 (format (current-error-port)
3009 "WARNING: ~A: `~A' imported from both ~A and ~A\n"
3010 (module-name module)
3016 (define (replace module name int1 val1 int2 val2 var val)
3017 (let ((old (or (and var (object-property var 'replace) var)
3018 (module-variable int1 name)))
3019 (new (module-variable int2 name)))
3020 (if (object-property old 'replace)
3021 (and (or (eq? old new)
3022 (not (object-property new 'replace)))
3024 (and (object-property new 'replace)
3027 (define (warn-override-core module name int1 val1 int2 val2 var val)
3028 (and (eq? int1 the-scm-module)
3030 (format (current-error-port)
3031 "WARNING: ~A: imported module ~A overrides core binding `~A'\n"
3032 (module-name module)
3035 (module-local-variable int2 name))))
3037 (define (first module name int1 val1 int2 val2 var val)
3038 (or var (module-local-variable int1 name)))
3040 (define (last module name int1 val1 int2 val2 var val)
3041 (module-local-variable int2 name))
3043 (define (noop module name int1 val1 int2 val2 var val)
3046 (set-module-name! m 'duplicate-handlers)
3047 (set-module-kind! m 'interface)
3048 (module-define! m 'check check)
3049 (module-define! m 'warn warn)
3050 (module-define! m 'replace replace)
3051 (module-define! m 'warn-override-core warn-override-core)
3052 (module-define! m 'first first)
3053 (module-define! m 'last last)
3054 (module-define! m 'merge-generics noop)
3055 (module-define! m 'merge-accessors noop)
3058 (define (lookup-duplicates-handlers handler-names)
3060 (map (lambda (handler-name)
3061 (or (module-symbol-local-binding
3062 duplicate-handlers handler-name #f)
3063 (error "invalid duplicate handler name:"
3065 (if (list? handler-names)
3067 (list handler-names)))))
3069 (define default-duplicate-binding-procedures
3070 (make-mutable-parameter #f))
3072 (define default-duplicate-binding-handler
3073 (make-mutable-parameter '(replace warn-override-core warn last)
3074 (lambda (handler-names)
3075 (default-duplicate-binding-procedures
3076 (lookup-duplicates-handlers handler-names))
3081 ;;; {`cond-expand' for SRFI-0 support.}
3083 ;;; This syntactic form expands into different commands or
3084 ;;; definitions, depending on the features provided by the Scheme
3090 ;;; --> (cond-expand <cond-expand-clause>+)
3091 ;;; | (cond-expand <cond-expand-clause>* (else <command-or-definition>))
3092 ;;; <cond-expand-clause>
3093 ;;; --> (<feature-requirement> <command-or-definition>*)
3094 ;;; <feature-requirement>
3095 ;;; --> <feature-identifier>
3096 ;;; | (and <feature-requirement>*)
3097 ;;; | (or <feature-requirement>*)
3098 ;;; | (not <feature-requirement>)
3099 ;;; <feature-identifier>
3100 ;;; --> <a symbol which is the name or alias of a SRFI>
3102 ;;; Additionally, this implementation provides the
3103 ;;; <feature-identifier>s `guile' and `r5rs', so that programs can
3104 ;;; determine the implementation type and the supported standard.
3106 ;;; Currently, the following feature identifiers are supported:
3108 ;;; guile r5rs srfi-0 srfi-4 srfi-6 srfi-13 srfi-14 srfi-55 srfi-61
3110 ;;; Remember to update the features list when adding more SRFIs.
3113 (define %cond-expand-features
3114 ;; Adjust the above comment when changing this.
3117 srfi-0 ;; cond-expand itself
3118 srfi-4 ;; homogenous numeric vectors
3119 srfi-6 ;; open-input-string etc, in the guile core
3120 srfi-13 ;; string library
3121 srfi-14 ;; character sets
3122 srfi-55 ;; require-extension
3123 srfi-61 ;; general cond clause
3126 ;; This table maps module public interfaces to the list of features.
3128 (define %cond-expand-table (make-hash-table 31))
3130 ;; Add one or more features to the `cond-expand' feature list of the
3133 (define (cond-expand-provide module features)
3134 (let ((mod (module-public-interface module)))
3136 (hashq-set! %cond-expand-table mod
3137 (append (hashq-ref %cond-expand-table mod '())
3141 (procedure->memoizing-macro
3143 (let ((clauses (cdr exp))
3144 (syntax-error (lambda (cl)
3145 (error "invalid clause in `cond-expand'" cl))))
3151 (or (memq clause %cond-expand-features)
3152 (let lp ((uses (module-uses (env-module env))))
3155 (hashq-ref %cond-expand-table
3161 ((eq? 'and (car clause))
3162 (let lp ((l (cdr clause)))
3166 (and (test-clause (car l)) (lp (cdr l))))
3168 (syntax-error clause)))))
3169 ((eq? 'or (car clause))
3170 (let lp ((l (cdr clause)))
3174 (or (test-clause (car l)) (lp (cdr l))))
3176 (syntax-error clause)))))
3177 ((eq? 'not (car clause))
3178 (cond ((not (pair? (cdr clause)))
3179 (syntax-error clause))
3180 ((pair? (cddr clause))
3181 ((syntax-error clause))))
3182 (not (test-clause (cadr clause))))
3184 (syntax-error clause))))
3186 (syntax-error clause))))))
3187 (let lp ((c clauses))
3190 (error "Unfulfilled `cond-expand'"))
3193 ((not (pair? (car c)))
3194 (syntax-error (car c)))
3195 ((test-clause (caar c))
3196 `(begin ,@(cdar c)))
3197 ((eq? (caar c) 'else)
3200 `(begin ,@(cdar c)))
3202 (lp (cdr c))))))))))
3204 ;; This procedure gets called from the startup code with a list of
3205 ;; numbers, which are the numbers of the SRFIs to be loaded on startup.
3207 (define (use-srfis srfis)
3208 (process-use-modules
3210 (list (list 'srfi (string->symbol
3211 (string-append "srfi-" (number->string num))))))
3216 ;;; srfi-55: require-extension
3219 (define-macro (require-extension extension-spec)
3220 ;; This macro only handles the srfi extension, which, at present, is
3221 ;; the only one defined by the standard.
3222 (if (not (pair? extension-spec))
3223 (scm-error 'wrong-type-arg "require-extension"
3224 "Not an extension: ~S" (list extension-spec) #f))
3225 (let ((extension (car extension-spec))
3226 (extension-args (cdr extension-spec)))
3229 (let ((use-list '()))
3232 (if (not (integer? i))
3233 (scm-error 'wrong-type-arg "require-extension"
3234 "Invalid srfi name: ~S" (list i) #f))
3235 (let ((srfi-sym (string->symbol
3236 (string-append "srfi-" (number->string i)))))
3237 (if (not (memq srfi-sym %cond-expand-features))
3238 (set! use-list (cons `(use-modules (srfi ,srfi-sym))
3241 (if (pair? use-list)
3242 ;; i.e. (begin (use-modules x) (use-modules y) (use-modules z))
3243 `(begin ,@(reverse! use-list)))))
3246 'wrong-type-arg "require-extension"
3247 "Not a recognized extension type: ~S" (list extension) #f)))))
3251 ;;; {Load emacs interface support if emacs option is given.}
3254 (define (named-module-use! user usee)
3255 (module-use! (resolve-module user) (resolve-interface usee)))
3257 (define (load-emacs-interface)
3258 (and (provided? 'debug-extensions)
3259 (debug-enable 'backtrace))
3260 (named-module-use! '(guile-user) '(ice-9 emacs)))
3264 (define using-readline?
3265 (let ((using-readline? (make-fluid)))
3266 (make-procedure-with-setter
3267 (lambda () (fluid-ref using-readline?))
3268 (lambda (v) (fluid-set! using-readline? v)))))
3271 (let ((guile-user-module (resolve-module '(guile-user))))
3273 ;; Load emacs interface support if emacs option is given.
3274 (if (and (module-defined? guile-user-module 'use-emacs-interface)
3275 (module-ref guile-user-module 'use-emacs-interface))
3276 (load-emacs-interface))
3278 ;; Use some convenient modules (in reverse order)
3280 (set-current-module guile-user-module)
3281 (process-use-modules
3286 (if (provided? 'regex)
3289 (if (provided? 'threads)
3290 '(((ice-9 threads)))
3292 ;; load debugger on demand
3293 (module-autoload! guile-user-module '(ice-9 debugger) '(debug))
3295 ;; Note: SIGFPE, SIGSEGV and SIGBUS are actually "query-only" (see
3296 ;; scmsigs.c scm_sigaction_for_thread), so the handlers setup here have
3298 (let ((old-handlers #f)
3299 (start-repl (module-ref (resolve-interface '(system repl repl))
3301 (signals (if (provided? 'posix)
3302 `((,SIGINT . "User interrupt")
3303 (,SIGFPE . "Arithmetic error")
3305 . "Bad memory access (Segmentation violation)"))
3307 ;; no SIGBUS on mingw
3308 (if (defined? 'SIGBUS)
3309 (set! signals (acons SIGBUS "Bad memory access (bus error)"
3316 (let ((make-handler (lambda (msg)
3318 ;; Make a backup copy of the stack
3319 (fluid-set! before-signal-stack
3320 (fluid-ref the-last-stack))
3328 (map (lambda (sig-msg)
3329 (sigaction (car sig-msg)
3330 (make-handler (cdr sig-msg))))
3333 ;; the protected thunk.
3335 (let ((status (start-repl 'scheme)))
3336 (run-hook exit-hook)
3341 (map (lambda (sig-msg old-handler)
3342 (if (not (car old-handler))
3343 ;; restore original C handler.
3344 (sigaction (car sig-msg) #f)
3345 ;; restore Scheme handler, SIG_IGN or SIG_DFL.
3346 (sigaction (car sig-msg)
3348 (cdr old-handler))))
3349 signals old-handlers))))))
3351 ;;; This hook is run at the very end of an interactive session.
3353 (define exit-hook (make-hook))
3357 ;;; {Deprecated stuff}
3361 (define (feature? sym)
3362 (issue-deprecation-warning
3363 "`feature?' is deprecated. Use `provided?' instead.")
3367 (primitive-load-path "ice-9/deprecated"))
3371 ;;; Place the user in the guile-user module.
3374 (define-module (guile-user))
3376 ;;; boot-9.scm ends here