3 ;;;; Copyright (C) 1995,1996,1997,1998,1999,2000,2001,2002,2003,2004,2005,2006,2007,2009
4 ;;;; Free Software Foundation, Inc.
6 ;;;; This library is free software; you can redistribute it and/or
7 ;;;; modify it under the terms of the GNU Lesser General Public
8 ;;;; License as published by the Free Software Foundation; either
9 ;;;; version 2.1 of the License, or (at your option) any later version.
11 ;;;; This library is distributed in the hope that it will be useful,
12 ;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
13 ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 ;;;; Lesser General Public License for more details.
16 ;;;; You should have received a copy of the GNU Lesser General Public
17 ;;;; License along with this library; if not, write to the Free Software
18 ;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
25 ;;; This file is the first thing loaded into Guile. It adds many mundane
26 ;;; definitions and a few that are interesting.
28 ;;; The module system (hence the hierarchical namespace) are defined in this
36 ;; Before compiling, make sure any symbols are resolved in the (guile)
37 ;; module, the primary location of those symbols, rather than in
38 ;; (guile-user), the default module that we compile in.
41 (set-current-module (resolve-module '(guile))))
46 (primitive-load-path "ice-9/r4rs")
50 ;;; {Simple Debugging Tools}
53 ;; peek takes any number of arguments, writes them to the
54 ;; current ouput port, and returns the last argument.
55 ;; It is handy to wrap around an expression to look at
56 ;; a value each time is evaluated, e.g.:
58 ;; (+ 10 (troublesome-fn))
59 ;; => (+ 10 (pk 'troublesome-fn-returned (troublesome-fn)))
62 (define (peek . stuff)
67 (car (last-pair stuff)))
71 (define (warn . stuff)
72 (with-output-to-port (current-error-port)
75 (display ";;; WARNING ")
78 (car (last-pair stuff)))))
86 (if (not (memq sym *features*))
87 (set! *features* (cons sym *features*))))
89 ;; Return #t iff FEATURE is available to this Guile interpreter. In SLIB,
90 ;; provided? also checks to see if the module is available. We should do that
93 (define (provided? feature)
94 (and (memq feature *features*) #t))
98 ;;; {and-map and or-map}
100 ;;; (and-map fn lst) is like (and (fn (car lst)) (fn (cadr lst)) (fn...) ...)
101 ;;; (or-map fn lst) is like (or (fn (car lst)) (fn (cadr lst)) (fn...) ...)
106 ;; Apply f to successive elements of l until exhaustion or f returns #f.
107 ;; If returning early, return #f. Otherwise, return the last value returned
108 ;; by f. If f has never been called because l is empty, return #t.
110 (define (and-map f lst)
111 (let loop ((result #t)
116 (loop (f (car l)) (cdr l))))))
120 ;; Apply f to successive elements of l until exhaustion or while f returns #f.
121 ;; If returning early, return the return value of f.
123 (define (or-map f lst)
124 (let loop ((result #f)
128 (loop (f (car l)) (cdr l))))))
132 ;; let format alias simple-format until the more complete version is loaded
134 (define format simple-format)
136 ;; this is scheme wrapping the C code so the final pred call is a tail call,
138 (define (string-any char_pred s . rest)
139 (let ((start (if (null? rest)
141 (end (if (or (null? rest) (null? (cdr rest)))
142 (string-length s) (cadr rest))))
143 (if (and (procedure? char_pred)
145 (<= end (string-length s))) ;; let c-code handle range error
146 (or (string-any-c-code char_pred s start (1- end))
147 (char_pred (string-ref s (1- end))))
148 (string-any-c-code char_pred s start end))))
150 ;; this is scheme wrapping the C code so the final pred call is a tail call,
152 (define (string-every char_pred s . rest)
153 (let ((start (if (null? rest)
155 (end (if (or (null? rest) (null? (cdr rest)))
156 (string-length s) (cadr rest))))
157 (if (and (procedure? char_pred)
159 (<= end (string-length s))) ;; let c-code handle range error
160 (and (string-every-c-code char_pred s start (1- end))
161 (char_pred (string-ref s (1- end))))
162 (string-every-c-code char_pred s start end))))
164 ;; A variant of string-fill! that we keep for compatability
166 (define (substring-fill! str start end fill)
167 (string-fill! str fill start end))
171 ;; Define a minimal stub of the module API for psyntax, before modules
173 (define (module-name x)
175 (define (module-define! module sym val)
176 (let ((v (hashq-ref (%get-pre-modules-obarray) sym)))
178 (variable-set! v val)
179 (hashq-set! (%get-pre-modules-obarray) sym
180 (make-variable val)))))
181 (define (module-ref module sym)
182 (let ((v (module-variable module sym)))
183 (if v (variable-ref v) (error "badness!" (pk module) (pk sym)))))
184 (define (resolve-module . args)
187 ;; Output hook for syncase. It's here because we want to be able to
188 ;; replace its definition, for compiling; but that isn't implemented
190 (define (make-module-ref mod var kind)
192 ((public) (if mod `(@ ,mod ,var) var))
193 ((private) (if (and mod (not (equal? mod (module-name (current-module)))))
197 ((hygiene) (if (and mod
198 (not (equal? mod (module-name (current-module))))
199 (module-variable (resolve-module mod) var))
202 (else (error "foo" mod var kind))))
204 ;; Input hook to syncase -- so that we might be able to pass annotated
205 ;; expressions in. Currently disabled. Maybe we should just use
206 ;; source-properties directly.
207 (define (annotation? x) #f)
209 ;; API provided by psyntax
210 (define syntax-violation #f)
211 (define datum->syntax #f)
212 (define syntax->datum #f)
213 (define identifier? #f)
214 (define generate-temporaries #f)
215 (define bound-identifier=? #f)
216 (define free-identifier=? #f)
217 (define sc-expand #f)
219 ;; $sc-expand is an implementation detail of psyntax. It is used by
220 ;; expanded macros, to dispatch an input against a set of patterns.
221 (define $sc-dispatch #f)
224 (primitive-load-path "ice-9/psyntax-pp")
226 ;; %pre-modules-transformer is the Scheme expander from now until the
227 ;; module system has booted up.
228 (define %pre-modules-transformer sc-expand)
235 (define-syntax define-macro
239 ((_ (macro . args) doc body1 body ...)
240 (string? (syntax->datum (syntax doc)))
241 (syntax (define-macro macro doc (lambda args body1 body ...))))
242 ((_ (macro . args) body ...)
243 (syntax (define-macro macro #f (lambda args body ...))))
244 ((_ macro doc transformer)
245 (or (string? (syntax->datum (syntax doc)))
246 (not (syntax->datum (syntax doc))))
253 (let ((v (syntax->datum (syntax args))))
254 (datum->syntax y (apply transformer v))))))))))))
256 (define-syntax defmacro
258 "Define a defmacro, with the old lispy defun syntax."
260 ((_ macro args doc body1 body ...)
261 (string? (syntax->datum (syntax doc)))
262 (syntax (define-macro macro doc (lambda args body1 body ...))))
263 ((_ macro args body ...)
264 (syntax (define-macro macro #f (lambda args body ...)))))))
272 ;;; Depends on: defmacro
275 (defmacro begin-deprecated forms
276 (if (include-deprecated-features)
282 ;;; {Trivial Functions}
285 (define (identity x) x)
286 (define (and=> value procedure) (and value (procedure value)))
287 (define call/cc call-with-current-continuation)
289 ;;; apply-to-args is functionally redundant with apply and, worse,
290 ;;; is less general than apply since it only takes two arguments.
292 ;;; On the other hand, apply-to-args is a syntacticly convenient way to
293 ;;; perform binding in many circumstances when the "let" family of
294 ;;; of forms don't cut it. E.g.:
296 ;;; (apply-to-args (return-3d-mouse-coords)
301 (define (apply-to-args args fn) (apply fn args))
303 (defmacro false-if-exception (expr)
304 `(catch #t (lambda () ,expr)
309 ;;; {General Properties}
312 ;; This is a more modern interface to properties. It will replace all
313 ;; other property-like things eventually.
315 (define (make-object-property)
316 (let ((prop (primitive-make-property #f)))
317 (make-procedure-with-setter
318 (lambda (obj) (primitive-property-ref prop obj))
319 (lambda (obj val) (primitive-property-set! prop obj val)))))
323 ;;; {Symbol Properties}
326 (define (symbol-property sym prop)
327 (let ((pair (assoc prop (symbol-pref sym))))
328 (and pair (cdr pair))))
330 (define (set-symbol-property! sym prop val)
331 (let ((pair (assoc prop (symbol-pref sym))))
334 (symbol-pset! sym (acons prop val (symbol-pref sym))))))
336 (define (symbol-property-remove! sym prop)
337 (let ((pair (assoc prop (symbol-pref sym))))
339 (symbol-pset! sym (delq! pair (symbol-pref sym))))))
346 (define (array-shape a)
347 (map (lambda (ind) (if (number? ind) (list 0 (+ -1 ind)) ind))
348 (array-dimensions a)))
355 (define (kw-arg-ref args kw)
356 (let ((rem (member kw args)))
357 (and rem (pair? (cdr rem)) (cadr rem))))
364 (define (struct-layout s)
365 (struct-ref (struct-vtable s) vtable-index-layout))
372 ;; Printing records: by default, records are printed as
374 ;; #<type-name field1: val1 field2: val2 ...>
376 ;; You can change that by giving a custom printing function to
377 ;; MAKE-RECORD-TYPE (after the list of field symbols). This function
378 ;; will be called like
380 ;; (<printer> object port)
382 ;; It should print OBJECT to PORT.
384 (define (inherit-print-state old-port new-port)
385 (if (get-print-state old-port)
386 (port-with-print-state new-port (get-print-state old-port))
389 ;; 0: type-name, 1: fields
390 (define record-type-vtable
391 (make-vtable-vtable "prpr" 0
393 (cond ((eq? s record-type-vtable)
394 (display "#<record-type-vtable>" p))
396 (display "#<record-type " p)
397 (display (record-type-name s) p)
400 (define (record-type? obj)
401 (and (struct? obj) (eq? record-type-vtable (struct-vtable obj))))
403 (define (make-record-type type-name fields . opt)
404 (let ((printer-fn (and (pair? opt) (car opt))))
405 (let ((struct (make-struct record-type-vtable 0
408 (map (lambda (f) "pw") fields)))
412 (display type-name p)
413 (let loop ((fields fields)
416 ((not (null? fields))
418 (display (car fields) p)
420 (display (struct-ref s off) p)
421 (loop (cdr fields) (+ 1 off)))))
424 (copy-tree fields))))
425 ;; Temporary solution: Associate a name to the record type descriptor
426 ;; so that the object system can create a wrapper class for it.
427 (set-struct-vtable-name! struct (if (symbol? type-name)
429 (string->symbol type-name)))
432 (define (record-type-name obj)
433 (if (record-type? obj)
434 (struct-ref obj vtable-offset-user)
435 (error 'not-a-record-type obj)))
437 (define (record-type-fields obj)
438 (if (record-type? obj)
439 (struct-ref obj (+ 1 vtable-offset-user))
440 (error 'not-a-record-type obj)))
442 (define (record-constructor rtd . opt)
443 (let ((field-names (if (pair? opt) (car opt) (record-type-fields rtd))))
445 `(lambda ,field-names
446 (make-struct ',rtd 0 ,@(map (lambda (f)
447 (if (memq f field-names)
450 (record-type-fields rtd)))))))
452 (define (record-predicate rtd)
453 (lambda (obj) (and (struct? obj) (eq? rtd (struct-vtable obj)))))
455 (define (%record-type-error rtd obj) ;; private helper
456 (or (eq? rtd (record-type-descriptor obj))
457 (scm-error 'wrong-type-arg "%record-type-check"
458 "Wrong type record (want `~S'): ~S"
459 (list (record-type-name rtd) obj)
462 (define (record-accessor rtd field-name)
463 (let ((pos (list-index (record-type-fields rtd) field-name)))
465 (error 'no-such-field field-name))
467 (if (eq? (struct-vtable obj) rtd)
469 (%record-type-error rtd obj)))))
471 (define (record-modifier rtd field-name)
472 (let ((pos (list-index (record-type-fields rtd) field-name)))
474 (error 'no-such-field field-name))
476 (if (eq? (struct-vtable obj) rtd)
477 (struct-set! obj pos val)
478 (%record-type-error rtd obj)))))
480 (define (record? obj)
481 (and (struct? obj) (record-type? (struct-vtable obj))))
483 (define (record-type-descriptor obj)
486 (error 'not-a-record obj)))
495 (define (->bool x) (not (not x)))
502 (define (symbol-append . args)
503 (string->symbol (apply string-append (map symbol->string args))))
505 (define (list->symbol . args)
506 (string->symbol (apply list->string args)))
508 (define (symbol . args)
509 (string->symbol (apply string args)))
516 (define (list-index l k)
522 (loop (+ n 1) (cdr l))))))
526 (if (provided? 'posix)
527 (primitive-load-path "ice-9/posix"))
529 (if (provided? 'socket)
530 (primitive-load-path "ice-9/networking"))
532 ;; For reference, Emacs file-exists-p uses stat in this same way.
533 ;; ENHANCE-ME: Catching an exception from stat is a bit wasteful, do this in
534 ;; C where all that's needed is to inspect the return from stat().
536 (if (provided? 'posix)
538 (->bool (false-if-exception (stat str))))
540 (let ((port (catch 'system-error (lambda () (open-file str OPEN_READ))
542 (if port (begin (close-port port) #t)
545 (define file-is-directory?
546 (if (provided? 'posix)
548 (eq? (stat:type (stat str)) 'directory))
550 (let ((port (catch 'system-error
551 (lambda () (open-file (string-append str "/.")
554 (if port (begin (close-port port) #t)
557 (define (has-suffix? str suffix)
558 (string-suffix? suffix str))
560 (define (system-error-errno args)
561 (if (eq? (car args) 'system-error)
562 (car (list-ref args 4))
570 (define (error . args)
573 (scm-error 'misc-error #f "?" #f #f)
574 (let loop ((msg "~A")
576 (if (not (null? rest))
577 (loop (string-append msg " ~S")
579 (scm-error 'misc-error #f msg args #f)))))
581 ;; bad-throw is the hook that is called upon a throw to a an unhandled
582 ;; key (unless the throw has four arguments, in which case
583 ;; it's usually interpreted as an error throw.)
584 ;; If the key has a default handler (a throw-handler-default property),
585 ;; it is applied to the throw.
587 (define (bad-throw key . args)
588 (let ((default (symbol-property key 'throw-handler-default)))
589 (or (and default (apply default key args))
590 (apply error "unhandled-exception:" key args))))
594 (define (tm:sec obj) (vector-ref obj 0))
595 (define (tm:min obj) (vector-ref obj 1))
596 (define (tm:hour obj) (vector-ref obj 2))
597 (define (tm:mday obj) (vector-ref obj 3))
598 (define (tm:mon obj) (vector-ref obj 4))
599 (define (tm:year obj) (vector-ref obj 5))
600 (define (tm:wday obj) (vector-ref obj 6))
601 (define (tm:yday obj) (vector-ref obj 7))
602 (define (tm:isdst obj) (vector-ref obj 8))
603 (define (tm:gmtoff obj) (vector-ref obj 9))
604 (define (tm:zone obj) (vector-ref obj 10))
606 (define (set-tm:sec obj val) (vector-set! obj 0 val))
607 (define (set-tm:min obj val) (vector-set! obj 1 val))
608 (define (set-tm:hour obj val) (vector-set! obj 2 val))
609 (define (set-tm:mday obj val) (vector-set! obj 3 val))
610 (define (set-tm:mon obj val) (vector-set! obj 4 val))
611 (define (set-tm:year obj val) (vector-set! obj 5 val))
612 (define (set-tm:wday obj val) (vector-set! obj 6 val))
613 (define (set-tm:yday obj val) (vector-set! obj 7 val))
614 (define (set-tm:isdst obj val) (vector-set! obj 8 val))
615 (define (set-tm:gmtoff obj val) (vector-set! obj 9 val))
616 (define (set-tm:zone obj val) (vector-set! obj 10 val))
618 (define (tms:clock obj) (vector-ref obj 0))
619 (define (tms:utime obj) (vector-ref obj 1))
620 (define (tms:stime obj) (vector-ref obj 2))
621 (define (tms:cutime obj) (vector-ref obj 3))
622 (define (tms:cstime obj) (vector-ref obj 4))
624 (define file-position ftell)
625 (define (file-set-position port offset . whence)
626 (let ((whence (if (eq? whence '()) SEEK_SET (car whence))))
627 (seek port offset whence)))
629 (define (move->fdes fd/port fd)
630 (cond ((integer? fd/port)
631 (dup->fdes fd/port fd)
635 (primitive-move->fdes fd/port fd)
636 (set-port-revealed! fd/port 1)
639 (define (release-port-handle port)
640 (let ((revealed (port-revealed port)))
642 (set-port-revealed! port (- revealed 1)))))
644 (define (dup->port port/fd mode . maybe-fd)
645 (let ((port (fdopen (apply dup->fdes port/fd maybe-fd)
648 (set-port-revealed! port 1))
651 (define (dup->inport port/fd . maybe-fd)
652 (apply dup->port port/fd "r" maybe-fd))
654 (define (dup->outport port/fd . maybe-fd)
655 (apply dup->port port/fd "w" maybe-fd))
657 (define (dup port/fd . maybe-fd)
658 (if (integer? port/fd)
659 (apply dup->fdes port/fd maybe-fd)
660 (apply dup->port port/fd (port-mode port/fd) maybe-fd)))
662 (define (duplicate-port port modes)
663 (dup->port port modes))
665 (define (fdes->inport fdes)
666 (let loop ((rest-ports (fdes->ports fdes)))
667 (cond ((null? rest-ports)
668 (let ((result (fdopen fdes "r")))
669 (set-port-revealed! result 1)
671 ((input-port? (car rest-ports))
672 (set-port-revealed! (car rest-ports)
673 (+ (port-revealed (car rest-ports)) 1))
676 (loop (cdr rest-ports))))))
678 (define (fdes->outport fdes)
679 (let loop ((rest-ports (fdes->ports fdes)))
680 (cond ((null? rest-ports)
681 (let ((result (fdopen fdes "w")))
682 (set-port-revealed! result 1)
684 ((output-port? (car rest-ports))
685 (set-port-revealed! (car rest-ports)
686 (+ (port-revealed (car rest-ports)) 1))
689 (loop (cdr rest-ports))))))
691 (define (port->fdes port)
692 (set-port-revealed! port (+ (port-revealed port) 1))
695 (define (setenv name value)
697 (putenv (string-append name "=" value))
700 (define (unsetenv name)
701 "Remove the entry for NAME from the environment."
709 ;;; Here for backward compatability
711 (define scheme-file-suffix (lambda () ".scm"))
713 (define (in-vicinity vicinity file)
714 (let ((tail (let ((len (string-length vicinity)))
717 (string-ref vicinity (- len 1))))))
718 (string-append vicinity
727 ;;; {Help for scm_shell}
729 ;;; The argument-processing code used by Guile-based shells generates
730 ;;; Scheme code based on the argument list. This page contains help
731 ;;; functions for the code it generates.
734 (define (command-line) (program-arguments))
736 ;; This is mostly for the internal use of the code generated by
737 ;; scm_compile_shell_switches.
739 (define (turn-on-debugging)
740 (debug-enable 'debug)
741 (debug-enable 'backtrace)
742 (read-enable 'positions))
744 (define (load-user-init)
745 (let* ((home (or (getenv "HOME")
746 (false-if-exception (passwd:dir (getpwuid (getuid))))
747 "/")) ;; fallback for cygwin etc.
748 (init-file (in-vicinity home ".guile")))
749 (if (file-exists? init-file)
750 (primitive-load init-file))))
754 ;;; {The interpreter stack}
757 (defmacro start-stack (tag exp)
758 `(%start-stack ,tag (lambda () ,exp)))
762 ;;; {Loading by paths}
765 ;;; Load a Scheme source file named NAME, searching for it in the
766 ;;; directories listed in %load-path, and applying each of the file
767 ;;; name extensions listed in %load-extensions.
768 (define (load-from-path name)
769 (start-stack 'load-stack
770 (primitive-load-path name)))
772 (define %load-verbosely #f)
773 (define (assert-load-verbosity v) (set! %load-verbosely v))
775 (define (%load-announce file)
777 (with-output-to-port (current-error-port)
785 (set! %load-hook %load-announce)
787 (define (load name . reader)
788 (with-fluid* current-reader (and (pair? reader) (car reader))
790 (start-stack 'load-stack
791 (primitive-load name)))))
795 ;;; {Transcendental Functions}
797 ;;; Derived from "Transcen.scm", Complex trancendental functions for SCM.
798 ;;; Written by Jerry D. Hedden, (C) FSF.
799 ;;; See the file `COPYING' for terms applying to this program.
803 (let ((integer-expt integer-expt))
805 (cond ((and (exact? z2) (integer? z2))
806 (integer-expt z1 z2))
807 ((and (real? z2) (real? z1) (>= z1 0))
810 (exp (* z2 (log z1))))))))
813 (if (real? z) ($sinh z)
814 (let ((x (real-part z)) (y (imag-part z)))
815 (make-rectangular (* ($sinh x) ($cos y))
816 (* ($cosh x) ($sin y))))))
818 (if (real? z) ($cosh z)
819 (let ((x (real-part z)) (y (imag-part z)))
820 (make-rectangular (* ($cosh x) ($cos y))
821 (* ($sinh x) ($sin y))))))
823 (if (real? z) ($tanh z)
824 (let* ((x (* 2 (real-part z)))
825 (y (* 2 (imag-part z)))
826 (w (+ ($cosh x) ($cos y))))
827 (make-rectangular (/ ($sinh x) w) (/ ($sin y) w)))))
830 (if (real? z) ($asinh z)
831 (log (+ z (sqrt (+ (* z z) 1))))))
834 (if (and (real? z) (>= z 1))
836 (log (+ z (sqrt (- (* z z) 1))))))
839 (if (and (real? z) (> z -1) (< z 1))
841 (/ (log (/ (+ 1 z) (- 1 z))) 2)))
844 (if (real? z) ($sin z)
845 (let ((x (real-part z)) (y (imag-part z)))
846 (make-rectangular (* ($sin x) ($cosh y))
847 (* ($cos x) ($sinh y))))))
849 (if (real? z) ($cos z)
850 (let ((x (real-part z)) (y (imag-part z)))
851 (make-rectangular (* ($cos x) ($cosh y))
852 (- (* ($sin x) ($sinh y)))))))
854 (if (real? z) ($tan z)
855 (let* ((x (* 2 (real-part z)))
856 (y (* 2 (imag-part z)))
857 (w (+ ($cos x) ($cosh y))))
858 (make-rectangular (/ ($sin x) w) (/ ($sinh y) w)))))
861 (if (and (real? z) (>= z -1) (<= z 1))
863 (* -i (asinh (* +i z)))))
866 (if (and (real? z) (>= z -1) (<= z 1))
868 (+ (/ (angle -1) 2) (* +i (asinh (* +i z))))))
872 (if (real? z) ($atan z)
873 (/ (log (/ (- +i z) (+ +i z))) +2i))
878 ;;; {Reader Extensions}
880 ;;; Reader code for various "#c" forms.
883 (read-hash-extend #\' (lambda (c port)
886 (define read-eval? (make-fluid))
887 (fluid-set! read-eval? #f)
888 (read-hash-extend #\.
890 (if (fluid-ref read-eval?)
891 (eval (read port) (interaction-environment))
893 "#. read expansion found and read-eval? is #f."))))
897 ;;; {Command Line Options}
900 (define (get-option argv kw-opts kw-args return)
905 ((or (not (eq? #\- (string-ref (car argv) 0)))
906 (eq? (string-length (car argv)) 1))
907 (return 'normal-arg (car argv) (cdr argv)))
909 ((eq? #\- (string-ref (car argv) 1))
910 (let* ((kw-arg-pos (or (string-index (car argv) #\=)
911 (string-length (car argv))))
912 (kw (symbol->keyword (substring (car argv) 2 kw-arg-pos)))
913 (kw-opt? (member kw kw-opts))
914 (kw-arg? (member kw kw-args))
915 (arg (or (and (not (eq? kw-arg-pos (string-length (car argv))))
916 (substring (car argv)
918 (string-length (car argv))))
920 (begin (set! argv (cdr argv)) (car argv))))))
921 (if (or kw-opt? kw-arg?)
922 (return kw arg (cdr argv))
923 (return 'usage-error kw (cdr argv)))))
926 (let* ((char (substring (car argv) 1 2))
927 (kw (symbol->keyword char)))
931 (let* ((rest-car (substring (car argv) 2 (string-length (car argv))))
932 (new-argv (if (= 0 (string-length rest-car))
934 (cons (string-append "-" rest-car) (cdr argv)))))
935 (return kw #f new-argv)))
938 (let* ((rest-car (substring (car argv) 2 (string-length (car argv))))
939 (arg (if (= 0 (string-length rest-car))
942 (new-argv (if (= 0 (string-length rest-car))
945 (return kw arg new-argv)))
947 (else (return 'usage-error kw argv)))))))
949 (define (for-next-option proc argv kw-opts kw-args)
950 (let loop ((argv argv))
951 (get-option argv kw-opts kw-args
952 (lambda (opt opt-arg argv)
953 (and opt (proc opt opt-arg argv loop))))))
955 (define (display-usage-report kw-desc)
958 (or (eq? (car kw) #t)
961 (help (cadr opt-desc))
962 (opts (car opt-desc))
963 (opts-proper (if (string? (car opts)) (cdr opts) opts))
964 (arg-name (if (string? (car opts))
965 (string-append "<" (car opts) ">")
967 (left-part (string-append
968 (with-output-to-string
970 (map (lambda (x) (display (keyword->symbol x)) (display " "))
973 (middle-part (if (and (< (string-length left-part) 30)
974 (< (string-length help) 40))
975 (make-string (- 30 (string-length left-part)) #\ )
978 (display middle-part)
985 (define (transform-usage-lambda cases)
986 (let* ((raw-usage (delq! 'else (map car cases)))
987 (usage-sans-specials (map (lambda (x)
988 (or (and (not (list? x)) x)
989 (and (symbol? (car x)) #t)
990 (and (boolean? (car x)) #t)
993 (usage-desc (delq! #t usage-sans-specials))
994 (kw-desc (map car usage-desc))
995 (kw-opts (apply append (map (lambda (x) (and (not (string? (car x))) x)) kw-desc)))
996 (kw-args (apply append (map (lambda (x) (and (string? (car x)) (cdr x))) kw-desc)))
997 (transmogrified-cases (map (lambda (case)
998 (cons (let ((opts (car case)))
999 (if (or (boolean? opts) (eq? 'else opts))
1002 ((symbol? (car opts)) opts)
1003 ((boolean? (car opts)) opts)
1004 ((string? (caar opts)) (cdar opts))
1005 (else (car opts)))))
1008 `(let ((%display-usage (lambda () (display-usage-report ',usage-desc))))
1010 (let %next-arg ((%argv %argv))
1014 (lambda (%opt %arg %new-argv)
1016 ,@ transmogrified-cases))))))))
1021 ;;; {Low Level Modules}
1023 ;;; These are the low level data structures for modules.
1025 ;;; Every module object is of the type 'module-type', which is a record
1026 ;;; consisting of the following members:
1028 ;;; - eval-closure: the function that defines for its module the strategy that
1029 ;;; shall be followed when looking up symbols in the module.
1031 ;;; An eval-closure is a function taking two arguments: the symbol to be
1032 ;;; looked up and a boolean value telling whether a binding for the symbol
1033 ;;; should be created if it does not exist yet. If the symbol lookup
1034 ;;; succeeded (either because an existing binding was found or because a new
1035 ;;; binding was created), a variable object representing the binding is
1036 ;;; returned. Otherwise, the value #f is returned. Note that the eval
1037 ;;; closure does not take the module to be searched as an argument: During
1038 ;;; construction of the eval-closure, the eval-closure has to store the
1039 ;;; module it belongs to in its environment. This means, that any
1040 ;;; eval-closure can belong to only one module.
1042 ;;; The eval-closure of a module can be defined arbitrarily. However, three
1043 ;;; special cases of eval-closures are to be distinguished: During startup
1044 ;;; the module system is not yet activated. In this phase, no modules are
1045 ;;; defined and all bindings are automatically stored by the system in the
1046 ;;; pre-modules-obarray. Since no eval-closures exist at this time, the
1047 ;;; functions which require an eval-closure as their argument need to be
1048 ;;; passed the value #f.
1050 ;;; The other two special cases of eval-closures are the
1051 ;;; standard-eval-closure and the standard-interface-eval-closure. Both
1052 ;;; behave equally for the case that no new binding is to be created. The
1053 ;;; difference between the two comes in, when the boolean argument to the
1054 ;;; eval-closure indicates that a new binding shall be created if it is not
1057 ;;; Given that no new binding shall be created, both standard eval-closures
1058 ;;; define the following standard strategy of searching bindings in the
1059 ;;; module: First, the module's obarray is searched for the symbol. Second,
1060 ;;; if no binding for the symbol was found in the module's obarray, the
1061 ;;; module's binder procedure is exececuted. If this procedure did not
1062 ;;; return a binding for the symbol, the modules referenced in the module's
1063 ;;; uses list are recursively searched for a binding of the symbol. If the
1064 ;;; binding can not be found in these modules also, the symbol lookup has
1067 ;;; If a new binding shall be created, the standard-interface-eval-closure
1068 ;;; immediately returns indicating failure. That is, it does not even try
1069 ;;; to look up the symbol. In contrast, the standard-eval-closure would
1070 ;;; first search the obarray, and if no binding was found there, would
1071 ;;; create a new binding in the obarray, therefore not calling the binder
1072 ;;; procedure or searching the modules in the uses list.
1074 ;;; The explanation of the following members obarray, binder and uses
1075 ;;; assumes that the symbol lookup follows the strategy that is defined in
1076 ;;; the standard-eval-closure and the standard-interface-eval-closure.
1078 ;;; - obarray: a hash table that maps symbols to variable objects. In this
1079 ;;; hash table, the definitions are found that are local to the module (that
1080 ;;; is, not imported from other modules). When looking up bindings in the
1081 ;;; module, this hash table is searched first.
1083 ;;; - binder: either #f or a function taking a module and a symbol argument.
1084 ;;; If it is a function it is called after the obarray has been
1085 ;;; unsuccessfully searched for a binding. It then can provide bindings
1086 ;;; that would otherwise not be found locally in the module.
1088 ;;; - uses: a list of modules from which non-local bindings can be inherited.
1089 ;;; These modules are the third place queried for bindings after the obarray
1090 ;;; has been unsuccessfully searched and the binder function did not deliver
1091 ;;; a result either.
1093 ;;; - transformer: either #f or a function taking a scheme expression as
1094 ;;; delivered by read. If it is a function, it will be called to perform
1095 ;;; syntax transformations (e. g. makro expansion) on the given scheme
1096 ;;; expression. The output of the transformer function will then be passed
1097 ;;; to Guile's internal memoizer. This means that the output must be valid
1098 ;;; scheme code. The only exception is, that the output may make use of the
1099 ;;; syntax extensions provided to identify the modules that a binding
1102 ;;; - name: the name of the module. This is used for all kinds of printing
1103 ;;; outputs. In certain places the module name also serves as a way of
1104 ;;; identification. When adding a module to the uses list of another
1105 ;;; module, it is made sure that the new uses list will not contain two
1106 ;;; modules of the same name.
1108 ;;; - kind: classification of the kind of module. The value is (currently?)
1109 ;;; only used for printing. It has no influence on how a module is treated.
1110 ;;; Currently the following values are used when setting the module kind:
1111 ;;; 'module, 'directory, 'interface, 'custom-interface. If no explicit kind
1112 ;;; is set, it defaults to 'module.
1114 ;;; - duplicates-handlers: a list of procedures that get called to make a
1115 ;;; choice between two duplicate bindings when name clashes occur. See the
1116 ;;; `duplicate-handlers' global variable below.
1118 ;;; - observers: a list of procedures that get called when the module is
1121 ;;; - weak-observers: a weak-key hash table of procedures that get called
1122 ;;; when the module is modified. See `module-observe-weak' for details.
1124 ;;; In addition, the module may (must?) contain a binding for
1125 ;;; `%module-public-interface'. This variable should be bound to a module
1126 ;;; representing the exported interface of a module. See the
1127 ;;; `module-public-interface' and `module-export!' procedures.
1129 ;;; !!! warning: The interface to lazy binder procedures is going
1130 ;;; to be changed in an incompatible way to permit all the basic
1131 ;;; module ops to be virtualized.
1133 ;;; (make-module size use-list lazy-binding-proc) => module
1134 ;;; module-{obarray,uses,binder}[|-set!]
1135 ;;; (module? obj) => [#t|#f]
1136 ;;; (module-locally-bound? module symbol) => [#t|#f]
1137 ;;; (module-bound? module symbol) => [#t|#f]
1138 ;;; (module-symbol-locally-interned? module symbol) => [#t|#f]
1139 ;;; (module-symbol-interned? module symbol) => [#t|#f]
1140 ;;; (module-local-variable module symbol) => [#<variable ...> | #f]
1141 ;;; (module-variable module symbol) => [#<variable ...> | #f]
1142 ;;; (module-symbol-binding module symbol opt-value)
1143 ;;; => [ <obj> | opt-value | an error occurs ]
1144 ;;; (module-make-local-var! module symbol) => #<variable...>
1145 ;;; (module-add! module symbol var) => unspecified
1146 ;;; (module-remove! module symbol) => unspecified
1147 ;;; (module-for-each proc module) => unspecified
1148 ;;; (make-scm-module) => module ; a lazy copy of the symhash module
1149 ;;; (set-current-module module) => unspecified
1150 ;;; (current-module) => #<module...>
1156 ;;; {Printing Modules}
1159 ;; This is how modules are printed. You can re-define it.
1160 ;; (Redefining is actually more complicated than simply redefining
1161 ;; %print-module because that would only change the binding and not
1162 ;; the value stored in the vtable that determines how record are
1165 (define (%print-module mod port) ; unused args: depth length style table)
1167 (display (or (module-kind mod) "module") port)
1168 (let ((name (module-name mod)))
1172 (display name port))))
1174 (display (number->string (object-address mod) 16) port)
1179 ;; A module is characterized by an obarray in which local symbols
1180 ;; are interned, a list of modules, "uses", from which non-local
1181 ;; bindings can be inherited, and an optional lazy-binder which
1182 ;; is a (CLOSURE module symbol) which, as a last resort, can provide
1183 ;; bindings that would otherwise not be found locally in the module.
1185 ;; NOTE: If you change anything here, you also need to change
1186 ;; libguile/modules.h.
1189 (make-record-type 'module
1190 '(obarray uses binder eval-closure transformer name kind
1191 duplicates-handlers import-obarray
1192 observers weak-observers)
1195 ;; make-module &opt size uses binder
1197 ;; Create a new module, perhaps with a particular size of obarray,
1198 ;; initial uses list, or binding procedure.
1203 (define (parse-arg index default)
1204 (if (> (length args) index)
1205 (list-ref args index)
1208 (define %default-import-size
1209 ;; Typical number of imported bindings actually used by a module.
1212 (if (> (length args) 3)
1213 (error "Too many args to make-module." args))
1215 (let ((size (parse-arg 0 31))
1216 (uses (parse-arg 1 '()))
1217 (binder (parse-arg 2 #f)))
1219 (if (not (integer? size))
1220 (error "Illegal size to make-module." size))
1221 (if (not (and (list? uses)
1222 (and-map module? uses)))
1223 (error "Incorrect use list." uses))
1224 (if (and binder (not (procedure? binder)))
1226 "Lazy-binder expected to be a procedure or #f." binder))
1228 (let ((module (module-constructor (make-hash-table size)
1229 uses binder #f %pre-modules-transformer
1231 (make-hash-table %default-import-size)
1233 (make-weak-key-hash-table 31))))
1235 ;; We can't pass this as an argument to module-constructor,
1236 ;; because we need it to close over a pointer to the module
1238 (set-module-eval-closure! module (standard-eval-closure module))
1242 (define module-constructor (record-constructor module-type))
1243 (define module-obarray (record-accessor module-type 'obarray))
1244 (define set-module-obarray! (record-modifier module-type 'obarray))
1245 (define module-uses (record-accessor module-type 'uses))
1246 (define set-module-uses! (record-modifier module-type 'uses))
1247 (define module-binder (record-accessor module-type 'binder))
1248 (define set-module-binder! (record-modifier module-type 'binder))
1250 ;; NOTE: This binding is used in libguile/modules.c.
1251 (define module-eval-closure (record-accessor module-type 'eval-closure))
1253 (define module-transformer (record-accessor module-type 'transformer))
1254 (define set-module-transformer! (record-modifier module-type 'transformer))
1255 ;; (define module-name (record-accessor module-type 'name)) wait until mods are booted
1256 (define set-module-name! (record-modifier module-type 'name))
1257 (define module-kind (record-accessor module-type 'kind))
1258 (define set-module-kind! (record-modifier module-type 'kind))
1259 (define module-duplicates-handlers
1260 (record-accessor module-type 'duplicates-handlers))
1261 (define set-module-duplicates-handlers!
1262 (record-modifier module-type 'duplicates-handlers))
1263 (define module-observers (record-accessor module-type 'observers))
1264 (define set-module-observers! (record-modifier module-type 'observers))
1265 (define module-weak-observers (record-accessor module-type 'weak-observers))
1266 (define module? (record-predicate module-type))
1268 (define module-import-obarray (record-accessor module-type 'import-obarray))
1270 (define set-module-eval-closure!
1271 (let ((setter (record-modifier module-type 'eval-closure)))
1272 (lambda (module closure)
1273 (setter module closure)
1274 ;; Make it possible to lookup the module from the environment.
1275 ;; This implementation is correct since an eval closure can belong
1276 ;; to maximally one module.
1277 (set-procedure-property! closure 'module module))))
1281 ;;; {Observer protocol}
1284 (define (module-observe module proc)
1285 (set-module-observers! module (cons proc (module-observers module)))
1288 (define (module-observe-weak module observer-id . proc)
1289 ;; Register PROC as an observer of MODULE under name OBSERVER-ID (which can
1290 ;; be any Scheme object). PROC is invoked and passed MODULE any time
1291 ;; MODULE is modified. PROC gets unregistered when OBSERVER-ID gets GC'd
1292 ;; (thus, it is never unregistered if OBSERVER-ID is an immediate value,
1295 ;; The two-argument version is kept for backward compatibility: when called
1296 ;; with two arguments, the observer gets unregistered when closure PROC
1297 ;; gets GC'd (making it impossible to use an anonymous lambda for PROC).
1299 (let ((proc (if (null? proc) observer-id (car proc))))
1300 (hashq-set! (module-weak-observers module) observer-id proc)))
1302 (define (module-unobserve token)
1303 (let ((module (car token))
1306 (hash-remove! (module-weak-observers module) id)
1307 (set-module-observers! module (delq1! id (module-observers module)))))
1310 (define module-defer-observers #f)
1311 (define module-defer-observers-mutex (make-mutex 'recursive))
1312 (define module-defer-observers-table (make-hash-table))
1314 (define (module-modified m)
1315 (if module-defer-observers
1316 (hash-set! module-defer-observers-table m #t)
1317 (module-call-observers m)))
1319 ;;; This function can be used to delay calls to observers so that they
1320 ;;; can be called once only in the face of massive updating of modules.
1322 (define (call-with-deferred-observers thunk)
1325 (lock-mutex module-defer-observers-mutex)
1326 (set! module-defer-observers #t))
1329 (set! module-defer-observers #f)
1330 (hash-for-each (lambda (m dummy)
1331 (module-call-observers m))
1332 module-defer-observers-table)
1333 (hash-clear! module-defer-observers-table)
1334 (unlock-mutex module-defer-observers-mutex))))
1336 (define (module-call-observers m)
1337 (for-each (lambda (proc) (proc m)) (module-observers m))
1339 ;; We assume that weak observers don't (un)register themselves as they are
1340 ;; called since this would preclude proper iteration over the hash table
1342 (hash-for-each (lambda (id proc) (proc m)) (module-weak-observers m)))
1346 ;;; {Module Searching in General}
1348 ;;; We sometimes want to look for properties of a symbol
1349 ;;; just within the obarray of one module. If the property
1350 ;;; holds, then it is said to hold ``locally'' as in, ``The symbol
1351 ;;; DISPLAY is locally rebound in the module `safe-guile'.''
1354 ;;; Other times, we want to test for a symbol property in the obarray
1355 ;;; of M and, if it is not found there, try each of the modules in the
1356 ;;; uses list of M. This is the normal way of testing for some
1357 ;;; property, so we state these properties without qualification as
1358 ;;; in: ``The symbol 'fnord is interned in module M because it is
1359 ;;; interned locally in module M2 which is a member of the uses list
1363 ;; module-search fn m
1365 ;; return the first non-#f result of FN applied to M and then to
1366 ;; the modules in the uses of m, and so on recursively. If all applications
1367 ;; return #f, then so does this function.
1369 (define (module-search fn m v)
1372 (or (module-search fn (car pos) v)
1375 (loop (module-uses m))))
1378 ;;; {Is a symbol bound in a module?}
1380 ;;; Symbol S in Module M is bound if S is interned in M and if the binding
1381 ;;; of S in M has been set to some well-defined value.
1384 ;; module-locally-bound? module symbol
1386 ;; Is a symbol bound (interned and defined) locally in a given module?
1388 (define (module-locally-bound? m v)
1389 (let ((var (module-local-variable m v)))
1391 (variable-bound? var))))
1393 ;; module-bound? module symbol
1395 ;; Is a symbol bound (interned and defined) anywhere in a given module
1398 (define (module-bound? m v)
1399 (let ((var (module-variable m v)))
1401 (variable-bound? var))))
1403 ;;; {Is a symbol interned in a module?}
1405 ;;; Symbol S in Module M is interned if S occurs in
1406 ;;; of S in M has been set to some well-defined value.
1408 ;;; It is possible to intern a symbol in a module without providing
1409 ;;; an initial binding for the corresponding variable. This is done
1411 ;;; (module-add! module symbol (make-undefined-variable))
1413 ;;; In that case, the symbol is interned in the module, but not
1414 ;;; bound there. The unbound symbol shadows any binding for that
1415 ;;; symbol that might otherwise be inherited from a member of the uses list.
1418 (define (module-obarray-get-handle ob key)
1419 ((if (symbol? key) hashq-get-handle hash-get-handle) ob key))
1421 (define (module-obarray-ref ob key)
1422 ((if (symbol? key) hashq-ref hash-ref) ob key))
1424 (define (module-obarray-set! ob key val)
1425 ((if (symbol? key) hashq-set! hash-set!) ob key val))
1427 (define (module-obarray-remove! ob key)
1428 ((if (symbol? key) hashq-remove! hash-remove!) ob key))
1430 ;; module-symbol-locally-interned? module symbol
1432 ;; is a symbol interned (not neccessarily defined) locally in a given module
1433 ;; or its uses? Interned symbols shadow inherited bindings even if
1434 ;; they are not themselves bound to a defined value.
1436 (define (module-symbol-locally-interned? m v)
1437 (not (not (module-obarray-get-handle (module-obarray m) v))))
1439 ;; module-symbol-interned? module symbol
1441 ;; is a symbol interned (not neccessarily defined) anywhere in a given module
1442 ;; or its uses? Interned symbols shadow inherited bindings even if
1443 ;; they are not themselves bound to a defined value.
1445 (define (module-symbol-interned? m v)
1446 (module-search module-symbol-locally-interned? m v))
1449 ;;; {Mapping modules x symbols --> variables}
1452 ;; module-local-variable module symbol
1453 ;; return the local variable associated with a MODULE and SYMBOL.
1455 ;;; This function is very important. It is the only function that can
1456 ;;; return a variable from a module other than the mutators that store
1457 ;;; new variables in modules. Therefore, this function is the location
1458 ;;; of the "lazy binder" hack.
1460 ;;; If symbol is defined in MODULE, and if the definition binds symbol
1461 ;;; to a variable, return that variable object.
1463 ;;; If the symbols is not found at first, but the module has a lazy binder,
1464 ;;; then try the binder.
1466 ;;; If the symbol is not found at all, return #f.
1468 ;;; (This is now written in C, see `modules.c'.)
1471 ;;; {Mapping modules x symbols --> bindings}
1473 ;;; These are similar to the mapping to variables, except that the
1474 ;;; variable is dereferenced.
1477 ;; module-symbol-binding module symbol opt-value
1479 ;; return the binding of a variable specified by name within
1480 ;; a given module, signalling an error if the variable is unbound.
1481 ;; If the OPT-VALUE is passed, then instead of signalling an error,
1482 ;; return OPT-VALUE.
1484 (define (module-symbol-local-binding m v . opt-val)
1485 (let ((var (module-local-variable m v)))
1486 (if (and var (variable-bound? var))
1488 (if (not (null? opt-val))
1490 (error "Locally unbound variable." v)))))
1492 ;; module-symbol-binding module symbol opt-value
1494 ;; return the binding of a variable specified by name within
1495 ;; a given module, signalling an error if the variable is unbound.
1496 ;; If the OPT-VALUE is passed, then instead of signalling an error,
1497 ;; return OPT-VALUE.
1499 (define (module-symbol-binding m v . opt-val)
1500 (let ((var (module-variable m v)))
1501 (if (and var (variable-bound? var))
1503 (if (not (null? opt-val))
1505 (error "Unbound variable." v)))))
1510 ;;; {Adding Variables to Modules}
1513 ;; module-make-local-var! module symbol
1515 ;; ensure a variable for V in the local namespace of M.
1516 ;; If no variable was already there, then create a new and uninitialzied
1519 ;; This function is used in modules.c.
1521 (define (module-make-local-var! m v)
1522 (or (let ((b (module-obarray-ref (module-obarray m) v)))
1525 ;; Mark as modified since this function is called when
1526 ;; the standard eval closure defines a binding
1530 ;; Create a new local variable.
1531 (let ((local-var (make-undefined-variable)))
1532 (module-add! m v local-var)
1535 ;; module-ensure-local-variable! module symbol
1537 ;; Ensure that there is a local variable in MODULE for SYMBOL. If
1538 ;; there is no binding for SYMBOL, create a new uninitialized
1539 ;; variable. Return the local variable.
1541 (define (module-ensure-local-variable! module symbol)
1542 (or (module-local-variable module symbol)
1543 (let ((var (make-undefined-variable)))
1544 (module-add! module symbol var)
1547 ;; module-add! module symbol var
1549 ;; ensure a particular variable for V in the local namespace of M.
1551 (define (module-add! m v var)
1552 (if (not (variable? var))
1553 (error "Bad variable to module-add!" var))
1554 (module-obarray-set! (module-obarray m) v var)
1555 (module-modified m))
1559 ;; make sure that a symbol is undefined in the local namespace of M.
1561 (define (module-remove! m v)
1562 (module-obarray-remove! (module-obarray m) v)
1563 (module-modified m))
1565 (define (module-clear! m)
1566 (hash-clear! (module-obarray m))
1567 (module-modified m))
1569 ;; MODULE-FOR-EACH -- exported
1571 ;; Call PROC on each symbol in MODULE, with arguments of (SYMBOL VARIABLE).
1573 (define (module-for-each proc module)
1574 (hash-for-each proc (module-obarray module)))
1576 (define (module-map proc module)
1577 (hash-map->list proc (module-obarray module)))
1581 ;;; {Low Level Bootstrapping}
1586 ;; A root module uses the pre-modules-obarray as its obarray. This
1587 ;; special obarray accumulates all bindings that have been established
1588 ;; before the module system is fully booted.
1590 ;; (The obarray continues to be used by code that has been closed over
1591 ;; before the module system has been booted.)
1593 (define (make-root-module)
1594 (let ((m (make-module 0)))
1595 (set-module-obarray! m (%get-pre-modules-obarray))
1600 ;; The root interface is a module that uses the same obarray as the
1601 ;; root module. It does not allow new definitions, tho.
1603 (define (make-scm-module)
1604 (let ((m (make-module 0)))
1605 (set-module-obarray! m (%get-pre-modules-obarray))
1606 (set-module-eval-closure! m (standard-interface-eval-closure m))
1612 ;;; {Module-based Loading}
1615 (define (save-module-excursion thunk)
1616 (let ((inner-module (current-module))
1618 (dynamic-wind (lambda ()
1619 (set! outer-module (current-module))
1620 (set-current-module inner-module)
1621 (set! inner-module #f))
1624 (set! inner-module (current-module))
1625 (set-current-module outer-module)
1626 (set! outer-module #f)))))
1628 (define basic-load load)
1630 (define (load-module filename . reader)
1631 (save-module-excursion
1633 (let ((oldname (and (current-load-port)
1634 (port-filename (current-load-port)))))
1637 (> (string-length filename) 0)
1638 (not (char=? (string-ref filename 0) #\/))
1639 (not (string=? (dirname oldname) ".")))
1640 (string-append (dirname oldname) "/" filename)
1647 ;;; {MODULE-REF -- exported}
1650 ;; Returns the value of a variable called NAME in MODULE or any of its
1651 ;; used modules. If there is no such variable, then if the optional third
1652 ;; argument DEFAULT is present, it is returned; otherwise an error is signaled.
1654 (define (module-ref module name . rest)
1655 (let ((variable (module-variable module name)))
1656 (if (and variable (variable-bound? variable))
1657 (variable-ref variable)
1659 (error "No variable named" name 'in module)
1660 (car rest) ; default value
1663 ;; MODULE-SET! -- exported
1665 ;; Sets the variable called NAME in MODULE (or in a module that MODULE uses)
1666 ;; to VALUE; if there is no such variable, an error is signaled.
1668 (define (module-set! module name value)
1669 (let ((variable (module-variable module name)))
1671 (variable-set! variable value)
1672 (error "No variable named" name 'in module))))
1674 ;; MODULE-DEFINE! -- exported
1676 ;; Sets the variable called NAME in MODULE to VALUE; if there is no such
1677 ;; variable, it is added first.
1679 (define (module-define! module name value)
1680 (let ((variable (module-local-variable module name)))
1683 (variable-set! variable value)
1684 (module-modified module))
1685 (let ((variable (make-variable value)))
1686 (module-add! module name variable)))))
1688 ;; MODULE-DEFINED? -- exported
1690 ;; Return #t iff NAME is defined in MODULE (or in a module that MODULE
1693 (define (module-defined? module name)
1694 (let ((variable (module-variable module name)))
1695 (and variable (variable-bound? variable))))
1697 ;; MODULE-USE! module interface
1699 ;; Add INTERFACE to the list of interfaces used by MODULE.
1701 (define (module-use! module interface)
1702 (if (not (or (eq? module interface)
1703 (memq interface (module-uses module))))
1705 ;; Newly used modules must be appended rather than consed, so that
1706 ;; `module-variable' traverses the use list starting from the first
1708 (set-module-uses! module
1709 (append (filter (lambda (m)
1711 (equal? (module-name m)
1712 (module-name interface))))
1713 (module-uses module))
1716 (module-modified module))))
1718 ;; MODULE-USE-INTERFACES! module interfaces
1720 ;; Same as MODULE-USE! but add multiple interfaces and check for duplicates
1722 (define (module-use-interfaces! module interfaces)
1723 (set-module-uses! module
1724 (append (module-uses module) interfaces))
1725 (module-modified module))
1729 ;;; {Recursive Namespaces}
1731 ;;; A hierarchical namespace emerges if we consider some module to be
1732 ;;; root, and variables bound to modules as nested namespaces.
1734 ;;; The routines in this file manage variable names in hierarchical namespace.
1735 ;;; Each variable name is a list of elements, looked up in successively nested
1738 ;;; (nested-ref some-root-module '(foo bar baz))
1739 ;;; => <value of a variable named baz in the module bound to bar in
1740 ;;; the module bound to foo in some-root-module>
1745 ;;; ;; a-root is a module
1746 ;;; ;; name is a list of symbols
1748 ;;; nested-ref a-root name
1749 ;;; nested-set! a-root name val
1750 ;;; nested-define! a-root name val
1751 ;;; nested-remove! a-root name
1754 ;;; (current-module) is a natural choice for a-root so for convenience there are
1757 ;;; local-ref name == nested-ref (current-module) name
1758 ;;; local-set! name val == nested-set! (current-module) name val
1759 ;;; local-define! name val == nested-define! (current-module) name val
1760 ;;; local-remove! name == nested-remove! (current-module) name
1764 (define (nested-ref root names)
1765 (let loop ((cur root)
1769 ((not (module? cur)) #f)
1770 (else (loop (module-ref cur (car elts) #f) (cdr elts))))))
1772 (define (nested-set! root names val)
1773 (let loop ((cur root)
1775 (if (null? (cdr elts))
1776 (module-set! cur (car elts) val)
1777 (loop (module-ref cur (car elts)) (cdr elts)))))
1779 (define (nested-define! root names val)
1780 (let loop ((cur root)
1782 (if (null? (cdr elts))
1783 (module-define! cur (car elts) val)
1784 (loop (module-ref cur (car elts)) (cdr elts)))))
1786 (define (nested-remove! root names)
1787 (let loop ((cur root)
1789 (if (null? (cdr elts))
1790 (module-remove! cur (car elts))
1791 (loop (module-ref cur (car elts)) (cdr elts)))))
1793 (define (local-ref names) (nested-ref (current-module) names))
1794 (define (local-set! names val) (nested-set! (current-module) names val))
1795 (define (local-define names val) (nested-define! (current-module) names val))
1796 (define (local-remove names) (nested-remove! (current-module) names))
1801 ;;; {The (%app) module}
1803 ;;; The root of conventionally named objects not directly in the top level.
1806 ;;; (%app modules guile)
1808 ;;; The directory of all modules and the standard root module.
1811 ;; module-public-interface is defined in C.
1812 (define (set-module-public-interface! m i)
1813 (module-define! m '%module-public-interface i))
1814 (define (set-system-module! m s)
1815 (set-procedure-property! (module-eval-closure m) 'system-module s))
1816 (define the-root-module (make-root-module))
1817 (define the-scm-module (make-scm-module))
1818 (set-module-public-interface! the-root-module the-scm-module)
1819 (set-module-name! the-root-module '(guile))
1820 (set-module-name! the-scm-module '(guile))
1821 (set-module-kind! the-scm-module 'interface)
1822 (set-system-module! the-root-module #t)
1823 (set-system-module! the-scm-module #t)
1825 ;; NOTE: This binding is used in libguile/modules.c.
1827 (define (make-modules-in module name)
1831 (let* ((var (module-local-variable module (car name)))
1832 (val (and var (variable-bound? var) (variable-ref var))))
1835 (let ((m (make-module 31)))
1836 (set-module-kind! m 'directory)
1837 (set-module-name! m (append (or (module-name module) '())
1839 (module-define! module (car name) m)
1843 (define (beautify-user-module! module)
1844 (let ((interface (module-public-interface module)))
1845 (if (or (not interface)
1846 (eq? interface module))
1847 (let ((interface (make-module 31)))
1848 (set-module-name! interface (module-name module))
1849 (set-module-kind! interface 'interface)
1850 (set-module-public-interface! module interface))))
1851 (if (and (not (memq the-scm-module (module-uses module)))
1852 (not (eq? module the-root-module)))
1853 ;; Import the default set of bindings (from the SCM module) in MODULE.
1854 (module-use! module the-scm-module)))
1856 ;; NOTE: This binding is used in libguile/modules.c.
1858 (define resolve-module
1859 (let ((the-root-module the-root-module))
1860 (lambda (name . maybe-autoload)
1861 (if (equal? name '(guile))
1863 (let ((full-name (append '(%app modules) name)))
1864 (let ((already (nested-ref the-root-module full-name))
1865 (autoload (or (null? maybe-autoload) (car maybe-autoload))))
1867 ((and already (module? already)
1868 (or (not autoload) (module-public-interface already)))
1869 ;; A hit, a palpable hit.
1872 ;; Try to autoload the module, and recurse.
1873 (try-load-module name)
1874 (resolve-module name #f))
1876 ;; A module is not bound (but maybe something else is),
1877 ;; we're not autoloading -- here's the weird semantics,
1878 ;; we create an empty module.
1879 (make-modules-in the-root-module full-name)))))))))
1881 ;; Cheat. These bindings are needed by modules.c, but we don't want
1882 ;; to move their real definition here because that would be unnatural.
1884 (define try-module-autoload #f)
1885 (define process-define-module #f)
1886 (define process-use-modules #f)
1887 (define module-export! #f)
1888 (define default-duplicate-binding-procedures #f)
1890 (define %app (make-module 31))
1891 (define app %app) ;; for backwards compatability
1893 (local-define '(%app modules) (make-module 31))
1894 (local-define '(%app modules guile) the-root-module)
1896 ;; This boots the module system. All bindings needed by modules.c
1897 ;; must have been defined by now.
1899 (set-current-module the-root-module)
1900 ;; definition deferred for syncase's benefit
1901 (define module-name (record-accessor module-type 'name))
1903 ;; (define-special-value '(%app modules new-ws) (lambda () (make-scm-module)))
1905 (define (try-load-module name)
1906 (try-module-autoload name))
1908 (define (purify-module! module)
1909 "Removes bindings in MODULE which are inherited from the (guile) module."
1910 (let ((use-list (module-uses module)))
1911 (if (and (pair? use-list)
1912 (eq? (car (last-pair use-list)) the-scm-module))
1913 (set-module-uses! module (reverse (cdr (reverse use-list)))))))
1915 ;; Return a module that is an interface to the module designated by
1918 ;; `resolve-interface' takes four keyword arguments:
1920 ;; #:select SELECTION
1922 ;; SELECTION is a list of binding-specs to be imported; A binding-spec
1923 ;; is either a symbol or a pair of symbols (ORIG . SEEN), where ORIG
1924 ;; is the name in the used module and SEEN is the name in the using
1925 ;; module. Note that SEEN is also passed through RENAMER, below. The
1926 ;; default is to select all bindings. If you specify no selection but
1927 ;; a renamer, only the bindings that already exist in the used module
1928 ;; are made available in the interface. Bindings that are added later
1929 ;; are not picked up.
1933 ;; BINDINGS is a list of bindings which should not be imported.
1937 ;; PREFIX is a symbol that will be appended to each exported name.
1938 ;; The default is to not perform any renaming.
1940 ;; #:renamer RENAMER
1942 ;; RENAMER is a procedure that takes a symbol and returns its new
1943 ;; name. The default is not perform any renaming.
1945 ;; Signal "no code for module" error if module name is not resolvable
1946 ;; or its public interface is not available. Signal "no binding"
1947 ;; error if selected binding does not exist in the used module.
1949 (define (resolve-interface name . args)
1951 (define (get-keyword-arg args kw def)
1952 (cond ((memq kw args)
1954 (if (null? (cdr kw-arg))
1955 (error "keyword without value: " kw))
1960 (let* ((select (get-keyword-arg args #:select #f))
1961 (hide (get-keyword-arg args #:hide '()))
1962 (renamer (or (get-keyword-arg args #:renamer #f)
1963 (let ((prefix (get-keyword-arg args #:prefix #f)))
1964 (and prefix (symbol-prefix-proc prefix)))
1966 (module (resolve-module name))
1967 (public-i (and module (module-public-interface module))))
1968 (and (or (not module) (not public-i))
1969 (error "no code for module" name))
1970 (if (and (not select) (null? hide) (eq? renamer identity))
1972 (let ((selection (or select (module-map (lambda (sym var) sym)
1974 (custom-i (make-module 31)))
1975 (set-module-kind! custom-i 'custom-interface)
1976 (set-module-name! custom-i name)
1977 ;; XXX - should use a lazy binder so that changes to the
1978 ;; used module are picked up automatically.
1979 (for-each (lambda (bspec)
1980 (let* ((direct? (symbol? bspec))
1981 (orig (if direct? bspec (car bspec)))
1982 (seen (if direct? bspec (cdr bspec)))
1983 (var (or (module-local-variable public-i orig)
1984 (module-local-variable module orig)
1986 ;; fixme: format manually for now
1988 #f "no binding `~A' in module ~A"
1990 (if (memq orig hide)
1991 (set! hide (delq! orig hide))
1992 (module-add! custom-i
1996 ;; Check that we are not hiding bindings which don't exist
1997 (for-each (lambda (binding)
1998 (if (not (module-local-variable public-i binding))
2001 #f "no binding `~A' to hide in module ~A"
2006 (define (symbol-prefix-proc prefix)
2008 (symbol-append prefix symbol)))
2010 ;; This function is called from "modules.c". If you change it, be
2011 ;; sure to update "modules.c" as well.
2013 (define (process-define-module args)
2014 (let* ((module-id (car args))
2015 (module (resolve-module module-id #f))
2017 (unrecognized (lambda (arg)
2018 (error "unrecognized define-module argument" arg))))
2019 (beautify-user-module! module)
2020 (let loop ((kws kws)
2021 (reversed-interfaces '())
2028 (call-with-deferred-observers
2030 (module-use-interfaces! module (reverse reversed-interfaces))
2031 (module-export! module exports)
2032 (module-replace! module replacements)
2033 (module-re-export! module re-exports)
2034 (if (not (null? autoloads))
2035 (apply module-autoload! module autoloads))))
2037 ((#:use-module #:use-syntax)
2038 (or (pair? (cdr kws))
2041 ((equal? (caadr kws) '(ice-9 syncase))
2042 (issue-deprecation-warning
2043 "(ice-9 syncase) is deprecated. Support for syntax-case is now in Guile core.")
2051 (let* ((interface-args (cadr kws))
2052 (interface (apply resolve-interface interface-args)))
2053 (and (eq? (car kws) #:use-syntax)
2054 (or (symbol? (caar interface-args))
2055 (error "invalid module name for use-syntax"
2056 (car interface-args)))
2057 (set-module-transformer!
2059 (module-ref interface
2060 (car (last-pair (car interface-args)))
2063 (cons interface reversed-interfaces)
2069 (or (and (pair? (cdr kws)) (pair? (cddr kws)))
2076 (let ((name (cadr kws))
2077 (bindings (caddr kws)))
2078 (cons* name bindings autoloads))))
2080 (set-system-module! module #t)
2081 (loop (cdr kws) reversed-interfaces exports re-exports
2082 replacements autoloads))
2084 (purify-module! module)
2085 (loop (cdr kws) reversed-interfaces exports re-exports
2086 replacements autoloads))
2088 (if (not (pair? (cdr kws)))
2090 (set-module-duplicates-handlers!
2092 (lookup-duplicates-handlers (cadr kws)))
2093 (loop (cddr kws) reversed-interfaces exports re-exports
2094 replacements autoloads))
2095 ((#:export #:export-syntax)
2096 (or (pair? (cdr kws))
2100 (append (cadr kws) exports)
2104 ((#:re-export #:re-export-syntax)
2105 (or (pair? (cdr kws))
2110 (append (cadr kws) re-exports)
2113 ((#:replace #:replace-syntax)
2114 (or (pair? (cdr kws))
2120 (append (cadr kws) replacements)
2123 (unrecognized kws)))))
2124 (run-hook module-defined-hook module)
2127 ;; `module-defined-hook' is a hook that is run whenever a new module
2128 ;; is defined. Its members are called with one argument, the new
2130 (define module-defined-hook (make-hook 1))
2137 (define (make-autoload-interface module name bindings)
2138 (let ((b (lambda (a sym definep)
2139 (and (memq sym bindings)
2140 (let ((i (module-public-interface (resolve-module name))))
2142 (error "missing interface for module" name))
2143 (let ((autoload (memq a (module-uses module))))
2144 ;; Replace autoload-interface with actual interface if
2145 ;; that has not happened yet.
2146 (if (pair? autoload)
2147 (set-car! autoload i)))
2148 (module-local-variable i sym))))))
2149 (module-constructor (make-hash-table 0) '() b #f #f name 'autoload #f
2150 (make-hash-table 0) '() (make-weak-value-hash-table 31))))
2152 (define (module-autoload! module . args)
2153 "Have @var{module} automatically load the module named @var{name} when one
2154 of the symbols listed in @var{bindings} is looked up. @var{args} should be a
2155 list of module-name/binding-list pairs, e.g., as in @code{(module-autoload!
2156 module '(ice-9 q) '(make-q q-length))}."
2157 (let loop ((args args))
2161 (error "invalid name+binding autoload list" args))
2163 (let ((name (car args))
2164 (bindings (cadr args)))
2165 (module-use! module (make-autoload-interface module
2167 (loop (cddr args)))))))
2172 ;;; {Autoloading modules}
2175 (define autoloads-in-progress '())
2177 ;; This function is called from "modules.c". If you change it, be
2178 ;; sure to update "modules.c" as well.
2180 (define (try-module-autoload module-name)
2181 (let* ((reverse-name (reverse module-name))
2182 (name (symbol->string (car reverse-name)))
2183 (dir-hint-module-name (reverse (cdr reverse-name)))
2184 (dir-hint (apply string-append
2186 (string-append (symbol->string elt) "/"))
2187 dir-hint-module-name))))
2188 (resolve-module dir-hint-module-name #f)
2189 (and (not (autoload-done-or-in-progress? dir-hint name))
2191 (define (load-file proc file)
2192 (save-module-excursion (lambda () (proc file)))
2195 (lambda () (autoload-in-progress! dir-hint name))
2197 (let ((file (in-vicinity dir-hint name)))
2198 (let ((compiled (and load-compiled
2200 (string-append file ".go"))))
2201 (source (%search-load-path file)))
2204 (< (stat:mtime (stat compiled))
2205 (stat:mtime (stat source)))))
2207 (warn "source file" source "newer than" compiled))
2208 (with-fluid* current-reader #f
2209 (lambda () (load-file primitive-load source))))
2211 (load-file load-compiled compiled))))))
2212 (lambda () (set-autoloaded! dir-hint name didit)))
2217 ;;; {Dynamic linking of modules}
2220 (define autoloads-done '((guile . guile)))
2222 (define (autoload-done-or-in-progress? p m)
2223 (let ((n (cons p m)))
2224 (->bool (or (member n autoloads-done)
2225 (member n autoloads-in-progress)))))
2227 (define (autoload-done! p m)
2228 (let ((n (cons p m)))
2229 (set! autoloads-in-progress
2230 (delete! n autoloads-in-progress))
2231 (or (member n autoloads-done)
2232 (set! autoloads-done (cons n autoloads-done)))))
2234 (define (autoload-in-progress! p m)
2235 (let ((n (cons p m)))
2236 (set! autoloads-done
2237 (delete! n autoloads-done))
2238 (set! autoloads-in-progress (cons n autoloads-in-progress))))
2240 (define (set-autoloaded! p m done?)
2242 (autoload-done! p m)
2243 (let ((n (cons p m)))
2244 (set! autoloads-done (delete! n autoloads-done))
2245 (set! autoloads-in-progress (delete! n autoloads-in-progress)))))
2249 ;;; {Run-time options}
2252 (defmacro define-option-interface (option-group)
2253 (let* ((option-name car)
2255 (option-documentation caddr)
2257 ;; Below follow the macros defining the run-time option interfaces.
2259 (make-options (lambda (interface)
2261 (cond ((null? args) (,interface))
2263 (,interface (car args)) (,interface))
2266 (display (option-name option))
2267 (if (< (string-length
2268 (symbol->string (option-name option)))
2272 (display (option-value option))
2274 (display (option-documentation option))
2276 (,interface #t)))))))
2278 (make-enable (lambda (interface)
2280 (,interface (append flags (,interface)))
2283 (make-disable (lambda (interface)
2285 (let ((options (,interface)))
2286 (for-each (lambda (flag)
2287 (set! options (delq! flag options)))
2289 (,interface options)
2291 (let* ((interface (car option-group))
2292 (options/enable/disable (cadr option-group)))
2294 (define ,(car options/enable/disable)
2295 ,(make-options interface))
2296 (define ,(cadr options/enable/disable)
2297 ,(make-enable interface))
2298 (define ,(caddr options/enable/disable)
2299 ,(make-disable interface))
2300 (defmacro ,(caaddr option-group) (opt val)
2301 `(,',(car options/enable/disable)
2302 (append (,',(car options/enable/disable))
2303 (list ',opt ,val))))))))
2305 (define-option-interface
2306 (eval-options-interface
2307 (eval-options eval-enable eval-disable)
2310 (define-option-interface
2311 (debug-options-interface
2312 (debug-options debug-enable debug-disable)
2315 (define-option-interface
2316 (evaluator-traps-interface
2317 (traps trap-enable trap-disable)
2320 (define-option-interface
2321 (read-options-interface
2322 (read-options read-enable read-disable)
2325 (define-option-interface
2326 (print-options-interface
2327 (print-options print-enable print-disable)
2335 (define (repl read evaler print)
2336 (let loop ((source (read (current-input-port))))
2337 (print (evaler source))
2338 (loop (read (current-input-port)))))
2340 ;; A provisional repl that acts like the SCM repl:
2342 (define scm-repl-silent #f)
2343 (define (assert-repl-silence v) (set! scm-repl-silent v))
2345 (define *unspecified* (if #f #f))
2346 (define (unspecified? v) (eq? v *unspecified*))
2348 (define scm-repl-print-unspecified #f)
2349 (define (assert-repl-print-unspecified v) (set! scm-repl-print-unspecified v))
2351 (define scm-repl-verbose #f)
2352 (define (assert-repl-verbosity v) (set! scm-repl-verbose v))
2354 (define scm-repl-prompt "guile> ")
2356 (define (set-repl-prompt! v) (set! scm-repl-prompt v))
2358 (define (default-pre-unwind-handler key . args)
2359 (save-stack pre-unwind-handler-dispatch)
2360 (apply throw key args))
2362 (define (pre-unwind-handler-dispatch key . args)
2363 (apply default-pre-unwind-handler key args))
2365 (define abort-hook (make-hook))
2367 ;; these definitions are used if running a script.
2368 ;; otherwise redefined in error-catching-loop.
2369 (define (set-batch-mode?! arg) #t)
2370 (define (batch-mode?) #t)
2372 (define (error-catching-loop thunk)
2375 (define (loop first)
2380 (call-with-unblocked-asyncs
2386 ;; This line is needed because mark
2387 ;; doesn't do closures quite right.
2388 ;; Unreferenced locals should be
2391 (let loop ((v (thunk)))
2395 (lambda (key . args)
2402 (apply throw 'switch-repl args))
2405 ;; This is one of the closures that require
2406 ;; (set! first #f) above
2409 (run-hook abort-hook)
2410 (force-output (current-output-port))
2411 (display "ABORT: " (current-error-port))
2412 (write args (current-error-port))
2413 (newline (current-error-port))
2417 (not has-shown-debugger-hint?)
2418 (not (memq 'backtrace
2419 (debug-options-interface)))
2420 (stack? (fluid-ref the-last-stack)))
2422 (newline (current-error-port))
2424 "Type \"(backtrace)\" to get more information or \"(debug)\" to enter the debugger.\n"
2425 (current-error-port))
2426 (set! has-shown-debugger-hint? #t)))
2427 (force-output (current-error-port)))
2429 (primitive-exit 1)))
2430 (set! stack-saved? #f)))
2433 ;; This is the other cons-leak closure...
2435 (cond ((= (length args) 4)
2436 (apply handle-system-error key args))
2438 (apply bad-throw key args)))))))
2440 ;; Note that having just `pre-unwind-handler-dispatch'
2441 ;; here is connected with the mechanism that
2442 ;; produces a nice backtrace upon error. If, for
2443 ;; example, this is replaced with (lambda args
2444 ;; (apply pre-unwind-handler-dispatch args)), the stack
2445 ;; cutting (in save-stack) goes wrong and ends up
2446 ;; saving no stack at all, so there is no
2448 pre-unwind-handler-dispatch)))
2450 (if next (loop next) status)))
2451 (set! set-batch-mode?! (lambda (arg)
2453 (set! interactive #f)
2456 (error "sorry, not implemented")))))
2457 (set! batch-mode? (lambda () (not interactive)))
2458 (call-with-blocked-asyncs
2459 (lambda () (loop (lambda () #t))))))
2461 ;;(define the-last-stack (make-fluid)) Defined by scm_init_backtrace ()
2462 (define before-signal-stack (make-fluid))
2463 (define stack-saved? #f)
2465 (define (save-stack . narrowing)
2467 (cond ((not (memq 'debug (debug-options-interface)))
2468 (fluid-set! the-last-stack #f)
2469 (set! stack-saved? #t))
2475 (apply make-stack #t save-stack primitive-eval #t 0 narrowing))
2477 (apply make-stack #t save-stack 0 #t 0 narrowing))
2479 (apply make-stack #t save-stack tk-stack-mark #t 0 narrowing))
2481 (apply make-stack #t save-stack 0 1 narrowing))
2483 (let ((id (stack-id #t)))
2484 (and (procedure? id)
2485 (apply make-stack #t save-stack id #t 0 narrowing))))))
2486 (set! stack-saved? #t)))))
2488 (define before-error-hook (make-hook))
2489 (define after-error-hook (make-hook))
2490 (define before-backtrace-hook (make-hook))
2491 (define after-backtrace-hook (make-hook))
2493 (define has-shown-debugger-hint? #f)
2495 (define (handle-system-error key . args)
2496 (let ((cep (current-error-port)))
2497 (cond ((not (stack? (fluid-ref the-last-stack))))
2498 ((memq 'backtrace (debug-options-interface))
2499 (let ((highlights (if (or (eq? key 'wrong-type-arg)
2500 (eq? key 'out-of-range))
2503 (run-hook before-backtrace-hook)
2505 (display "Backtrace:\n")
2506 (display-backtrace (fluid-ref the-last-stack) cep
2509 (run-hook after-backtrace-hook))))
2510 (run-hook before-error-hook)
2511 (apply display-error (fluid-ref the-last-stack) cep args)
2512 (run-hook after-error-hook)
2514 (throw 'abort key)))
2516 (define (quit . args)
2517 (apply throw 'quit args))
2521 ;;(define has-shown-backtrace-hint? #f) Defined by scm_init_backtrace ()
2523 ;; Replaced by C code:
2524 ;;(define (backtrace)
2525 ;; (if (fluid-ref the-last-stack)
2528 ;; (display-backtrace (fluid-ref the-last-stack) (current-output-port))
2530 ;; (if (and (not has-shown-backtrace-hint?)
2531 ;; (not (memq 'backtrace (debug-options-interface))))
2534 ;;"Type \"(debug-enable 'backtrace)\" if you would like a backtrace
2535 ;;automatically if an error occurs in the future.\n")
2536 ;; (set! has-shown-backtrace-hint? #t))))
2537 ;; (display "No backtrace available.\n")))
2539 (define (error-catching-repl r e p)
2540 (error-catching-loop
2542 (call-with-values (lambda () (e (r)))
2543 (lambda the-values (for-each p the-values))))))
2545 (define (gc-run-time)
2546 (cdr (assq 'gc-time-taken (gc-stats))))
2548 (define before-read-hook (make-hook))
2549 (define after-read-hook (make-hook))
2550 (define before-eval-hook (make-hook 1))
2551 (define after-eval-hook (make-hook 1))
2552 (define before-print-hook (make-hook 1))
2553 (define after-print-hook (make-hook 1))
2555 ;;; The default repl-reader function. We may override this if we've
2556 ;;; the readline library.
2559 (display (if (string? prompt) prompt (prompt)))
2561 (run-hook before-read-hook)
2562 ((or (fluid-ref current-reader) read) (current-input-port))))
2564 (define (scm-style-repl)
2569 (repl-report-start-timing (lambda ()
2570 (set! start-gc-rt (gc-run-time))
2571 (set! start-rt (get-internal-run-time))))
2572 (repl-report (lambda ()
2574 (display (inexact->exact
2575 (* 1000 (/ (- (get-internal-run-time) start-rt)
2576 internal-time-units-per-second))))
2578 (display (inexact->exact
2579 (* 1000 (/ (- (gc-run-time) start-gc-rt)
2580 internal-time-units-per-second))))
2581 (display " msec in gc)\n")))
2583 (consume-trailing-whitespace
2585 (let ((ch (peek-char)))
2588 ((or (char=? ch #\space) (char=? ch #\tab))
2590 (consume-trailing-whitespace))
2591 ((char=? ch #\newline)
2595 (let ((prompt (cond ((string? scm-repl-prompt)
2597 ((thunk? scm-repl-prompt)
2599 (scm-repl-prompt "> ")
2601 (repl-reader prompt))))
2603 ;; As described in R4RS, the READ procedure updates the
2604 ;; port to point to the first character past the end of
2605 ;; the external representation of the object. This
2606 ;; means that it doesn't consume the newline typically
2607 ;; found after an expression. This means that, when
2608 ;; debugging Guile with GDB, GDB gets the newline, which
2609 ;; it often interprets as a "continue" command, making
2610 ;; breakpoints kind of useless. So, consume any
2611 ;; trailing newline here, as well as any whitespace
2613 ;; But not if EOF, for control-D.
2614 (if (not (eof-object? val))
2615 (consume-trailing-whitespace))
2616 (run-hook after-read-hook)
2617 (if (eof-object? val)
2619 (repl-report-start-timing)
2620 (if scm-repl-verbose
2623 (display ";;; EOF -- quitting")
2628 (-eval (lambda (sourc)
2629 (repl-report-start-timing)
2630 (run-hook before-eval-hook sourc)
2631 (let ((val (start-stack 'repl-stack
2632 ;; If you change this procedure
2633 ;; (primitive-eval), please also
2634 ;; modify the repl-stack case in
2635 ;; save-stack so that stack cutting
2636 ;; continues to work.
2637 (primitive-eval sourc))))
2638 (run-hook after-eval-hook sourc)
2642 (-print (let ((maybe-print (lambda (result)
2643 (if (or scm-repl-print-unspecified
2644 (not (unspecified? result)))
2649 (if (not scm-repl-silent)
2651 (run-hook before-print-hook result)
2652 (maybe-print result)
2653 (run-hook after-print-hook result)
2654 (if scm-repl-verbose
2658 (-quit (lambda (args)
2659 (if scm-repl-verbose
2661 (display ";;; QUIT executed, repl exitting")
2667 (if scm-repl-verbose
2669 (display ";;; ABORT executed.")
2672 (repl -read -eval -print))))
2674 (let ((status (error-catching-repl -read
2682 ;;; {IOTA functions: generating lists of numbers}
2686 (let loop ((count (1- n)) (result '()))
2687 (if (< count 0) result
2688 (loop (1- count) (cons count result)))))
2694 ;;; Similar to `begin' but returns a list of the results of all constituent
2695 ;;; forms instead of the result of the last form.
2696 ;;; (The definition relies on the current left-to-right
2697 ;;; order of evaluation of operands in applications.)
2700 (defmacro collect forms
2708 ;; with-fluids is a convenience wrapper for the builtin procedure
2709 ;; `with-fluids*'. The syntax is just like `let':
2711 ;; (with-fluids ((fluid val)
2715 (defmacro with-fluids (bindings . body)
2716 (let ((fluids (map car bindings))
2717 (values (map cadr bindings)))
2718 (if (and (= (length fluids) 1) (= (length values) 1))
2719 `(with-fluid* ,(car fluids) ,(car values) (lambda () ,@body))
2720 `(with-fluids* (list ,@fluids) (list ,@values)
2721 (lambda () ,@body)))))
2725 ;;; with `continue' and `break'.
2728 ;; The inner `do' loop avoids re-establishing a catch every iteration,
2729 ;; that's only necessary if continue is actually used. A new key is
2730 ;; generated every time, so break and continue apply to their originating
2731 ;; `while' even when recursing.
2733 ;; FIXME: This macro is unintentionally unhygienic with respect to let,
2734 ;; make-symbol, do, throw, catch, lambda, and not.
2736 (define-macro (while cond . body)
2737 (let ((keyvar (make-symbol "while-keyvar")))
2738 `(let ((,keyvar (make-symbol "while-key")))
2742 (let ((break (lambda () (throw ,keyvar #t)))
2743 (continue (lambda () (throw ,keyvar #f))))
2754 ;;; {Module System Macros}
2757 ;; Return a list of expressions that evaluate to the appropriate
2758 ;; arguments for resolve-interface according to SPEC.
2762 (if (memq 'prefix (read-options))
2763 (error "boot-9 must be compiled with #:kw, not :kw")))
2765 (define (compile-interface-spec spec)
2766 (define (make-keyarg sym key quote?)
2767 (cond ((or (memq sym spec)
2771 (list key (list 'quote (cadr rest)))
2772 (list key (cadr rest)))))
2775 (define (map-apply func list)
2776 (map (lambda (args) (apply func args)) list))
2779 '((:select #:select #t)
2781 (:prefix #:prefix #t)
2782 (:renamer #:renamer #f)))
2783 (if (not (pair? (car spec)))
2786 ,@(apply append (map-apply make-keyarg keys)))))
2788 (define (keyword-like-symbol->keyword sym)
2789 (symbol->keyword (string->symbol (substring (symbol->string sym) 1))))
2791 (define (compile-define-module-args args)
2792 ;; Just quote everything except #:use-module and #:use-syntax. We
2793 ;; need to know about all arguments regardless since we want to turn
2794 ;; symbols that look like keywords into real keywords, and the
2795 ;; keyword args in a define-module form are not regular
2796 ;; (i.e. no-backtrace doesn't take a value).
2797 (let loop ((compiled-args `((quote ,(car args))))
2800 (reverse! compiled-args))
2801 ;; symbol in keyword position
2802 ((symbol? (car args))
2804 (cons (keyword-like-symbol->keyword (car args)) (cdr args))))
2805 ((memq (car args) '(#:no-backtrace #:pure))
2806 (loop (cons (car args) compiled-args)
2809 (error "keyword without value:" (car args)))
2810 ((memq (car args) '(#:use-module #:use-syntax))
2811 (loop (cons* `(list ,@(compile-interface-spec (cadr args)))
2815 ((eq? (car args) #:autoload)
2816 (loop (cons* `(quote ,(caddr args))
2817 `(quote ,(cadr args))
2822 (loop (cons* `(quote ,(cadr args))
2827 (defmacro define-module args
2830 (let ((m (process-define-module
2831 (list ,@(compile-define-module-args args)))))
2832 (set-current-module m)
2835 ;; The guts of the use-modules macro. Add the interfaces of the named
2836 ;; modules to the use-list of the current module, in order.
2838 ;; This function is called by "modules.c". If you change it, be sure
2839 ;; to change scm_c_use_module as well.
2841 (define (process-use-modules module-interface-args)
2842 (let ((interfaces (map (lambda (mif-args)
2843 (or (apply resolve-interface mif-args)
2844 (error "no such module" mif-args)))
2845 module-interface-args)))
2846 (call-with-deferred-observers
2848 (module-use-interfaces! (current-module) interfaces)))))
2850 (defmacro use-modules modules
2853 (process-use-modules
2854 (list ,@(map (lambda (m)
2855 `(list ,@(compile-interface-spec m)))
2859 (defmacro use-syntax (spec)
2862 (issue-deprecation-warning
2863 "`use-syntax' is deprecated. Please contact guile-devel for more info.")
2864 (process-use-modules (list (list ,@(compile-interface-spec spec))))
2867 ;; Dirk:FIXME:: This incorrect (according to R5RS) syntax needs to be changed
2868 ;; as soon as guile supports hygienic macros.
2869 (define-syntax define-private
2874 (define-syntax define-public
2876 ((_ (name . args) . body)
2877 (define-public name (lambda args . body)))
2883 (define-syntax defmacro-public
2885 ((_ name args . body)
2887 (defmacro name args . body)
2888 (export-syntax name)))))
2890 ;; Export a local variable
2892 ;; This function is called from "modules.c". If you change it, be
2893 ;; sure to update "modules.c" as well.
2895 (define (module-export! m names)
2896 (let ((public-i (module-public-interface m)))
2897 (for-each (lambda (name)
2898 (let ((var (module-ensure-local-variable! m name)))
2899 (module-add! public-i name var)))
2902 (define (module-replace! m names)
2903 (let ((public-i (module-public-interface m)))
2904 (for-each (lambda (name)
2905 (let ((var (module-ensure-local-variable! m name)))
2906 (set-object-property! var 'replace #t)
2907 (module-add! public-i name var)))
2910 ;; Re-export a imported variable
2912 (define (module-re-export! m names)
2913 (let ((public-i (module-public-interface m)))
2914 (for-each (lambda (name)
2915 (let ((var (module-variable m name)))
2917 (error "Undefined variable:" name))
2918 ((eq? var (module-local-variable m name))
2919 (error "re-exporting local variable:" name))
2921 (module-add! public-i name var)))))
2924 (defmacro export names
2925 `(call-with-deferred-observers
2927 (module-export! (current-module) ',names))))
2929 (defmacro re-export names
2930 `(call-with-deferred-observers
2932 (module-re-export! (current-module) ',names))))
2934 (defmacro export-syntax names
2937 (defmacro re-export-syntax names
2938 `(re-export ,@names))
2940 (define load load-module)
2944 ;;; {Compiler interface}
2946 ;;; The full compiler interface can be found in (system). Here we put a
2947 ;;; few useful procedures into the global namespace.
2949 (module-autoload! the-scm-module
2950 '(system base compile)
2952 compile-time-environment))
2960 (define make-mutable-parameter
2961 (let ((make (lambda (fluid converter)
2965 (fluid-set! fluid (converter (car args))))))))
2966 (lambda (init . converter)
2967 (let ((fluid (make-fluid))
2968 (converter (if (null? converter)
2971 (fluid-set! fluid (converter init))
2972 (make fluid converter)))))
2976 ;;; {Handling of duplicate imported bindings}
2979 ;; Duplicate handlers take the following arguments:
2981 ;; module importing module
2982 ;; name conflicting name
2983 ;; int1 old interface where name occurs
2984 ;; val1 value of binding in old interface
2985 ;; int2 new interface where name occurs
2986 ;; val2 value of binding in new interface
2987 ;; var previous resolution or #f
2988 ;; val value of previous resolution
2990 ;; A duplicate handler can take three alternative actions:
2992 ;; 1. return #f => leave responsibility to next handler
2993 ;; 2. exit with an error
2994 ;; 3. return a variable resolving the conflict
2997 (define duplicate-handlers
2998 (let ((m (make-module 7)))
3000 (define (check module name int1 val1 int2 val2 var val)
3001 (scm-error 'misc-error
3003 "~A: `~A' imported from both ~A and ~A"
3004 (list (module-name module)
3010 (define (warn module name int1 val1 int2 val2 var val)
3011 (format (current-error-port)
3012 "WARNING: ~A: `~A' imported from both ~A and ~A\n"
3013 (module-name module)
3019 (define (replace module name int1 val1 int2 val2 var val)
3020 (let ((old (or (and var (object-property var 'replace) var)
3021 (module-variable int1 name)))
3022 (new (module-variable int2 name)))
3023 (if (object-property old 'replace)
3024 (and (or (eq? old new)
3025 (not (object-property new 'replace)))
3027 (and (object-property new 'replace)
3030 (define (warn-override-core module name int1 val1 int2 val2 var val)
3031 (and (eq? int1 the-scm-module)
3033 (format (current-error-port)
3034 "WARNING: ~A: imported module ~A overrides core binding `~A'\n"
3035 (module-name module)
3038 (module-local-variable int2 name))))
3040 (define (first module name int1 val1 int2 val2 var val)
3041 (or var (module-local-variable int1 name)))
3043 (define (last module name int1 val1 int2 val2 var val)
3044 (module-local-variable int2 name))
3046 (define (noop module name int1 val1 int2 val2 var val)
3049 (set-module-name! m 'duplicate-handlers)
3050 (set-module-kind! m 'interface)
3051 (module-define! m 'check check)
3052 (module-define! m 'warn warn)
3053 (module-define! m 'replace replace)
3054 (module-define! m 'warn-override-core warn-override-core)
3055 (module-define! m 'first first)
3056 (module-define! m 'last last)
3057 (module-define! m 'merge-generics noop)
3058 (module-define! m 'merge-accessors noop)
3061 (define (lookup-duplicates-handlers handler-names)
3063 (map (lambda (handler-name)
3064 (or (module-symbol-local-binding
3065 duplicate-handlers handler-name #f)
3066 (error "invalid duplicate handler name:"
3068 (if (list? handler-names)
3070 (list handler-names)))))
3072 (define default-duplicate-binding-procedures
3073 (make-mutable-parameter #f))
3075 (define default-duplicate-binding-handler
3076 (make-mutable-parameter '(replace warn-override-core warn last)
3077 (lambda (handler-names)
3078 (default-duplicate-binding-procedures
3079 (lookup-duplicates-handlers handler-names))
3084 ;;; {`cond-expand' for SRFI-0 support.}
3086 ;;; This syntactic form expands into different commands or
3087 ;;; definitions, depending on the features provided by the Scheme
3093 ;;; --> (cond-expand <cond-expand-clause>+)
3094 ;;; | (cond-expand <cond-expand-clause>* (else <command-or-definition>))
3095 ;;; <cond-expand-clause>
3096 ;;; --> (<feature-requirement> <command-or-definition>*)
3097 ;;; <feature-requirement>
3098 ;;; --> <feature-identifier>
3099 ;;; | (and <feature-requirement>*)
3100 ;;; | (or <feature-requirement>*)
3101 ;;; | (not <feature-requirement>)
3102 ;;; <feature-identifier>
3103 ;;; --> <a symbol which is the name or alias of a SRFI>
3105 ;;; Additionally, this implementation provides the
3106 ;;; <feature-identifier>s `guile' and `r5rs', so that programs can
3107 ;;; determine the implementation type and the supported standard.
3109 ;;; Currently, the following feature identifiers are supported:
3111 ;;; guile r5rs srfi-0 srfi-4 srfi-6 srfi-13 srfi-14 srfi-55 srfi-61
3113 ;;; Remember to update the features list when adding more SRFIs.
3116 (define %cond-expand-features
3117 ;; Adjust the above comment when changing this.
3120 srfi-0 ;; cond-expand itself
3121 srfi-4 ;; homogenous numeric vectors
3122 srfi-6 ;; open-input-string etc, in the guile core
3123 srfi-13 ;; string library
3124 srfi-14 ;; character sets
3125 srfi-55 ;; require-extension
3126 srfi-61 ;; general cond clause
3129 ;; This table maps module public interfaces to the list of features.
3131 (define %cond-expand-table (make-hash-table 31))
3133 ;; Add one or more features to the `cond-expand' feature list of the
3136 (define (cond-expand-provide module features)
3137 (let ((mod (module-public-interface module)))
3139 (hashq-set! %cond-expand-table mod
3140 (append (hashq-ref %cond-expand-table mod '())
3144 (procedure->memoizing-macro
3146 (let ((clauses (cdr exp))
3147 (syntax-error (lambda (cl)
3148 (error "invalid clause in `cond-expand'" cl))))
3154 (or (memq clause %cond-expand-features)
3155 (let lp ((uses (module-uses (env-module env))))
3158 (hashq-ref %cond-expand-table
3164 ((eq? 'and (car clause))
3165 (let lp ((l (cdr clause)))
3169 (and (test-clause (car l)) (lp (cdr l))))
3171 (syntax-error clause)))))
3172 ((eq? 'or (car clause))
3173 (let lp ((l (cdr clause)))
3177 (or (test-clause (car l)) (lp (cdr l))))
3179 (syntax-error clause)))))
3180 ((eq? 'not (car clause))
3181 (cond ((not (pair? (cdr clause)))
3182 (syntax-error clause))
3183 ((pair? (cddr clause))
3184 ((syntax-error clause))))
3185 (not (test-clause (cadr clause))))
3187 (syntax-error clause))))
3189 (syntax-error clause))))))
3190 (let lp ((c clauses))
3193 (error "Unfulfilled `cond-expand'"))
3196 ((not (pair? (car c)))
3197 (syntax-error (car c)))
3198 ((test-clause (caar c))
3199 `(begin ,@(cdar c)))
3200 ((eq? (caar c) 'else)
3203 `(begin ,@(cdar c)))
3205 (lp (cdr c))))))))))
3207 ;; This procedure gets called from the startup code with a list of
3208 ;; numbers, which are the numbers of the SRFIs to be loaded on startup.
3210 (define (use-srfis srfis)
3211 (process-use-modules
3213 (list (list 'srfi (string->symbol
3214 (string-append "srfi-" (number->string num))))))
3219 ;;; srfi-55: require-extension
3222 (define-macro (require-extension extension-spec)
3223 ;; This macro only handles the srfi extension, which, at present, is
3224 ;; the only one defined by the standard.
3225 (if (not (pair? extension-spec))
3226 (scm-error 'wrong-type-arg "require-extension"
3227 "Not an extension: ~S" (list extension-spec) #f))
3228 (let ((extension (car extension-spec))
3229 (extension-args (cdr extension-spec)))
3232 (let ((use-list '()))
3235 (if (not (integer? i))
3236 (scm-error 'wrong-type-arg "require-extension"
3237 "Invalid srfi name: ~S" (list i) #f))
3238 (let ((srfi-sym (string->symbol
3239 (string-append "srfi-" (number->string i)))))
3240 (if (not (memq srfi-sym %cond-expand-features))
3241 (set! use-list (cons `(use-modules (srfi ,srfi-sym))
3244 (if (pair? use-list)
3245 ;; i.e. (begin (use-modules x) (use-modules y) (use-modules z))
3246 `(begin ,@(reverse! use-list)))))
3249 'wrong-type-arg "require-extension"
3250 "Not a recognized extension type: ~S" (list extension) #f)))))
3254 ;;; {Load emacs interface support if emacs option is given.}
3257 (define (named-module-use! user usee)
3258 (module-use! (resolve-module user) (resolve-interface usee)))
3260 (define (load-emacs-interface)
3261 (and (provided? 'debug-extensions)
3262 (debug-enable 'backtrace))
3263 (named-module-use! '(guile-user) '(ice-9 emacs)))
3267 (define using-readline?
3268 (let ((using-readline? (make-fluid)))
3269 (make-procedure-with-setter
3270 (lambda () (fluid-ref using-readline?))
3271 (lambda (v) (fluid-set! using-readline? v)))))
3274 (let ((guile-user-module (resolve-module '(guile-user))))
3276 ;; Load emacs interface support if emacs option is given.
3277 (if (and (module-defined? guile-user-module 'use-emacs-interface)
3278 (module-ref guile-user-module 'use-emacs-interface))
3279 (load-emacs-interface))
3281 ;; Use some convenient modules (in reverse order)
3283 (set-current-module guile-user-module)
3284 (process-use-modules
3289 (if (provided? 'regex)
3292 (if (provided? 'threads)
3293 '(((ice-9 threads)))
3295 ;; load debugger on demand
3296 (module-autoload! guile-user-module '(ice-9 debugger) '(debug))
3298 ;; Note: SIGFPE, SIGSEGV and SIGBUS are actually "query-only" (see
3299 ;; scmsigs.c scm_sigaction_for_thread), so the handlers setup here have
3301 (let ((old-handlers #f)
3302 (start-repl (module-ref (resolve-interface '(system repl repl))
3304 (signals (if (provided? 'posix)
3305 `((,SIGINT . "User interrupt")
3306 (,SIGFPE . "Arithmetic error")
3308 . "Bad memory access (Segmentation violation)"))
3310 ;; no SIGBUS on mingw
3311 (if (defined? 'SIGBUS)
3312 (set! signals (acons SIGBUS "Bad memory access (bus error)"
3319 (let ((make-handler (lambda (msg)
3321 ;; Make a backup copy of the stack
3322 (fluid-set! before-signal-stack
3323 (fluid-ref the-last-stack))
3331 (map (lambda (sig-msg)
3332 (sigaction (car sig-msg)
3333 (make-handler (cdr sig-msg))))
3336 ;; the protected thunk.
3338 (let ((status (start-repl 'scheme)))
3339 (run-hook exit-hook)
3344 (map (lambda (sig-msg old-handler)
3345 (if (not (car old-handler))
3346 ;; restore original C handler.
3347 (sigaction (car sig-msg) #f)
3348 ;; restore Scheme handler, SIG_IGN or SIG_DFL.
3349 (sigaction (car sig-msg)
3351 (cdr old-handler))))
3352 signals old-handlers))))))
3354 ;;; This hook is run at the very end of an interactive session.
3356 (define exit-hook (make-hook))
3360 ;;; {Deprecated stuff}
3364 (define (feature? sym)
3365 (issue-deprecation-warning
3366 "`feature?' is deprecated. Use `provided?' instead.")
3370 (primitive-load-path "ice-9/deprecated"))
3374 ;;; Place the user in the guile-user module.
3377 ;;; FIXME: annotate ?
3378 ;; (define (syncase exp)
3379 ;; (with-fluids ((expansion-eval-closure
3380 ;; (module-eval-closure (current-module))))
3381 ;; (deannotate/source-properties (sc-expand (annotate exp)))))
3383 (define-module (guile-user))
3385 ;;; boot-9.scm ends here