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 ;; Input hook to syncase -- so that we might be able to pass annotated
188 ;; expressions in. Currently disabled. Maybe we should just use
189 ;; source-properties directly.
190 (define (annotation? x) #f)
192 ;; API provided by psyntax
193 (define syntax-violation #f)
194 (define datum->syntax #f)
195 (define syntax->datum #f)
196 (define identifier? #f)
197 (define generate-temporaries #f)
198 (define bound-identifier=? #f)
199 (define free-identifier=? #f)
200 (define sc-expand #f)
202 ;; $sc-expand is an implementation detail of psyntax. It is used by
203 ;; expanded macros, to dispatch an input against a set of patterns.
204 (define $sc-dispatch #f)
207 (primitive-load-path "ice-9/psyntax-pp")
209 ;; %pre-modules-transformer is the Scheme expander from now until the
210 ;; module system has booted up.
211 (define %pre-modules-transformer sc-expand)
215 ((_ exp) (make-promise (lambda () exp)))))
222 (define-syntax define-macro
226 ((_ (macro . args) doc body1 body ...)
227 (string? (syntax->datum (syntax doc)))
228 (syntax (define-macro macro doc (lambda args body1 body ...))))
229 ((_ (macro . args) body ...)
230 (syntax (define-macro macro #f (lambda args body ...))))
231 ((_ macro doc transformer)
232 (or (string? (syntax->datum (syntax doc)))
233 (not (syntax->datum (syntax doc))))
240 (let ((v (syntax->datum (syntax args))))
241 (datum->syntax y (apply transformer v))))))))))))
243 (define-syntax defmacro
245 "Define a defmacro, with the old lispy defun syntax."
247 ((_ macro args doc body1 body ...)
248 (string? (syntax->datum (syntax doc)))
249 (syntax (define-macro macro doc (lambda args body1 body ...))))
250 ((_ macro args body ...)
251 (syntax (define-macro macro #f (lambda args body ...)))))))
259 ;;; Depends on: defmacro
262 (defmacro begin-deprecated forms
263 (if (include-deprecated-features)
269 ;;; {Trivial Functions}
272 (define (identity x) x)
273 (define (and=> value procedure) (and value (procedure value)))
274 (define call/cc call-with-current-continuation)
276 ;;; apply-to-args is functionally redundant with apply and, worse,
277 ;;; is less general than apply since it only takes two arguments.
279 ;;; On the other hand, apply-to-args is a syntacticly convenient way to
280 ;;; perform binding in many circumstances when the "let" family of
281 ;;; of forms don't cut it. E.g.:
283 ;;; (apply-to-args (return-3d-mouse-coords)
288 (define (apply-to-args args fn) (apply fn args))
290 (defmacro false-if-exception (expr)
291 `(catch #t (lambda () ,expr)
296 ;;; {General Properties}
299 ;; This is a more modern interface to properties. It will replace all
300 ;; other property-like things eventually.
302 (define (make-object-property)
303 (let ((prop (primitive-make-property #f)))
304 (make-procedure-with-setter
305 (lambda (obj) (primitive-property-ref prop obj))
306 (lambda (obj val) (primitive-property-set! prop obj val)))))
310 ;;; {Symbol Properties}
313 (define (symbol-property sym prop)
314 (let ((pair (assoc prop (symbol-pref sym))))
315 (and pair (cdr pair))))
317 (define (set-symbol-property! sym prop val)
318 (let ((pair (assoc prop (symbol-pref sym))))
321 (symbol-pset! sym (acons prop val (symbol-pref sym))))))
323 (define (symbol-property-remove! sym prop)
324 (let ((pair (assoc prop (symbol-pref sym))))
326 (symbol-pset! sym (delq! pair (symbol-pref sym))))))
333 (define (array-shape a)
334 (map (lambda (ind) (if (number? ind) (list 0 (+ -1 ind)) ind))
335 (array-dimensions a)))
342 (define (kw-arg-ref args kw)
343 (let ((rem (member kw args)))
344 (and rem (pair? (cdr rem)) (cadr rem))))
351 (define (struct-layout s)
352 (struct-ref (struct-vtable s) vtable-index-layout))
359 ;; Printing records: by default, records are printed as
361 ;; #<type-name field1: val1 field2: val2 ...>
363 ;; You can change that by giving a custom printing function to
364 ;; MAKE-RECORD-TYPE (after the list of field symbols). This function
365 ;; will be called like
367 ;; (<printer> object port)
369 ;; It should print OBJECT to PORT.
371 (define (inherit-print-state old-port new-port)
372 (if (get-print-state old-port)
373 (port-with-print-state new-port (get-print-state old-port))
376 ;; 0: type-name, 1: fields
377 (define record-type-vtable
378 (make-vtable-vtable "prpr" 0
380 (cond ((eq? s record-type-vtable)
381 (display "#<record-type-vtable>" p))
383 (display "#<record-type " p)
384 (display (record-type-name s) p)
387 (define (record-type? obj)
388 (and (struct? obj) (eq? record-type-vtable (struct-vtable obj))))
390 (define (make-record-type type-name fields . opt)
391 (let ((printer-fn (and (pair? opt) (car opt))))
392 (let ((struct (make-struct record-type-vtable 0
395 (map (lambda (f) "pw") fields)))
399 (display type-name p)
400 (let loop ((fields fields)
403 ((not (null? fields))
405 (display (car fields) p)
407 (display (struct-ref s off) p)
408 (loop (cdr fields) (+ 1 off)))))
411 (copy-tree fields))))
412 ;; Temporary solution: Associate a name to the record type descriptor
413 ;; so that the object system can create a wrapper class for it.
414 (set-struct-vtable-name! struct (if (symbol? type-name)
416 (string->symbol type-name)))
419 (define (record-type-name obj)
420 (if (record-type? obj)
421 (struct-ref obj vtable-offset-user)
422 (error 'not-a-record-type obj)))
424 (define (record-type-fields obj)
425 (if (record-type? obj)
426 (struct-ref obj (+ 1 vtable-offset-user))
427 (error 'not-a-record-type obj)))
429 (define (record-constructor rtd . opt)
430 (let ((field-names (if (pair? opt) (car opt) (record-type-fields rtd))))
432 `(lambda ,field-names
433 (make-struct ',rtd 0 ,@(map (lambda (f)
434 (if (memq f field-names)
437 (record-type-fields rtd)))))))
439 (define (record-predicate rtd)
440 (lambda (obj) (and (struct? obj) (eq? rtd (struct-vtable obj)))))
442 (define (%record-type-error rtd obj) ;; private helper
443 (or (eq? rtd (record-type-descriptor obj))
444 (scm-error 'wrong-type-arg "%record-type-check"
445 "Wrong type record (want `~S'): ~S"
446 (list (record-type-name rtd) obj)
449 (define (record-accessor rtd field-name)
450 (let ((pos (list-index (record-type-fields rtd) field-name)))
452 (error 'no-such-field field-name))
454 (if (eq? (struct-vtable obj) rtd)
456 (%record-type-error rtd obj)))))
458 (define (record-modifier rtd field-name)
459 (let ((pos (list-index (record-type-fields rtd) field-name)))
461 (error 'no-such-field field-name))
463 (if (eq? (struct-vtable obj) rtd)
464 (struct-set! obj pos val)
465 (%record-type-error rtd obj)))))
467 (define (record? obj)
468 (and (struct? obj) (record-type? (struct-vtable obj))))
470 (define (record-type-descriptor obj)
473 (error 'not-a-record obj)))
482 (define (->bool x) (not (not x)))
489 (define (symbol-append . args)
490 (string->symbol (apply string-append (map symbol->string args))))
492 (define (list->symbol . args)
493 (string->symbol (apply list->string args)))
495 (define (symbol . args)
496 (string->symbol (apply string args)))
503 (define (list-index l k)
509 (loop (+ n 1) (cdr l))))))
513 (if (provided? 'posix)
514 (primitive-load-path "ice-9/posix"))
516 (if (provided? 'socket)
517 (primitive-load-path "ice-9/networking"))
519 ;; For reference, Emacs file-exists-p uses stat in this same way.
520 ;; ENHANCE-ME: Catching an exception from stat is a bit wasteful, do this in
521 ;; C where all that's needed is to inspect the return from stat().
523 (if (provided? 'posix)
525 (->bool (false-if-exception (stat str))))
527 (let ((port (catch 'system-error (lambda () (open-file str OPEN_READ))
529 (if port (begin (close-port port) #t)
532 (define file-is-directory?
533 (if (provided? 'posix)
535 (eq? (stat:type (stat str)) 'directory))
537 (let ((port (catch 'system-error
538 (lambda () (open-file (string-append str "/.")
541 (if port (begin (close-port port) #t)
544 (define (has-suffix? str suffix)
545 (string-suffix? suffix str))
547 (define (system-error-errno args)
548 (if (eq? (car args) 'system-error)
549 (car (list-ref args 4))
557 (define (error . args)
560 (scm-error 'misc-error #f "?" #f #f)
561 (let loop ((msg "~A")
563 (if (not (null? rest))
564 (loop (string-append msg " ~S")
566 (scm-error 'misc-error #f msg args #f)))))
568 ;; bad-throw is the hook that is called upon a throw to a an unhandled
569 ;; key (unless the throw has four arguments, in which case
570 ;; it's usually interpreted as an error throw.)
571 ;; If the key has a default handler (a throw-handler-default property),
572 ;; it is applied to the throw.
574 (define (bad-throw key . args)
575 (let ((default (symbol-property key 'throw-handler-default)))
576 (or (and default (apply default key args))
577 (apply error "unhandled-exception:" key args))))
581 (define (tm:sec obj) (vector-ref obj 0))
582 (define (tm:min obj) (vector-ref obj 1))
583 (define (tm:hour obj) (vector-ref obj 2))
584 (define (tm:mday obj) (vector-ref obj 3))
585 (define (tm:mon obj) (vector-ref obj 4))
586 (define (tm:year obj) (vector-ref obj 5))
587 (define (tm:wday obj) (vector-ref obj 6))
588 (define (tm:yday obj) (vector-ref obj 7))
589 (define (tm:isdst obj) (vector-ref obj 8))
590 (define (tm:gmtoff obj) (vector-ref obj 9))
591 (define (tm:zone obj) (vector-ref obj 10))
593 (define (set-tm:sec obj val) (vector-set! obj 0 val))
594 (define (set-tm:min obj val) (vector-set! obj 1 val))
595 (define (set-tm:hour obj val) (vector-set! obj 2 val))
596 (define (set-tm:mday obj val) (vector-set! obj 3 val))
597 (define (set-tm:mon obj val) (vector-set! obj 4 val))
598 (define (set-tm:year obj val) (vector-set! obj 5 val))
599 (define (set-tm:wday obj val) (vector-set! obj 6 val))
600 (define (set-tm:yday obj val) (vector-set! obj 7 val))
601 (define (set-tm:isdst obj val) (vector-set! obj 8 val))
602 (define (set-tm:gmtoff obj val) (vector-set! obj 9 val))
603 (define (set-tm:zone obj val) (vector-set! obj 10 val))
605 (define (tms:clock obj) (vector-ref obj 0))
606 (define (tms:utime obj) (vector-ref obj 1))
607 (define (tms:stime obj) (vector-ref obj 2))
608 (define (tms:cutime obj) (vector-ref obj 3))
609 (define (tms:cstime obj) (vector-ref obj 4))
611 (define file-position ftell)
612 (define (file-set-position port offset . whence)
613 (let ((whence (if (eq? whence '()) SEEK_SET (car whence))))
614 (seek port offset whence)))
616 (define (move->fdes fd/port fd)
617 (cond ((integer? fd/port)
618 (dup->fdes fd/port fd)
622 (primitive-move->fdes fd/port fd)
623 (set-port-revealed! fd/port 1)
626 (define (release-port-handle port)
627 (let ((revealed (port-revealed port)))
629 (set-port-revealed! port (- revealed 1)))))
631 (define (dup->port port/fd mode . maybe-fd)
632 (let ((port (fdopen (apply dup->fdes port/fd maybe-fd)
635 (set-port-revealed! port 1))
638 (define (dup->inport port/fd . maybe-fd)
639 (apply dup->port port/fd "r" maybe-fd))
641 (define (dup->outport port/fd . maybe-fd)
642 (apply dup->port port/fd "w" maybe-fd))
644 (define (dup port/fd . maybe-fd)
645 (if (integer? port/fd)
646 (apply dup->fdes port/fd maybe-fd)
647 (apply dup->port port/fd (port-mode port/fd) maybe-fd)))
649 (define (duplicate-port port modes)
650 (dup->port port modes))
652 (define (fdes->inport fdes)
653 (let loop ((rest-ports (fdes->ports fdes)))
654 (cond ((null? rest-ports)
655 (let ((result (fdopen fdes "r")))
656 (set-port-revealed! result 1)
658 ((input-port? (car rest-ports))
659 (set-port-revealed! (car rest-ports)
660 (+ (port-revealed (car rest-ports)) 1))
663 (loop (cdr rest-ports))))))
665 (define (fdes->outport fdes)
666 (let loop ((rest-ports (fdes->ports fdes)))
667 (cond ((null? rest-ports)
668 (let ((result (fdopen fdes "w")))
669 (set-port-revealed! result 1)
671 ((output-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 (port->fdes port)
679 (set-port-revealed! port (+ (port-revealed port) 1))
682 (define (setenv name value)
684 (putenv (string-append name "=" value))
687 (define (unsetenv name)
688 "Remove the entry for NAME from the environment."
696 ;;; Here for backward compatability
698 (define scheme-file-suffix (lambda () ".scm"))
700 (define (in-vicinity vicinity file)
701 (let ((tail (let ((len (string-length vicinity)))
704 (string-ref vicinity (- len 1))))))
705 (string-append vicinity
714 ;;; {Help for scm_shell}
716 ;;; The argument-processing code used by Guile-based shells generates
717 ;;; Scheme code based on the argument list. This page contains help
718 ;;; functions for the code it generates.
721 (define (command-line) (program-arguments))
723 ;; This is mostly for the internal use of the code generated by
724 ;; scm_compile_shell_switches.
726 (define (turn-on-debugging)
727 (debug-enable 'debug)
728 (debug-enable 'backtrace)
729 (read-enable 'positions))
731 (define (load-user-init)
732 (let* ((home (or (getenv "HOME")
733 (false-if-exception (passwd:dir (getpwuid (getuid))))
734 "/")) ;; fallback for cygwin etc.
735 (init-file (in-vicinity home ".guile")))
736 (if (file-exists? init-file)
737 (primitive-load init-file))))
741 ;;; {The interpreter stack}
744 (defmacro start-stack (tag exp)
745 `(%start-stack ,tag (lambda () ,exp)))
749 ;;; {Loading by paths}
752 ;;; Load a Scheme source file named NAME, searching for it in the
753 ;;; directories listed in %load-path, and applying each of the file
754 ;;; name extensions listed in %load-extensions.
755 (define (load-from-path name)
756 (start-stack 'load-stack
757 (primitive-load-path name)))
759 (define %load-verbosely #f)
760 (define (assert-load-verbosity v) (set! %load-verbosely v))
762 (define (%load-announce file)
764 (with-output-to-port (current-error-port)
772 (set! %load-hook %load-announce)
774 (define (load name . reader)
775 (with-fluid* current-reader (and (pair? reader) (car reader))
777 (start-stack 'load-stack
778 (primitive-load name)))))
782 ;;; {Transcendental Functions}
784 ;;; Derived from "Transcen.scm", Complex trancendental functions for SCM.
785 ;;; Written by Jerry D. Hedden, (C) FSF.
786 ;;; See the file `COPYING' for terms applying to this program.
790 (let ((integer-expt integer-expt))
792 (cond ((and (exact? z2) (integer? z2))
793 (integer-expt z1 z2))
794 ((and (real? z2) (real? z1) (>= z1 0))
797 (exp (* z2 (log z1))))))))
800 (if (real? z) ($sinh z)
801 (let ((x (real-part z)) (y (imag-part z)))
802 (make-rectangular (* ($sinh x) ($cos y))
803 (* ($cosh x) ($sin y))))))
805 (if (real? z) ($cosh z)
806 (let ((x (real-part z)) (y (imag-part z)))
807 (make-rectangular (* ($cosh x) ($cos y))
808 (* ($sinh x) ($sin y))))))
810 (if (real? z) ($tanh z)
811 (let* ((x (* 2 (real-part z)))
812 (y (* 2 (imag-part z)))
813 (w (+ ($cosh x) ($cos y))))
814 (make-rectangular (/ ($sinh x) w) (/ ($sin y) w)))))
817 (if (real? z) ($asinh z)
818 (log (+ z (sqrt (+ (* z z) 1))))))
821 (if (and (real? z) (>= z 1))
823 (log (+ z (sqrt (- (* z z) 1))))))
826 (if (and (real? z) (> z -1) (< z 1))
828 (/ (log (/ (+ 1 z) (- 1 z))) 2)))
831 (if (real? z) ($sin z)
832 (let ((x (real-part z)) (y (imag-part z)))
833 (make-rectangular (* ($sin x) ($cosh y))
834 (* ($cos x) ($sinh y))))))
836 (if (real? z) ($cos z)
837 (let ((x (real-part z)) (y (imag-part z)))
838 (make-rectangular (* ($cos x) ($cosh y))
839 (- (* ($sin x) ($sinh y)))))))
841 (if (real? z) ($tan z)
842 (let* ((x (* 2 (real-part z)))
843 (y (* 2 (imag-part z)))
844 (w (+ ($cos x) ($cosh y))))
845 (make-rectangular (/ ($sin x) w) (/ ($sinh y) w)))))
848 (if (and (real? z) (>= z -1) (<= z 1))
850 (* -i (asinh (* +i z)))))
853 (if (and (real? z) (>= z -1) (<= z 1))
855 (+ (/ (angle -1) 2) (* +i (asinh (* +i z))))))
859 (if (real? z) ($atan z)
860 (/ (log (/ (- +i z) (+ +i z))) +2i))
865 ;;; {Reader Extensions}
867 ;;; Reader code for various "#c" forms.
870 (read-hash-extend #\' (lambda (c port)
873 (define read-eval? (make-fluid))
874 (fluid-set! read-eval? #f)
875 (read-hash-extend #\.
877 (if (fluid-ref read-eval?)
878 (eval (read port) (interaction-environment))
880 "#. read expansion found and read-eval? is #f."))))
884 ;;; {Command Line Options}
887 (define (get-option argv kw-opts kw-args return)
892 ((or (not (eq? #\- (string-ref (car argv) 0)))
893 (eq? (string-length (car argv)) 1))
894 (return 'normal-arg (car argv) (cdr argv)))
896 ((eq? #\- (string-ref (car argv) 1))
897 (let* ((kw-arg-pos (or (string-index (car argv) #\=)
898 (string-length (car argv))))
899 (kw (symbol->keyword (substring (car argv) 2 kw-arg-pos)))
900 (kw-opt? (member kw kw-opts))
901 (kw-arg? (member kw kw-args))
902 (arg (or (and (not (eq? kw-arg-pos (string-length (car argv))))
903 (substring (car argv)
905 (string-length (car argv))))
907 (begin (set! argv (cdr argv)) (car argv))))))
908 (if (or kw-opt? kw-arg?)
909 (return kw arg (cdr argv))
910 (return 'usage-error kw (cdr argv)))))
913 (let* ((char (substring (car argv) 1 2))
914 (kw (symbol->keyword char)))
918 (let* ((rest-car (substring (car argv) 2 (string-length (car argv))))
919 (new-argv (if (= 0 (string-length rest-car))
921 (cons (string-append "-" rest-car) (cdr argv)))))
922 (return kw #f new-argv)))
925 (let* ((rest-car (substring (car argv) 2 (string-length (car argv))))
926 (arg (if (= 0 (string-length rest-car))
929 (new-argv (if (= 0 (string-length rest-car))
932 (return kw arg new-argv)))
934 (else (return 'usage-error kw argv)))))))
936 (define (for-next-option proc argv kw-opts kw-args)
937 (let loop ((argv argv))
938 (get-option argv kw-opts kw-args
939 (lambda (opt opt-arg argv)
940 (and opt (proc opt opt-arg argv loop))))))
942 (define (display-usage-report kw-desc)
945 (or (eq? (car kw) #t)
948 (help (cadr opt-desc))
949 (opts (car opt-desc))
950 (opts-proper (if (string? (car opts)) (cdr opts) opts))
951 (arg-name (if (string? (car opts))
952 (string-append "<" (car opts) ">")
954 (left-part (string-append
955 (with-output-to-string
957 (map (lambda (x) (display (keyword->symbol x)) (display " "))
960 (middle-part (if (and (< (string-length left-part) 30)
961 (< (string-length help) 40))
962 (make-string (- 30 (string-length left-part)) #\ )
965 (display middle-part)
972 (define (transform-usage-lambda cases)
973 (let* ((raw-usage (delq! 'else (map car cases)))
974 (usage-sans-specials (map (lambda (x)
975 (or (and (not (list? x)) x)
976 (and (symbol? (car x)) #t)
977 (and (boolean? (car x)) #t)
980 (usage-desc (delq! #t usage-sans-specials))
981 (kw-desc (map car usage-desc))
982 (kw-opts (apply append (map (lambda (x) (and (not (string? (car x))) x)) kw-desc)))
983 (kw-args (apply append (map (lambda (x) (and (string? (car x)) (cdr x))) kw-desc)))
984 (transmogrified-cases (map (lambda (case)
985 (cons (let ((opts (car case)))
986 (if (or (boolean? opts) (eq? 'else opts))
989 ((symbol? (car opts)) opts)
990 ((boolean? (car opts)) opts)
991 ((string? (caar opts)) (cdar opts))
995 `(let ((%display-usage (lambda () (display-usage-report ',usage-desc))))
997 (let %next-arg ((%argv %argv))
1001 (lambda (%opt %arg %new-argv)
1003 ,@ transmogrified-cases))))))))
1008 ;;; {Low Level Modules}
1010 ;;; These are the low level data structures for modules.
1012 ;;; Every module object is of the type 'module-type', which is a record
1013 ;;; consisting of the following members:
1015 ;;; - eval-closure: the function that defines for its module the strategy that
1016 ;;; shall be followed when looking up symbols in the module.
1018 ;;; An eval-closure is a function taking two arguments: the symbol to be
1019 ;;; looked up and a boolean value telling whether a binding for the symbol
1020 ;;; should be created if it does not exist yet. If the symbol lookup
1021 ;;; succeeded (either because an existing binding was found or because a new
1022 ;;; binding was created), a variable object representing the binding is
1023 ;;; returned. Otherwise, the value #f is returned. Note that the eval
1024 ;;; closure does not take the module to be searched as an argument: During
1025 ;;; construction of the eval-closure, the eval-closure has to store the
1026 ;;; module it belongs to in its environment. This means, that any
1027 ;;; eval-closure can belong to only one module.
1029 ;;; The eval-closure of a module can be defined arbitrarily. However, three
1030 ;;; special cases of eval-closures are to be distinguished: During startup
1031 ;;; the module system is not yet activated. In this phase, no modules are
1032 ;;; defined and all bindings are automatically stored by the system in the
1033 ;;; pre-modules-obarray. Since no eval-closures exist at this time, the
1034 ;;; functions which require an eval-closure as their argument need to be
1035 ;;; passed the value #f.
1037 ;;; The other two special cases of eval-closures are the
1038 ;;; standard-eval-closure and the standard-interface-eval-closure. Both
1039 ;;; behave equally for the case that no new binding is to be created. The
1040 ;;; difference between the two comes in, when the boolean argument to the
1041 ;;; eval-closure indicates that a new binding shall be created if it is not
1044 ;;; Given that no new binding shall be created, both standard eval-closures
1045 ;;; define the following standard strategy of searching bindings in the
1046 ;;; module: First, the module's obarray is searched for the symbol. Second,
1047 ;;; if no binding for the symbol was found in the module's obarray, the
1048 ;;; module's binder procedure is exececuted. If this procedure did not
1049 ;;; return a binding for the symbol, the modules referenced in the module's
1050 ;;; uses list are recursively searched for a binding of the symbol. If the
1051 ;;; binding can not be found in these modules also, the symbol lookup has
1054 ;;; If a new binding shall be created, the standard-interface-eval-closure
1055 ;;; immediately returns indicating failure. That is, it does not even try
1056 ;;; to look up the symbol. In contrast, the standard-eval-closure would
1057 ;;; first search the obarray, and if no binding was found there, would
1058 ;;; create a new binding in the obarray, therefore not calling the binder
1059 ;;; procedure or searching the modules in the uses list.
1061 ;;; The explanation of the following members obarray, binder and uses
1062 ;;; assumes that the symbol lookup follows the strategy that is defined in
1063 ;;; the standard-eval-closure and the standard-interface-eval-closure.
1065 ;;; - obarray: a hash table that maps symbols to variable objects. In this
1066 ;;; hash table, the definitions are found that are local to the module (that
1067 ;;; is, not imported from other modules). When looking up bindings in the
1068 ;;; module, this hash table is searched first.
1070 ;;; - binder: either #f or a function taking a module and a symbol argument.
1071 ;;; If it is a function it is called after the obarray has been
1072 ;;; unsuccessfully searched for a binding. It then can provide bindings
1073 ;;; that would otherwise not be found locally in the module.
1075 ;;; - uses: a list of modules from which non-local bindings can be inherited.
1076 ;;; These modules are the third place queried for bindings after the obarray
1077 ;;; has been unsuccessfully searched and the binder function did not deliver
1078 ;;; a result either.
1080 ;;; - transformer: either #f or a function taking a scheme expression as
1081 ;;; delivered by read. If it is a function, it will be called to perform
1082 ;;; syntax transformations (e. g. makro expansion) on the given scheme
1083 ;;; expression. The output of the transformer function will then be passed
1084 ;;; to Guile's internal memoizer. This means that the output must be valid
1085 ;;; scheme code. The only exception is, that the output may make use of the
1086 ;;; syntax extensions provided to identify the modules that a binding
1089 ;;; - name: the name of the module. This is used for all kinds of printing
1090 ;;; outputs. In certain places the module name also serves as a way of
1091 ;;; identification. When adding a module to the uses list of another
1092 ;;; module, it is made sure that the new uses list will not contain two
1093 ;;; modules of the same name.
1095 ;;; - kind: classification of the kind of module. The value is (currently?)
1096 ;;; only used for printing. It has no influence on how a module is treated.
1097 ;;; Currently the following values are used when setting the module kind:
1098 ;;; 'module, 'directory, 'interface, 'custom-interface. If no explicit kind
1099 ;;; is set, it defaults to 'module.
1101 ;;; - duplicates-handlers: a list of procedures that get called to make a
1102 ;;; choice between two duplicate bindings when name clashes occur. See the
1103 ;;; `duplicate-handlers' global variable below.
1105 ;;; - observers: a list of procedures that get called when the module is
1108 ;;; - weak-observers: a weak-key hash table of procedures that get called
1109 ;;; when the module is modified. See `module-observe-weak' for details.
1111 ;;; In addition, the module may (must?) contain a binding for
1112 ;;; `%module-public-interface'. This variable should be bound to a module
1113 ;;; representing the exported interface of a module. See the
1114 ;;; `module-public-interface' and `module-export!' procedures.
1116 ;;; !!! warning: The interface to lazy binder procedures is going
1117 ;;; to be changed in an incompatible way to permit all the basic
1118 ;;; module ops to be virtualized.
1120 ;;; (make-module size use-list lazy-binding-proc) => module
1121 ;;; module-{obarray,uses,binder}[|-set!]
1122 ;;; (module? obj) => [#t|#f]
1123 ;;; (module-locally-bound? module symbol) => [#t|#f]
1124 ;;; (module-bound? module symbol) => [#t|#f]
1125 ;;; (module-symbol-locally-interned? module symbol) => [#t|#f]
1126 ;;; (module-symbol-interned? module symbol) => [#t|#f]
1127 ;;; (module-local-variable module symbol) => [#<variable ...> | #f]
1128 ;;; (module-variable module symbol) => [#<variable ...> | #f]
1129 ;;; (module-symbol-binding module symbol opt-value)
1130 ;;; => [ <obj> | opt-value | an error occurs ]
1131 ;;; (module-make-local-var! module symbol) => #<variable...>
1132 ;;; (module-add! module symbol var) => unspecified
1133 ;;; (module-remove! module symbol) => unspecified
1134 ;;; (module-for-each proc module) => unspecified
1135 ;;; (make-scm-module) => module ; a lazy copy of the symhash module
1136 ;;; (set-current-module module) => unspecified
1137 ;;; (current-module) => #<module...>
1143 ;;; {Printing Modules}
1146 ;; This is how modules are printed. You can re-define it.
1147 ;; (Redefining is actually more complicated than simply redefining
1148 ;; %print-module because that would only change the binding and not
1149 ;; the value stored in the vtable that determines how record are
1152 (define (%print-module mod port) ; unused args: depth length style table)
1154 (display (or (module-kind mod) "module") port)
1155 (let ((name (module-name mod)))
1159 (display name port))))
1161 (display (number->string (object-address mod) 16) port)
1166 ;; A module is characterized by an obarray in which local symbols
1167 ;; are interned, a list of modules, "uses", from which non-local
1168 ;; bindings can be inherited, and an optional lazy-binder which
1169 ;; is a (CLOSURE module symbol) which, as a last resort, can provide
1170 ;; bindings that would otherwise not be found locally in the module.
1172 ;; NOTE: If you change anything here, you also need to change
1173 ;; libguile/modules.h.
1176 (make-record-type 'module
1177 '(obarray uses binder eval-closure transformer name kind
1178 duplicates-handlers import-obarray
1179 observers weak-observers)
1182 ;; make-module &opt size uses binder
1184 ;; Create a new module, perhaps with a particular size of obarray,
1185 ;; initial uses list, or binding procedure.
1190 (define (parse-arg index default)
1191 (if (> (length args) index)
1192 (list-ref args index)
1195 (define %default-import-size
1196 ;; Typical number of imported bindings actually used by a module.
1199 (if (> (length args) 3)
1200 (error "Too many args to make-module." args))
1202 (let ((size (parse-arg 0 31))
1203 (uses (parse-arg 1 '()))
1204 (binder (parse-arg 2 #f)))
1206 (if (not (integer? size))
1207 (error "Illegal size to make-module." size))
1208 (if (not (and (list? uses)
1209 (and-map module? uses)))
1210 (error "Incorrect use list." uses))
1211 (if (and binder (not (procedure? binder)))
1213 "Lazy-binder expected to be a procedure or #f." binder))
1215 (let ((module (module-constructor (make-hash-table size)
1216 uses binder #f %pre-modules-transformer
1218 (make-hash-table %default-import-size)
1220 (make-weak-key-hash-table 31))))
1222 ;; We can't pass this as an argument to module-constructor,
1223 ;; because we need it to close over a pointer to the module
1225 (set-module-eval-closure! module (standard-eval-closure module))
1229 (define module-constructor (record-constructor module-type))
1230 (define module-obarray (record-accessor module-type 'obarray))
1231 (define set-module-obarray! (record-modifier module-type 'obarray))
1232 (define module-uses (record-accessor module-type 'uses))
1233 (define set-module-uses! (record-modifier module-type 'uses))
1234 (define module-binder (record-accessor module-type 'binder))
1235 (define set-module-binder! (record-modifier module-type 'binder))
1237 ;; NOTE: This binding is used in libguile/modules.c.
1238 (define module-eval-closure (record-accessor module-type 'eval-closure))
1240 (define module-transformer (record-accessor module-type 'transformer))
1241 (define set-module-transformer! (record-modifier module-type 'transformer))
1242 ;; (define module-name (record-accessor module-type 'name)) wait until mods are booted
1243 (define set-module-name! (record-modifier module-type 'name))
1244 (define module-kind (record-accessor module-type 'kind))
1245 (define set-module-kind! (record-modifier module-type 'kind))
1246 (define module-duplicates-handlers
1247 (record-accessor module-type 'duplicates-handlers))
1248 (define set-module-duplicates-handlers!
1249 (record-modifier module-type 'duplicates-handlers))
1250 (define module-observers (record-accessor module-type 'observers))
1251 (define set-module-observers! (record-modifier module-type 'observers))
1252 (define module-weak-observers (record-accessor module-type 'weak-observers))
1253 (define module? (record-predicate module-type))
1255 (define module-import-obarray (record-accessor module-type 'import-obarray))
1257 (define set-module-eval-closure!
1258 (let ((setter (record-modifier module-type 'eval-closure)))
1259 (lambda (module closure)
1260 (setter module closure)
1261 ;; Make it possible to lookup the module from the environment.
1262 ;; This implementation is correct since an eval closure can belong
1263 ;; to maximally one module.
1264 (set-procedure-property! closure 'module module))))
1268 ;;; {Observer protocol}
1271 (define (module-observe module proc)
1272 (set-module-observers! module (cons proc (module-observers module)))
1275 (define (module-observe-weak module observer-id . proc)
1276 ;; Register PROC as an observer of MODULE under name OBSERVER-ID (which can
1277 ;; be any Scheme object). PROC is invoked and passed MODULE any time
1278 ;; MODULE is modified. PROC gets unregistered when OBSERVER-ID gets GC'd
1279 ;; (thus, it is never unregistered if OBSERVER-ID is an immediate value,
1282 ;; The two-argument version is kept for backward compatibility: when called
1283 ;; with two arguments, the observer gets unregistered when closure PROC
1284 ;; gets GC'd (making it impossible to use an anonymous lambda for PROC).
1286 (let ((proc (if (null? proc) observer-id (car proc))))
1287 (hashq-set! (module-weak-observers module) observer-id proc)))
1289 (define (module-unobserve token)
1290 (let ((module (car token))
1293 (hash-remove! (module-weak-observers module) id)
1294 (set-module-observers! module (delq1! id (module-observers module)))))
1297 (define module-defer-observers #f)
1298 (define module-defer-observers-mutex (make-mutex 'recursive))
1299 (define module-defer-observers-table (make-hash-table))
1301 (define (module-modified m)
1302 (if module-defer-observers
1303 (hash-set! module-defer-observers-table m #t)
1304 (module-call-observers m)))
1306 ;;; This function can be used to delay calls to observers so that they
1307 ;;; can be called once only in the face of massive updating of modules.
1309 (define (call-with-deferred-observers thunk)
1312 (lock-mutex module-defer-observers-mutex)
1313 (set! module-defer-observers #t))
1316 (set! module-defer-observers #f)
1317 (hash-for-each (lambda (m dummy)
1318 (module-call-observers m))
1319 module-defer-observers-table)
1320 (hash-clear! module-defer-observers-table)
1321 (unlock-mutex module-defer-observers-mutex))))
1323 (define (module-call-observers m)
1324 (for-each (lambda (proc) (proc m)) (module-observers m))
1326 ;; We assume that weak observers don't (un)register themselves as they are
1327 ;; called since this would preclude proper iteration over the hash table
1329 (hash-for-each (lambda (id proc) (proc m)) (module-weak-observers m)))
1333 ;;; {Module Searching in General}
1335 ;;; We sometimes want to look for properties of a symbol
1336 ;;; just within the obarray of one module. If the property
1337 ;;; holds, then it is said to hold ``locally'' as in, ``The symbol
1338 ;;; DISPLAY is locally rebound in the module `safe-guile'.''
1341 ;;; Other times, we want to test for a symbol property in the obarray
1342 ;;; of M and, if it is not found there, try each of the modules in the
1343 ;;; uses list of M. This is the normal way of testing for some
1344 ;;; property, so we state these properties without qualification as
1345 ;;; in: ``The symbol 'fnord is interned in module M because it is
1346 ;;; interned locally in module M2 which is a member of the uses list
1350 ;; module-search fn m
1352 ;; return the first non-#f result of FN applied to M and then to
1353 ;; the modules in the uses of m, and so on recursively. If all applications
1354 ;; return #f, then so does this function.
1356 (define (module-search fn m v)
1359 (or (module-search fn (car pos) v)
1362 (loop (module-uses m))))
1365 ;;; {Is a symbol bound in a module?}
1367 ;;; Symbol S in Module M is bound if S is interned in M and if the binding
1368 ;;; of S in M has been set to some well-defined value.
1371 ;; module-locally-bound? module symbol
1373 ;; Is a symbol bound (interned and defined) locally in a given module?
1375 (define (module-locally-bound? m v)
1376 (let ((var (module-local-variable m v)))
1378 (variable-bound? var))))
1380 ;; module-bound? module symbol
1382 ;; Is a symbol bound (interned and defined) anywhere in a given module
1385 (define (module-bound? m v)
1386 (let ((var (module-variable m v)))
1388 (variable-bound? var))))
1390 ;;; {Is a symbol interned in a module?}
1392 ;;; Symbol S in Module M is interned if S occurs in
1393 ;;; of S in M has been set to some well-defined value.
1395 ;;; It is possible to intern a symbol in a module without providing
1396 ;;; an initial binding for the corresponding variable. This is done
1398 ;;; (module-add! module symbol (make-undefined-variable))
1400 ;;; In that case, the symbol is interned in the module, but not
1401 ;;; bound there. The unbound symbol shadows any binding for that
1402 ;;; symbol that might otherwise be inherited from a member of the uses list.
1405 (define (module-obarray-get-handle ob key)
1406 ((if (symbol? key) hashq-get-handle hash-get-handle) ob key))
1408 (define (module-obarray-ref ob key)
1409 ((if (symbol? key) hashq-ref hash-ref) ob key))
1411 (define (module-obarray-set! ob key val)
1412 ((if (symbol? key) hashq-set! hash-set!) ob key val))
1414 (define (module-obarray-remove! ob key)
1415 ((if (symbol? key) hashq-remove! hash-remove!) ob key))
1417 ;; module-symbol-locally-interned? module symbol
1419 ;; is a symbol interned (not neccessarily defined) locally in a given module
1420 ;; or its uses? Interned symbols shadow inherited bindings even if
1421 ;; they are not themselves bound to a defined value.
1423 (define (module-symbol-locally-interned? m v)
1424 (not (not (module-obarray-get-handle (module-obarray m) v))))
1426 ;; module-symbol-interned? module symbol
1428 ;; is a symbol interned (not neccessarily defined) anywhere in a given module
1429 ;; or its uses? Interned symbols shadow inherited bindings even if
1430 ;; they are not themselves bound to a defined value.
1432 (define (module-symbol-interned? m v)
1433 (module-search module-symbol-locally-interned? m v))
1436 ;;; {Mapping modules x symbols --> variables}
1439 ;; module-local-variable module symbol
1440 ;; return the local variable associated with a MODULE and SYMBOL.
1442 ;;; This function is very important. It is the only function that can
1443 ;;; return a variable from a module other than the mutators that store
1444 ;;; new variables in modules. Therefore, this function is the location
1445 ;;; of the "lazy binder" hack.
1447 ;;; If symbol is defined in MODULE, and if the definition binds symbol
1448 ;;; to a variable, return that variable object.
1450 ;;; If the symbols is not found at first, but the module has a lazy binder,
1451 ;;; then try the binder.
1453 ;;; If the symbol is not found at all, return #f.
1455 ;;; (This is now written in C, see `modules.c'.)
1458 ;;; {Mapping modules x symbols --> bindings}
1460 ;;; These are similar to the mapping to variables, except that the
1461 ;;; variable is dereferenced.
1464 ;; module-symbol-binding module symbol opt-value
1466 ;; return the binding of a variable specified by name within
1467 ;; a given module, signalling an error if the variable is unbound.
1468 ;; If the OPT-VALUE is passed, then instead of signalling an error,
1469 ;; return OPT-VALUE.
1471 (define (module-symbol-local-binding m v . opt-val)
1472 (let ((var (module-local-variable m v)))
1473 (if (and var (variable-bound? var))
1475 (if (not (null? opt-val))
1477 (error "Locally unbound variable." v)))))
1479 ;; module-symbol-binding module symbol opt-value
1481 ;; return the binding of a variable specified by name within
1482 ;; a given module, signalling an error if the variable is unbound.
1483 ;; If the OPT-VALUE is passed, then instead of signalling an error,
1484 ;; return OPT-VALUE.
1486 (define (module-symbol-binding m v . opt-val)
1487 (let ((var (module-variable m v)))
1488 (if (and var (variable-bound? var))
1490 (if (not (null? opt-val))
1492 (error "Unbound variable." v)))))
1497 ;;; {Adding Variables to Modules}
1500 ;; module-make-local-var! module symbol
1502 ;; ensure a variable for V in the local namespace of M.
1503 ;; If no variable was already there, then create a new and uninitialzied
1506 ;; This function is used in modules.c.
1508 (define (module-make-local-var! m v)
1509 (or (let ((b (module-obarray-ref (module-obarray m) v)))
1512 ;; Mark as modified since this function is called when
1513 ;; the standard eval closure defines a binding
1517 ;; Create a new local variable.
1518 (let ((local-var (make-undefined-variable)))
1519 (module-add! m v local-var)
1522 ;; module-ensure-local-variable! module symbol
1524 ;; Ensure that there is a local variable in MODULE for SYMBOL. If
1525 ;; there is no binding for SYMBOL, create a new uninitialized
1526 ;; variable. Return the local variable.
1528 (define (module-ensure-local-variable! module symbol)
1529 (or (module-local-variable module symbol)
1530 (let ((var (make-undefined-variable)))
1531 (module-add! module symbol var)
1534 ;; module-add! module symbol var
1536 ;; ensure a particular variable for V in the local namespace of M.
1538 (define (module-add! m v var)
1539 (if (not (variable? var))
1540 (error "Bad variable to module-add!" var))
1541 (module-obarray-set! (module-obarray m) v var)
1542 (module-modified m))
1546 ;; make sure that a symbol is undefined in the local namespace of M.
1548 (define (module-remove! m v)
1549 (module-obarray-remove! (module-obarray m) v)
1550 (module-modified m))
1552 (define (module-clear! m)
1553 (hash-clear! (module-obarray m))
1554 (module-modified m))
1556 ;; MODULE-FOR-EACH -- exported
1558 ;; Call PROC on each symbol in MODULE, with arguments of (SYMBOL VARIABLE).
1560 (define (module-for-each proc module)
1561 (hash-for-each proc (module-obarray module)))
1563 (define (module-map proc module)
1564 (hash-map->list proc (module-obarray module)))
1568 ;;; {Low Level Bootstrapping}
1573 ;; A root module uses the pre-modules-obarray as its obarray. This
1574 ;; special obarray accumulates all bindings that have been established
1575 ;; before the module system is fully booted.
1577 ;; (The obarray continues to be used by code that has been closed over
1578 ;; before the module system has been booted.)
1580 (define (make-root-module)
1581 (let ((m (make-module 0)))
1582 (set-module-obarray! m (%get-pre-modules-obarray))
1587 ;; The root interface is a module that uses the same obarray as the
1588 ;; root module. It does not allow new definitions, tho.
1590 (define (make-scm-module)
1591 (let ((m (make-module 0)))
1592 (set-module-obarray! m (%get-pre-modules-obarray))
1593 (set-module-eval-closure! m (standard-interface-eval-closure m))
1599 ;;; {Module-based Loading}
1602 (define (save-module-excursion thunk)
1603 (let ((inner-module (current-module))
1605 (dynamic-wind (lambda ()
1606 (set! outer-module (current-module))
1607 (set-current-module inner-module)
1608 (set! inner-module #f))
1611 (set! inner-module (current-module))
1612 (set-current-module outer-module)
1613 (set! outer-module #f)))))
1615 (define basic-load load)
1617 (define (load-module filename . reader)
1618 (save-module-excursion
1620 (let ((oldname (and (current-load-port)
1621 (port-filename (current-load-port)))))
1624 (> (string-length filename) 0)
1625 (not (char=? (string-ref filename 0) #\/))
1626 (not (string=? (dirname oldname) ".")))
1627 (string-append (dirname oldname) "/" filename)
1634 ;;; {MODULE-REF -- exported}
1637 ;; Returns the value of a variable called NAME in MODULE or any of its
1638 ;; used modules. If there is no such variable, then if the optional third
1639 ;; argument DEFAULT is present, it is returned; otherwise an error is signaled.
1641 (define (module-ref module name . rest)
1642 (let ((variable (module-variable module name)))
1643 (if (and variable (variable-bound? variable))
1644 (variable-ref variable)
1646 (error "No variable named" name 'in module)
1647 (car rest) ; default value
1650 ;; MODULE-SET! -- exported
1652 ;; Sets the variable called NAME in MODULE (or in a module that MODULE uses)
1653 ;; to VALUE; if there is no such variable, an error is signaled.
1655 (define (module-set! module name value)
1656 (let ((variable (module-variable module name)))
1658 (variable-set! variable value)
1659 (error "No variable named" name 'in module))))
1661 ;; MODULE-DEFINE! -- exported
1663 ;; Sets the variable called NAME in MODULE to VALUE; if there is no such
1664 ;; variable, it is added first.
1666 (define (module-define! module name value)
1667 (let ((variable (module-local-variable module name)))
1670 (variable-set! variable value)
1671 (module-modified module))
1672 (let ((variable (make-variable value)))
1673 (module-add! module name variable)))))
1675 ;; MODULE-DEFINED? -- exported
1677 ;; Return #t iff NAME is defined in MODULE (or in a module that MODULE
1680 (define (module-defined? module name)
1681 (let ((variable (module-variable module name)))
1682 (and variable (variable-bound? variable))))
1684 ;; MODULE-USE! module interface
1686 ;; Add INTERFACE to the list of interfaces used by MODULE.
1688 (define (module-use! module interface)
1689 (if (not (or (eq? module interface)
1690 (memq interface (module-uses module))))
1692 ;; Newly used modules must be appended rather than consed, so that
1693 ;; `module-variable' traverses the use list starting from the first
1695 (set-module-uses! module
1696 (append (filter (lambda (m)
1698 (equal? (module-name m)
1699 (module-name interface))))
1700 (module-uses module))
1703 (module-modified module))))
1705 ;; MODULE-USE-INTERFACES! module interfaces
1707 ;; Same as MODULE-USE! but add multiple interfaces and check for duplicates
1709 (define (module-use-interfaces! module interfaces)
1710 (set-module-uses! module
1711 (append (module-uses module) interfaces))
1712 (module-modified module))
1716 ;;; {Recursive Namespaces}
1718 ;;; A hierarchical namespace emerges if we consider some module to be
1719 ;;; root, and variables bound to modules as nested namespaces.
1721 ;;; The routines in this file manage variable names in hierarchical namespace.
1722 ;;; Each variable name is a list of elements, looked up in successively nested
1725 ;;; (nested-ref some-root-module '(foo bar baz))
1726 ;;; => <value of a variable named baz in the module bound to bar in
1727 ;;; the module bound to foo in some-root-module>
1732 ;;; ;; a-root is a module
1733 ;;; ;; name is a list of symbols
1735 ;;; nested-ref a-root name
1736 ;;; nested-set! a-root name val
1737 ;;; nested-define! a-root name val
1738 ;;; nested-remove! a-root name
1741 ;;; (current-module) is a natural choice for a-root so for convenience there are
1744 ;;; local-ref name == nested-ref (current-module) name
1745 ;;; local-set! name val == nested-set! (current-module) name val
1746 ;;; local-define! name val == nested-define! (current-module) name val
1747 ;;; local-remove! name == nested-remove! (current-module) name
1751 (define (nested-ref root names)
1752 (let loop ((cur root)
1756 ((not (module? cur)) #f)
1757 (else (loop (module-ref cur (car elts) #f) (cdr elts))))))
1759 (define (nested-set! root names val)
1760 (let loop ((cur root)
1762 (if (null? (cdr elts))
1763 (module-set! cur (car elts) val)
1764 (loop (module-ref cur (car elts)) (cdr elts)))))
1766 (define (nested-define! root names val)
1767 (let loop ((cur root)
1769 (if (null? (cdr elts))
1770 (module-define! cur (car elts) val)
1771 (loop (module-ref cur (car elts)) (cdr elts)))))
1773 (define (nested-remove! root names)
1774 (let loop ((cur root)
1776 (if (null? (cdr elts))
1777 (module-remove! cur (car elts))
1778 (loop (module-ref cur (car elts)) (cdr elts)))))
1780 (define (local-ref names) (nested-ref (current-module) names))
1781 (define (local-set! names val) (nested-set! (current-module) names val))
1782 (define (local-define names val) (nested-define! (current-module) names val))
1783 (define (local-remove names) (nested-remove! (current-module) names))
1788 ;;; {The (%app) module}
1790 ;;; The root of conventionally named objects not directly in the top level.
1793 ;;; (%app modules guile)
1795 ;;; The directory of all modules and the standard root module.
1798 ;; module-public-interface is defined in C.
1799 (define (set-module-public-interface! m i)
1800 (module-define! m '%module-public-interface i))
1801 (define (set-system-module! m s)
1802 (set-procedure-property! (module-eval-closure m) 'system-module s))
1803 (define the-root-module (make-root-module))
1804 (define the-scm-module (make-scm-module))
1805 (set-module-public-interface! the-root-module the-scm-module)
1806 (set-module-name! the-root-module '(guile))
1807 (set-module-name! the-scm-module '(guile))
1808 (set-module-kind! the-scm-module 'interface)
1809 (set-system-module! the-root-module #t)
1810 (set-system-module! the-scm-module #t)
1812 ;; NOTE: This binding is used in libguile/modules.c.
1814 (define (make-modules-in module name)
1818 (let* ((var (module-local-variable module (car name)))
1819 (val (and var (variable-bound? var) (variable-ref var))))
1822 (let ((m (make-module 31)))
1823 (set-module-kind! m 'directory)
1824 (set-module-name! m (append (or (module-name module) '())
1826 (module-define! module (car name) m)
1830 (define (beautify-user-module! module)
1831 (let ((interface (module-public-interface module)))
1832 (if (or (not interface)
1833 (eq? interface module))
1834 (let ((interface (make-module 31)))
1835 (set-module-name! interface (module-name module))
1836 (set-module-kind! interface 'interface)
1837 (set-module-public-interface! module interface))))
1838 (if (and (not (memq the-scm-module (module-uses module)))
1839 (not (eq? module the-root-module)))
1840 ;; Import the default set of bindings (from the SCM module) in MODULE.
1841 (module-use! module the-scm-module)))
1843 ;; NOTE: This binding is used in libguile/modules.c.
1845 (define resolve-module
1846 (let ((the-root-module the-root-module))
1847 (lambda (name . maybe-autoload)
1848 (if (equal? name '(guile))
1850 (let ((full-name (append '(%app modules) name)))
1851 (let ((already (nested-ref the-root-module full-name))
1852 (autoload (or (null? maybe-autoload) (car maybe-autoload))))
1854 ((and already (module? already)
1855 (or (not autoload) (module-public-interface already)))
1856 ;; A hit, a palpable hit.
1859 ;; Try to autoload the module, and recurse.
1860 (try-load-module name)
1861 (resolve-module name #f))
1863 ;; A module is not bound (but maybe something else is),
1864 ;; we're not autoloading -- here's the weird semantics,
1865 ;; we create an empty module.
1866 (make-modules-in the-root-module full-name)))))))))
1868 ;; Cheat. These bindings are needed by modules.c, but we don't want
1869 ;; to move their real definition here because that would be unnatural.
1871 (define try-module-autoload #f)
1872 (define process-define-module #f)
1873 (define process-use-modules #f)
1874 (define module-export! #f)
1875 (define default-duplicate-binding-procedures #f)
1877 (define %app (make-module 31))
1878 (define app %app) ;; for backwards compatability
1880 (local-define '(%app modules) (make-module 31))
1881 (local-define '(%app modules guile) the-root-module)
1883 ;; This boots the module system. All bindings needed by modules.c
1884 ;; must have been defined by now.
1886 (set-current-module the-root-module)
1887 ;; definition deferred for syncase's benefit
1888 (define module-name (record-accessor module-type 'name))
1890 ;; (define-special-value '(%app modules new-ws) (lambda () (make-scm-module)))
1892 (define (try-load-module name)
1893 (try-module-autoload name))
1895 (define (purify-module! module)
1896 "Removes bindings in MODULE which are inherited from the (guile) module."
1897 (let ((use-list (module-uses module)))
1898 (if (and (pair? use-list)
1899 (eq? (car (last-pair use-list)) the-scm-module))
1900 (set-module-uses! module (reverse (cdr (reverse use-list)))))))
1902 ;; Return a module that is an interface to the module designated by
1905 ;; `resolve-interface' takes four keyword arguments:
1907 ;; #:select SELECTION
1909 ;; SELECTION is a list of binding-specs to be imported; A binding-spec
1910 ;; is either a symbol or a pair of symbols (ORIG . SEEN), where ORIG
1911 ;; is the name in the used module and SEEN is the name in the using
1912 ;; module. Note that SEEN is also passed through RENAMER, below. The
1913 ;; default is to select all bindings. If you specify no selection but
1914 ;; a renamer, only the bindings that already exist in the used module
1915 ;; are made available in the interface. Bindings that are added later
1916 ;; are not picked up.
1920 ;; BINDINGS is a list of bindings which should not be imported.
1924 ;; PREFIX is a symbol that will be appended to each exported name.
1925 ;; The default is to not perform any renaming.
1927 ;; #:renamer RENAMER
1929 ;; RENAMER is a procedure that takes a symbol and returns its new
1930 ;; name. The default is not perform any renaming.
1932 ;; Signal "no code for module" error if module name is not resolvable
1933 ;; or its public interface is not available. Signal "no binding"
1934 ;; error if selected binding does not exist in the used module.
1936 (define (resolve-interface name . args)
1938 (define (get-keyword-arg args kw def)
1939 (cond ((memq kw args)
1941 (if (null? (cdr kw-arg))
1942 (error "keyword without value: " kw))
1947 (let* ((select (get-keyword-arg args #:select #f))
1948 (hide (get-keyword-arg args #:hide '()))
1949 (renamer (or (get-keyword-arg args #:renamer #f)
1950 (let ((prefix (get-keyword-arg args #:prefix #f)))
1951 (and prefix (symbol-prefix-proc prefix)))
1953 (module (resolve-module name))
1954 (public-i (and module (module-public-interface module))))
1955 (and (or (not module) (not public-i))
1956 (error "no code for module" name))
1957 (if (and (not select) (null? hide) (eq? renamer identity))
1959 (let ((selection (or select (module-map (lambda (sym var) sym)
1961 (custom-i (make-module 31)))
1962 (set-module-kind! custom-i 'custom-interface)
1963 (set-module-name! custom-i name)
1964 ;; XXX - should use a lazy binder so that changes to the
1965 ;; used module are picked up automatically.
1966 (for-each (lambda (bspec)
1967 (let* ((direct? (symbol? bspec))
1968 (orig (if direct? bspec (car bspec)))
1969 (seen (if direct? bspec (cdr bspec)))
1970 (var (or (module-local-variable public-i orig)
1971 (module-local-variable module orig)
1973 ;; fixme: format manually for now
1975 #f "no binding `~A' in module ~A"
1977 (if (memq orig hide)
1978 (set! hide (delq! orig hide))
1979 (module-add! custom-i
1983 ;; Check that we are not hiding bindings which don't exist
1984 (for-each (lambda (binding)
1985 (if (not (module-local-variable public-i binding))
1988 #f "no binding `~A' to hide in module ~A"
1993 (define (symbol-prefix-proc prefix)
1995 (symbol-append prefix symbol)))
1997 ;; This function is called from "modules.c". If you change it, be
1998 ;; sure to update "modules.c" as well.
2000 (define (process-define-module args)
2001 (let* ((module-id (car args))
2002 (module (resolve-module module-id #f))
2004 (unrecognized (lambda (arg)
2005 (error "unrecognized define-module argument" arg))))
2006 (beautify-user-module! module)
2007 (let loop ((kws kws)
2008 (reversed-interfaces '())
2015 (call-with-deferred-observers
2017 (module-use-interfaces! module (reverse reversed-interfaces))
2018 (module-export! module exports)
2019 (module-replace! module replacements)
2020 (module-re-export! module re-exports)
2021 (if (not (null? autoloads))
2022 (apply module-autoload! module autoloads))))
2024 ((#:use-module #:use-syntax)
2025 (or (pair? (cdr kws))
2028 ((equal? (caadr kws) '(ice-9 syncase))
2029 (issue-deprecation-warning
2030 "(ice-9 syncase) is deprecated. Support for syntax-case is now in Guile core.")
2038 (let* ((interface-args (cadr kws))
2039 (interface (apply resolve-interface interface-args)))
2040 (and (eq? (car kws) #:use-syntax)
2041 (or (symbol? (caar interface-args))
2042 (error "invalid module name for use-syntax"
2043 (car interface-args)))
2044 (set-module-transformer!
2046 (module-ref interface
2047 (car (last-pair (car interface-args)))
2050 (cons interface reversed-interfaces)
2056 (or (and (pair? (cdr kws)) (pair? (cddr kws)))
2063 (let ((name (cadr kws))
2064 (bindings (caddr kws)))
2065 (cons* name bindings autoloads))))
2067 (set-system-module! module #t)
2068 (loop (cdr kws) reversed-interfaces exports re-exports
2069 replacements autoloads))
2071 (purify-module! module)
2072 (loop (cdr kws) reversed-interfaces exports re-exports
2073 replacements autoloads))
2075 (if (not (pair? (cdr kws)))
2077 (set-module-duplicates-handlers!
2079 (lookup-duplicates-handlers (cadr kws)))
2080 (loop (cddr kws) reversed-interfaces exports re-exports
2081 replacements autoloads))
2082 ((#:export #:export-syntax)
2083 (or (pair? (cdr kws))
2087 (append (cadr kws) exports)
2091 ((#:re-export #:re-export-syntax)
2092 (or (pair? (cdr kws))
2097 (append (cadr kws) re-exports)
2100 ((#:replace #:replace-syntax)
2101 (or (pair? (cdr kws))
2107 (append (cadr kws) replacements)
2110 (unrecognized kws)))))
2111 (run-hook module-defined-hook module)
2114 ;; `module-defined-hook' is a hook that is run whenever a new module
2115 ;; is defined. Its members are called with one argument, the new
2117 (define module-defined-hook (make-hook 1))
2124 (define (make-autoload-interface module name bindings)
2125 (let ((b (lambda (a sym definep)
2126 (and (memq sym bindings)
2127 (let ((i (module-public-interface (resolve-module name))))
2129 (error "missing interface for module" name))
2130 (let ((autoload (memq a (module-uses module))))
2131 ;; Replace autoload-interface with actual interface if
2132 ;; that has not happened yet.
2133 (if (pair? autoload)
2134 (set-car! autoload i)))
2135 (module-local-variable i sym))))))
2136 (module-constructor (make-hash-table 0) '() b #f #f name 'autoload #f
2137 (make-hash-table 0) '() (make-weak-value-hash-table 31))))
2139 (define (module-autoload! module . args)
2140 "Have @var{module} automatically load the module named @var{name} when one
2141 of the symbols listed in @var{bindings} is looked up. @var{args} should be a
2142 list of module-name/binding-list pairs, e.g., as in @code{(module-autoload!
2143 module '(ice-9 q) '(make-q q-length))}."
2144 (let loop ((args args))
2148 (error "invalid name+binding autoload list" args))
2150 (let ((name (car args))
2151 (bindings (cadr args)))
2152 (module-use! module (make-autoload-interface module
2154 (loop (cddr args)))))))
2159 ;;; {Autoloading modules}
2162 (define autoloads-in-progress '())
2164 ;; This function is called from "modules.c". If you change it, be
2165 ;; sure to update "modules.c" as well.
2167 (define (try-module-autoload module-name)
2168 (let* ((reverse-name (reverse module-name))
2169 (name (symbol->string (car reverse-name)))
2170 (dir-hint-module-name (reverse (cdr reverse-name)))
2171 (dir-hint (apply string-append
2173 (string-append (symbol->string elt) "/"))
2174 dir-hint-module-name))))
2175 (resolve-module dir-hint-module-name #f)
2176 (and (not (autoload-done-or-in-progress? dir-hint name))
2178 (define (load-file proc file)
2179 (save-module-excursion (lambda () (proc file)))
2182 (lambda () (autoload-in-progress! dir-hint name))
2184 (let ((file (in-vicinity dir-hint name)))
2185 (let ((compiled (and load-compiled
2187 (string-append file ".go"))))
2188 (source (%search-load-path file)))
2191 (< (stat:mtime (stat compiled))
2192 (stat:mtime (stat source)))))
2194 (warn "source file" source "newer than" compiled))
2195 (with-fluid* current-reader #f
2196 (lambda () (load-file primitive-load source))))
2198 (load-file load-compiled compiled))))))
2199 (lambda () (set-autoloaded! dir-hint name didit)))
2204 ;;; {Dynamic linking of modules}
2207 (define autoloads-done '((guile . guile)))
2209 (define (autoload-done-or-in-progress? p m)
2210 (let ((n (cons p m)))
2211 (->bool (or (member n autoloads-done)
2212 (member n autoloads-in-progress)))))
2214 (define (autoload-done! p m)
2215 (let ((n (cons p m)))
2216 (set! autoloads-in-progress
2217 (delete! n autoloads-in-progress))
2218 (or (member n autoloads-done)
2219 (set! autoloads-done (cons n autoloads-done)))))
2221 (define (autoload-in-progress! p m)
2222 (let ((n (cons p m)))
2223 (set! autoloads-done
2224 (delete! n autoloads-done))
2225 (set! autoloads-in-progress (cons n autoloads-in-progress))))
2227 (define (set-autoloaded! p m done?)
2229 (autoload-done! p m)
2230 (let ((n (cons p m)))
2231 (set! autoloads-done (delete! n autoloads-done))
2232 (set! autoloads-in-progress (delete! n autoloads-in-progress)))))
2236 ;;; {Run-time options}
2239 (defmacro define-option-interface (option-group)
2240 (let* ((option-name car)
2242 (option-documentation caddr)
2244 ;; Below follow the macros defining the run-time option interfaces.
2246 (make-options (lambda (interface)
2248 (cond ((null? args) (,interface))
2250 (,interface (car args)) (,interface))
2253 (display (option-name option))
2254 (if (< (string-length
2255 (symbol->string (option-name option)))
2259 (display (option-value option))
2261 (display (option-documentation option))
2263 (,interface #t)))))))
2265 (make-enable (lambda (interface)
2267 (,interface (append flags (,interface)))
2270 (make-disable (lambda (interface)
2272 (let ((options (,interface)))
2273 (for-each (lambda (flag)
2274 (set! options (delq! flag options)))
2276 (,interface options)
2278 (let* ((interface (car option-group))
2279 (options/enable/disable (cadr option-group)))
2281 (define ,(car options/enable/disable)
2282 ,(make-options interface))
2283 (define ,(cadr options/enable/disable)
2284 ,(make-enable interface))
2285 (define ,(caddr options/enable/disable)
2286 ,(make-disable interface))
2287 (defmacro ,(caaddr option-group) (opt val)
2288 `(,',(car options/enable/disable)
2289 (append (,',(car options/enable/disable))
2290 (list ',opt ,val))))))))
2292 (define-option-interface
2293 (eval-options-interface
2294 (eval-options eval-enable eval-disable)
2297 (define-option-interface
2298 (debug-options-interface
2299 (debug-options debug-enable debug-disable)
2302 (define-option-interface
2303 (evaluator-traps-interface
2304 (traps trap-enable trap-disable)
2307 (define-option-interface
2308 (read-options-interface
2309 (read-options read-enable read-disable)
2312 (define-option-interface
2313 (print-options-interface
2314 (print-options print-enable print-disable)
2322 (define (repl read evaler print)
2323 (let loop ((source (read (current-input-port))))
2324 (print (evaler source))
2325 (loop (read (current-input-port)))))
2327 ;; A provisional repl that acts like the SCM repl:
2329 (define scm-repl-silent #f)
2330 (define (assert-repl-silence v) (set! scm-repl-silent v))
2332 (define *unspecified* (if #f #f))
2333 (define (unspecified? v) (eq? v *unspecified*))
2335 (define scm-repl-print-unspecified #f)
2336 (define (assert-repl-print-unspecified v) (set! scm-repl-print-unspecified v))
2338 (define scm-repl-verbose #f)
2339 (define (assert-repl-verbosity v) (set! scm-repl-verbose v))
2341 (define scm-repl-prompt "guile> ")
2343 (define (set-repl-prompt! v) (set! scm-repl-prompt v))
2345 (define (default-pre-unwind-handler key . args)
2346 (save-stack pre-unwind-handler-dispatch)
2347 (apply throw key args))
2349 (define (pre-unwind-handler-dispatch key . args)
2350 (apply default-pre-unwind-handler key args))
2352 (define abort-hook (make-hook))
2354 ;; these definitions are used if running a script.
2355 ;; otherwise redefined in error-catching-loop.
2356 (define (set-batch-mode?! arg) #t)
2357 (define (batch-mode?) #t)
2359 (define (error-catching-loop thunk)
2362 (define (loop first)
2367 (call-with-unblocked-asyncs
2373 ;; This line is needed because mark
2374 ;; doesn't do closures quite right.
2375 ;; Unreferenced locals should be
2378 (let loop ((v (thunk)))
2382 (lambda (key . args)
2389 (apply throw 'switch-repl args))
2392 ;; This is one of the closures that require
2393 ;; (set! first #f) above
2396 (run-hook abort-hook)
2397 (force-output (current-output-port))
2398 (display "ABORT: " (current-error-port))
2399 (write args (current-error-port))
2400 (newline (current-error-port))
2404 (not has-shown-debugger-hint?)
2405 (not (memq 'backtrace
2406 (debug-options-interface)))
2407 (stack? (fluid-ref the-last-stack)))
2409 (newline (current-error-port))
2411 "Type \"(backtrace)\" to get more information or \"(debug)\" to enter the debugger.\n"
2412 (current-error-port))
2413 (set! has-shown-debugger-hint? #t)))
2414 (force-output (current-error-port)))
2416 (primitive-exit 1)))
2417 (set! stack-saved? #f)))
2420 ;; This is the other cons-leak closure...
2422 (cond ((= (length args) 4)
2423 (apply handle-system-error key args))
2425 (apply bad-throw key args)))))))
2427 ;; Note that having just `pre-unwind-handler-dispatch'
2428 ;; here is connected with the mechanism that
2429 ;; produces a nice backtrace upon error. If, for
2430 ;; example, this is replaced with (lambda args
2431 ;; (apply pre-unwind-handler-dispatch args)), the stack
2432 ;; cutting (in save-stack) goes wrong and ends up
2433 ;; saving no stack at all, so there is no
2435 pre-unwind-handler-dispatch)))
2437 (if next (loop next) status)))
2438 (set! set-batch-mode?! (lambda (arg)
2440 (set! interactive #f)
2443 (error "sorry, not implemented")))))
2444 (set! batch-mode? (lambda () (not interactive)))
2445 (call-with-blocked-asyncs
2446 (lambda () (loop (lambda () #t))))))
2448 ;;(define the-last-stack (make-fluid)) Defined by scm_init_backtrace ()
2449 (define before-signal-stack (make-fluid))
2450 (define stack-saved? #f)
2452 (define (save-stack . narrowing)
2454 (cond ((not (memq 'debug (debug-options-interface)))
2455 (fluid-set! the-last-stack #f)
2456 (set! stack-saved? #t))
2462 (apply make-stack #t save-stack primitive-eval #t 0 narrowing))
2464 (apply make-stack #t save-stack 0 #t 0 narrowing))
2466 (apply make-stack #t save-stack tk-stack-mark #t 0 narrowing))
2468 (apply make-stack #t save-stack 0 1 narrowing))
2470 (let ((id (stack-id #t)))
2471 (and (procedure? id)
2472 (apply make-stack #t save-stack id #t 0 narrowing))))))
2473 (set! stack-saved? #t)))))
2475 (define before-error-hook (make-hook))
2476 (define after-error-hook (make-hook))
2477 (define before-backtrace-hook (make-hook))
2478 (define after-backtrace-hook (make-hook))
2480 (define has-shown-debugger-hint? #f)
2482 (define (handle-system-error key . args)
2483 (let ((cep (current-error-port)))
2484 (cond ((not (stack? (fluid-ref the-last-stack))))
2485 ((memq 'backtrace (debug-options-interface))
2486 (let ((highlights (if (or (eq? key 'wrong-type-arg)
2487 (eq? key 'out-of-range))
2490 (run-hook before-backtrace-hook)
2492 (display "Backtrace:\n")
2493 (display-backtrace (fluid-ref the-last-stack) cep
2496 (run-hook after-backtrace-hook))))
2497 (run-hook before-error-hook)
2498 (apply display-error (fluid-ref the-last-stack) cep args)
2499 (run-hook after-error-hook)
2501 (throw 'abort key)))
2503 (define (quit . args)
2504 (apply throw 'quit args))
2508 ;;(define has-shown-backtrace-hint? #f) Defined by scm_init_backtrace ()
2510 ;; Replaced by C code:
2511 ;;(define (backtrace)
2512 ;; (if (fluid-ref the-last-stack)
2515 ;; (display-backtrace (fluid-ref the-last-stack) (current-output-port))
2517 ;; (if (and (not has-shown-backtrace-hint?)
2518 ;; (not (memq 'backtrace (debug-options-interface))))
2521 ;;"Type \"(debug-enable 'backtrace)\" if you would like a backtrace
2522 ;;automatically if an error occurs in the future.\n")
2523 ;; (set! has-shown-backtrace-hint? #t))))
2524 ;; (display "No backtrace available.\n")))
2526 (define (error-catching-repl r e p)
2527 (error-catching-loop
2529 (call-with-values (lambda () (e (r)))
2530 (lambda the-values (for-each p the-values))))))
2532 (define (gc-run-time)
2533 (cdr (assq 'gc-time-taken (gc-stats))))
2535 (define before-read-hook (make-hook))
2536 (define after-read-hook (make-hook))
2537 (define before-eval-hook (make-hook 1))
2538 (define after-eval-hook (make-hook 1))
2539 (define before-print-hook (make-hook 1))
2540 (define after-print-hook (make-hook 1))
2542 ;;; The default repl-reader function. We may override this if we've
2543 ;;; the readline library.
2546 (display (if (string? prompt) prompt (prompt)))
2548 (run-hook before-read-hook)
2549 ((or (fluid-ref current-reader) read) (current-input-port))))
2551 (define (scm-style-repl)
2556 (repl-report-start-timing (lambda ()
2557 (set! start-gc-rt (gc-run-time))
2558 (set! start-rt (get-internal-run-time))))
2559 (repl-report (lambda ()
2561 (display (inexact->exact
2562 (* 1000 (/ (- (get-internal-run-time) start-rt)
2563 internal-time-units-per-second))))
2565 (display (inexact->exact
2566 (* 1000 (/ (- (gc-run-time) start-gc-rt)
2567 internal-time-units-per-second))))
2568 (display " msec in gc)\n")))
2570 (consume-trailing-whitespace
2572 (let ((ch (peek-char)))
2575 ((or (char=? ch #\space) (char=? ch #\tab))
2577 (consume-trailing-whitespace))
2578 ((char=? ch #\newline)
2582 (let ((prompt (cond ((string? scm-repl-prompt)
2584 ((thunk? scm-repl-prompt)
2586 (scm-repl-prompt "> ")
2588 (repl-reader prompt))))
2590 ;; As described in R4RS, the READ procedure updates the
2591 ;; port to point to the first character past the end of
2592 ;; the external representation of the object. This
2593 ;; means that it doesn't consume the newline typically
2594 ;; found after an expression. This means that, when
2595 ;; debugging Guile with GDB, GDB gets the newline, which
2596 ;; it often interprets as a "continue" command, making
2597 ;; breakpoints kind of useless. So, consume any
2598 ;; trailing newline here, as well as any whitespace
2600 ;; But not if EOF, for control-D.
2601 (if (not (eof-object? val))
2602 (consume-trailing-whitespace))
2603 (run-hook after-read-hook)
2604 (if (eof-object? val)
2606 (repl-report-start-timing)
2607 (if scm-repl-verbose
2610 (display ";;; EOF -- quitting")
2615 (-eval (lambda (sourc)
2616 (repl-report-start-timing)
2617 (run-hook before-eval-hook sourc)
2618 (let ((val (start-stack 'repl-stack
2619 ;; If you change this procedure
2620 ;; (primitive-eval), please also
2621 ;; modify the repl-stack case in
2622 ;; save-stack so that stack cutting
2623 ;; continues to work.
2624 (primitive-eval sourc))))
2625 (run-hook after-eval-hook sourc)
2629 (-print (let ((maybe-print (lambda (result)
2630 (if (or scm-repl-print-unspecified
2631 (not (unspecified? result)))
2636 (if (not scm-repl-silent)
2638 (run-hook before-print-hook result)
2639 (maybe-print result)
2640 (run-hook after-print-hook result)
2641 (if scm-repl-verbose
2645 (-quit (lambda (args)
2646 (if scm-repl-verbose
2648 (display ";;; QUIT executed, repl exitting")
2654 (if scm-repl-verbose
2656 (display ";;; ABORT executed.")
2659 (repl -read -eval -print))))
2661 (let ((status (error-catching-repl -read
2669 ;;; {IOTA functions: generating lists of numbers}
2673 (let loop ((count (1- n)) (result '()))
2674 (if (< count 0) result
2675 (loop (1- count) (cons count result)))))
2681 ;;; Similar to `begin' but returns a list of the results of all constituent
2682 ;;; forms instead of the result of the last form.
2683 ;;; (The definition relies on the current left-to-right
2684 ;;; order of evaluation of operands in applications.)
2687 (defmacro collect forms
2695 ;; with-fluids is a convenience wrapper for the builtin procedure
2696 ;; `with-fluids*'. The syntax is just like `let':
2698 ;; (with-fluids ((fluid val)
2702 (defmacro with-fluids (bindings . body)
2703 (let ((fluids (map car bindings))
2704 (values (map cadr bindings)))
2705 (if (and (= (length fluids) 1) (= (length values) 1))
2706 `(with-fluid* ,(car fluids) ,(car values) (lambda () ,@body))
2707 `(with-fluids* (list ,@fluids) (list ,@values)
2708 (lambda () ,@body)))))
2712 ;;; with `continue' and `break'.
2715 ;; The inner `do' loop avoids re-establishing a catch every iteration,
2716 ;; that's only necessary if continue is actually used. A new key is
2717 ;; generated every time, so break and continue apply to their originating
2718 ;; `while' even when recursing.
2720 ;; FIXME: This macro is unintentionally unhygienic with respect to let,
2721 ;; make-symbol, do, throw, catch, lambda, and not.
2723 (define-macro (while cond . body)
2724 (let ((keyvar (make-symbol "while-keyvar")))
2725 `(let ((,keyvar (make-symbol "while-key")))
2729 (let ((break (lambda () (throw ,keyvar #t)))
2730 (continue (lambda () (throw ,keyvar #f))))
2741 ;;; {Module System Macros}
2744 ;; Return a list of expressions that evaluate to the appropriate
2745 ;; arguments for resolve-interface according to SPEC.
2749 (if (memq 'prefix (read-options))
2750 (error "boot-9 must be compiled with #:kw, not :kw")))
2752 (define (compile-interface-spec spec)
2753 (define (make-keyarg sym key quote?)
2754 (cond ((or (memq sym spec)
2758 (list key (list 'quote (cadr rest)))
2759 (list key (cadr rest)))))
2762 (define (map-apply func list)
2763 (map (lambda (args) (apply func args)) list))
2766 '((:select #:select #t)
2768 (:prefix #:prefix #t)
2769 (:renamer #:renamer #f)))
2770 (if (not (pair? (car spec)))
2773 ,@(apply append (map-apply make-keyarg keys)))))
2775 (define (keyword-like-symbol->keyword sym)
2776 (symbol->keyword (string->symbol (substring (symbol->string sym) 1))))
2778 (define (compile-define-module-args args)
2779 ;; Just quote everything except #:use-module and #:use-syntax. We
2780 ;; need to know about all arguments regardless since we want to turn
2781 ;; symbols that look like keywords into real keywords, and the
2782 ;; keyword args in a define-module form are not regular
2783 ;; (i.e. no-backtrace doesn't take a value).
2784 (let loop ((compiled-args `((quote ,(car args))))
2787 (reverse! compiled-args))
2788 ;; symbol in keyword position
2789 ((symbol? (car args))
2791 (cons (keyword-like-symbol->keyword (car args)) (cdr args))))
2792 ((memq (car args) '(#:no-backtrace #:pure))
2793 (loop (cons (car args) compiled-args)
2796 (error "keyword without value:" (car args)))
2797 ((memq (car args) '(#:use-module #:use-syntax))
2798 (loop (cons* `(list ,@(compile-interface-spec (cadr args)))
2802 ((eq? (car args) #:autoload)
2803 (loop (cons* `(quote ,(caddr args))
2804 `(quote ,(cadr args))
2809 (loop (cons* `(quote ,(cadr args))
2814 (defmacro define-module args
2817 (let ((m (process-define-module
2818 (list ,@(compile-define-module-args args)))))
2819 (set-current-module m)
2822 ;; The guts of the use-modules macro. Add the interfaces of the named
2823 ;; modules to the use-list of the current module, in order.
2825 ;; This function is called by "modules.c". If you change it, be sure
2826 ;; to change scm_c_use_module as well.
2828 (define (process-use-modules module-interface-args)
2829 (let ((interfaces (map (lambda (mif-args)
2830 (or (apply resolve-interface mif-args)
2831 (error "no such module" mif-args)))
2832 module-interface-args)))
2833 (call-with-deferred-observers
2835 (module-use-interfaces! (current-module) interfaces)))))
2837 (defmacro use-modules modules
2840 (process-use-modules
2841 (list ,@(map (lambda (m)
2842 `(list ,@(compile-interface-spec m)))
2846 (defmacro use-syntax (spec)
2849 (issue-deprecation-warning
2850 "`use-syntax' is deprecated. Please contact guile-devel for more info.")
2851 (process-use-modules (list (list ,@(compile-interface-spec spec))))
2854 ;; Dirk:FIXME:: This incorrect (according to R5RS) syntax needs to be changed
2855 ;; as soon as guile supports hygienic macros.
2856 (define-syntax define-private
2861 (define-syntax define-public
2863 ((_ (name . args) . body)
2864 (define-public name (lambda args . body)))
2870 (define-syntax defmacro-public
2872 ((_ name args . body)
2874 (defmacro name args . body)
2875 (export-syntax name)))))
2877 ;; Export a local variable
2879 ;; This function is called from "modules.c". If you change it, be
2880 ;; sure to update "modules.c" as well.
2882 (define (module-export! m names)
2883 (let ((public-i (module-public-interface m)))
2884 (for-each (lambda (name)
2885 (let ((var (module-ensure-local-variable! m name)))
2886 (module-add! public-i name var)))
2889 (define (module-replace! m names)
2890 (let ((public-i (module-public-interface m)))
2891 (for-each (lambda (name)
2892 (let ((var (module-ensure-local-variable! m name)))
2893 (set-object-property! var 'replace #t)
2894 (module-add! public-i name var)))
2897 ;; Re-export a imported variable
2899 (define (module-re-export! m names)
2900 (let ((public-i (module-public-interface m)))
2901 (for-each (lambda (name)
2902 (let ((var (module-variable m name)))
2904 (error "Undefined variable:" name))
2905 ((eq? var (module-local-variable m name))
2906 (error "re-exporting local variable:" name))
2908 (module-add! public-i name var)))))
2911 (defmacro export names
2912 `(call-with-deferred-observers
2914 (module-export! (current-module) ',names))))
2916 (defmacro re-export names
2917 `(call-with-deferred-observers
2919 (module-re-export! (current-module) ',names))))
2921 (defmacro export-syntax names
2924 (defmacro re-export-syntax names
2925 `(re-export ,@names))
2927 (define load load-module)
2931 ;;; {Compiler interface}
2933 ;;; The full compiler interface can be found in (system). Here we put a
2934 ;;; few useful procedures into the global namespace.
2936 (module-autoload! the-scm-module
2937 '(system base compile)
2939 compile-time-environment))
2947 (define make-mutable-parameter
2948 (let ((make (lambda (fluid converter)
2952 (fluid-set! fluid (converter (car args))))))))
2953 (lambda (init . converter)
2954 (let ((fluid (make-fluid))
2955 (converter (if (null? converter)
2958 (fluid-set! fluid (converter init))
2959 (make fluid converter)))))
2963 ;;; {Handling of duplicate imported bindings}
2966 ;; Duplicate handlers take the following arguments:
2968 ;; module importing module
2969 ;; name conflicting name
2970 ;; int1 old interface where name occurs
2971 ;; val1 value of binding in old interface
2972 ;; int2 new interface where name occurs
2973 ;; val2 value of binding in new interface
2974 ;; var previous resolution or #f
2975 ;; val value of previous resolution
2977 ;; A duplicate handler can take three alternative actions:
2979 ;; 1. return #f => leave responsibility to next handler
2980 ;; 2. exit with an error
2981 ;; 3. return a variable resolving the conflict
2984 (define duplicate-handlers
2985 (let ((m (make-module 7)))
2987 (define (check module name int1 val1 int2 val2 var val)
2988 (scm-error 'misc-error
2990 "~A: `~A' imported from both ~A and ~A"
2991 (list (module-name module)
2997 (define (warn module name int1 val1 int2 val2 var val)
2998 (format (current-error-port)
2999 "WARNING: ~A: `~A' imported from both ~A and ~A\n"
3000 (module-name module)
3006 (define (replace module name int1 val1 int2 val2 var val)
3007 (let ((old (or (and var (object-property var 'replace) var)
3008 (module-variable int1 name)))
3009 (new (module-variable int2 name)))
3010 (if (object-property old 'replace)
3011 (and (or (eq? old new)
3012 (not (object-property new 'replace)))
3014 (and (object-property new 'replace)
3017 (define (warn-override-core module name int1 val1 int2 val2 var val)
3018 (and (eq? int1 the-scm-module)
3020 (format (current-error-port)
3021 "WARNING: ~A: imported module ~A overrides core binding `~A'\n"
3022 (module-name module)
3025 (module-local-variable int2 name))))
3027 (define (first module name int1 val1 int2 val2 var val)
3028 (or var (module-local-variable int1 name)))
3030 (define (last module name int1 val1 int2 val2 var val)
3031 (module-local-variable int2 name))
3033 (define (noop module name int1 val1 int2 val2 var val)
3036 (set-module-name! m 'duplicate-handlers)
3037 (set-module-kind! m 'interface)
3038 (module-define! m 'check check)
3039 (module-define! m 'warn warn)
3040 (module-define! m 'replace replace)
3041 (module-define! m 'warn-override-core warn-override-core)
3042 (module-define! m 'first first)
3043 (module-define! m 'last last)
3044 (module-define! m 'merge-generics noop)
3045 (module-define! m 'merge-accessors noop)
3048 (define (lookup-duplicates-handlers handler-names)
3050 (map (lambda (handler-name)
3051 (or (module-symbol-local-binding
3052 duplicate-handlers handler-name #f)
3053 (error "invalid duplicate handler name:"
3055 (if (list? handler-names)
3057 (list handler-names)))))
3059 (define default-duplicate-binding-procedures
3060 (make-mutable-parameter #f))
3062 (define default-duplicate-binding-handler
3063 (make-mutable-parameter '(replace warn-override-core warn last)
3064 (lambda (handler-names)
3065 (default-duplicate-binding-procedures
3066 (lookup-duplicates-handlers handler-names))
3071 ;;; {`cond-expand' for SRFI-0 support.}
3073 ;;; This syntactic form expands into different commands or
3074 ;;; definitions, depending on the features provided by the Scheme
3080 ;;; --> (cond-expand <cond-expand-clause>+)
3081 ;;; | (cond-expand <cond-expand-clause>* (else <command-or-definition>))
3082 ;;; <cond-expand-clause>
3083 ;;; --> (<feature-requirement> <command-or-definition>*)
3084 ;;; <feature-requirement>
3085 ;;; --> <feature-identifier>
3086 ;;; | (and <feature-requirement>*)
3087 ;;; | (or <feature-requirement>*)
3088 ;;; | (not <feature-requirement>)
3089 ;;; <feature-identifier>
3090 ;;; --> <a symbol which is the name or alias of a SRFI>
3092 ;;; Additionally, this implementation provides the
3093 ;;; <feature-identifier>s `guile' and `r5rs', so that programs can
3094 ;;; determine the implementation type and the supported standard.
3096 ;;; Currently, the following feature identifiers are supported:
3098 ;;; guile r5rs srfi-0 srfi-4 srfi-6 srfi-13 srfi-14 srfi-55 srfi-61
3100 ;;; Remember to update the features list when adding more SRFIs.
3103 (define %cond-expand-features
3104 ;; Adjust the above comment when changing this.
3107 srfi-0 ;; cond-expand itself
3108 srfi-4 ;; homogenous numeric vectors
3109 srfi-6 ;; open-input-string etc, in the guile core
3110 srfi-13 ;; string library
3111 srfi-14 ;; character sets
3112 srfi-55 ;; require-extension
3113 srfi-61 ;; general cond clause
3116 ;; This table maps module public interfaces to the list of features.
3118 (define %cond-expand-table (make-hash-table 31))
3120 ;; Add one or more features to the `cond-expand' feature list of the
3123 (define (cond-expand-provide module features)
3124 (let ((mod (module-public-interface module)))
3126 (hashq-set! %cond-expand-table mod
3127 (append (hashq-ref %cond-expand-table mod '())
3131 (procedure->memoizing-macro
3133 (let ((clauses (cdr exp))
3134 (syntax-error (lambda (cl)
3135 (error "invalid clause in `cond-expand'" cl))))
3141 (or (memq clause %cond-expand-features)
3142 (let lp ((uses (module-uses (env-module env))))
3145 (hashq-ref %cond-expand-table
3151 ((eq? 'and (car clause))
3152 (let lp ((l (cdr clause)))
3156 (and (test-clause (car l)) (lp (cdr l))))
3158 (syntax-error clause)))))
3159 ((eq? 'or (car clause))
3160 (let lp ((l (cdr clause)))
3164 (or (test-clause (car l)) (lp (cdr l))))
3166 (syntax-error clause)))))
3167 ((eq? 'not (car clause))
3168 (cond ((not (pair? (cdr clause)))
3169 (syntax-error clause))
3170 ((pair? (cddr clause))
3171 ((syntax-error clause))))
3172 (not (test-clause (cadr clause))))
3174 (syntax-error clause))))
3176 (syntax-error clause))))))
3177 (let lp ((c clauses))
3180 (error "Unfulfilled `cond-expand'"))
3183 ((not (pair? (car c)))
3184 (syntax-error (car c)))
3185 ((test-clause (caar c))
3186 `(begin ,@(cdar c)))
3187 ((eq? (caar c) 'else)
3190 `(begin ,@(cdar c)))
3192 (lp (cdr c))))))))))
3194 ;; This procedure gets called from the startup code with a list of
3195 ;; numbers, which are the numbers of the SRFIs to be loaded on startup.
3197 (define (use-srfis srfis)
3198 (process-use-modules
3200 (list (list 'srfi (string->symbol
3201 (string-append "srfi-" (number->string num))))))
3206 ;;; srfi-55: require-extension
3209 (define-macro (require-extension extension-spec)
3210 ;; This macro only handles the srfi extension, which, at present, is
3211 ;; the only one defined by the standard.
3212 (if (not (pair? extension-spec))
3213 (scm-error 'wrong-type-arg "require-extension"
3214 "Not an extension: ~S" (list extension-spec) #f))
3215 (let ((extension (car extension-spec))
3216 (extension-args (cdr extension-spec)))
3219 (let ((use-list '()))
3222 (if (not (integer? i))
3223 (scm-error 'wrong-type-arg "require-extension"
3224 "Invalid srfi name: ~S" (list i) #f))
3225 (let ((srfi-sym (string->symbol
3226 (string-append "srfi-" (number->string i)))))
3227 (if (not (memq srfi-sym %cond-expand-features))
3228 (set! use-list (cons `(use-modules (srfi ,srfi-sym))
3231 (if (pair? use-list)
3232 ;; i.e. (begin (use-modules x) (use-modules y) (use-modules z))
3233 `(begin ,@(reverse! use-list)))))
3236 'wrong-type-arg "require-extension"
3237 "Not a recognized extension type: ~S" (list extension) #f)))))
3241 ;;; {Load emacs interface support if emacs option is given.}
3244 (define (named-module-use! user usee)
3245 (module-use! (resolve-module user) (resolve-interface usee)))
3247 (define (load-emacs-interface)
3248 (and (provided? 'debug-extensions)
3249 (debug-enable 'backtrace))
3250 (named-module-use! '(guile-user) '(ice-9 emacs)))
3254 (define using-readline?
3255 (let ((using-readline? (make-fluid)))
3256 (make-procedure-with-setter
3257 (lambda () (fluid-ref using-readline?))
3258 (lambda (v) (fluid-set! using-readline? v)))))
3261 (let ((guile-user-module (resolve-module '(guile-user))))
3263 ;; Load emacs interface support if emacs option is given.
3264 (if (and (module-defined? guile-user-module 'use-emacs-interface)
3265 (module-ref guile-user-module 'use-emacs-interface))
3266 (load-emacs-interface))
3268 ;; Use some convenient modules (in reverse order)
3270 (set-current-module guile-user-module)
3271 (process-use-modules
3276 (if (provided? 'regex)
3279 (if (provided? 'threads)
3280 '(((ice-9 threads)))
3282 ;; load debugger on demand
3283 (module-autoload! guile-user-module '(ice-9 debugger) '(debug))
3285 ;; Note: SIGFPE, SIGSEGV and SIGBUS are actually "query-only" (see
3286 ;; scmsigs.c scm_sigaction_for_thread), so the handlers setup here have
3288 (let ((old-handlers #f)
3289 (start-repl (module-ref (resolve-interface '(system repl repl))
3291 (signals (if (provided? 'posix)
3292 `((,SIGINT . "User interrupt")
3293 (,SIGFPE . "Arithmetic error")
3295 . "Bad memory access (Segmentation violation)"))
3297 ;; no SIGBUS on mingw
3298 (if (defined? 'SIGBUS)
3299 (set! signals (acons SIGBUS "Bad memory access (bus error)"
3306 (let ((make-handler (lambda (msg)
3308 ;; Make a backup copy of the stack
3309 (fluid-set! before-signal-stack
3310 (fluid-ref the-last-stack))
3318 (map (lambda (sig-msg)
3319 (sigaction (car sig-msg)
3320 (make-handler (cdr sig-msg))))
3323 ;; the protected thunk.
3325 (let ((status (start-repl 'scheme)))
3326 (run-hook exit-hook)
3331 (map (lambda (sig-msg old-handler)
3332 (if (not (car old-handler))
3333 ;; restore original C handler.
3334 (sigaction (car sig-msg) #f)
3335 ;; restore Scheme handler, SIG_IGN or SIG_DFL.
3336 (sigaction (car sig-msg)
3338 (cdr old-handler))))
3339 signals old-handlers))))))
3341 ;;; This hook is run at the very end of an interactive session.
3343 (define exit-hook (make-hook))
3347 ;;; {Deprecated stuff}
3351 (define (feature? sym)
3352 (issue-deprecation-warning
3353 "`feature?' is deprecated. Use `provided?' instead.")
3357 (primitive-load-path "ice-9/deprecated"))
3361 ;;; Place the user in the guile-user module.
3364 ;;; FIXME: annotate ?
3365 ;; (define (syncase exp)
3366 ;; (with-fluids ((expansion-eval-closure
3367 ;; (module-eval-closure (current-module))))
3368 ;; (deannotate/source-properties (sc-expand (annotate exp)))))
3370 (define-module (guile-user))
3372 ;;; boot-9.scm ends here