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)
218 (define-syntax define-macro
222 ((_ (macro . args) doc body1 body ...)
223 (string? (syntax->datum (syntax doc)))
224 (syntax (define-macro macro doc (lambda args body1 body ...))))
225 ((_ (macro . args) body ...)
226 (syntax (define-macro macro #f (lambda args body ...))))
227 ((_ macro doc transformer)
228 (or (string? (syntax->datum (syntax doc)))
229 (not (syntax->datum (syntax doc))))
236 (let ((v (syntax->datum (syntax args))))
237 (datum->syntax y (apply transformer v))))))))))))
239 (define-syntax defmacro
241 "Define a defmacro, with the old lispy defun syntax."
243 ((_ macro args doc body1 body ...)
244 (string? (syntax->datum (syntax doc)))
245 (syntax (define-macro macro doc (lambda args body1 body ...))))
246 ((_ macro args body ...)
247 (syntax (define-macro macro #f (lambda args body ...)))))))
255 ;;; Depends on: defmacro
258 (defmacro begin-deprecated forms
259 (if (include-deprecated-features)
265 ;;; {Trivial Functions}
268 (define (identity x) x)
269 (define (and=> value procedure) (and value (procedure value)))
270 (define call/cc call-with-current-continuation)
272 ;;; apply-to-args is functionally redundant with apply and, worse,
273 ;;; is less general than apply since it only takes two arguments.
275 ;;; On the other hand, apply-to-args is a syntacticly convenient way to
276 ;;; perform binding in many circumstances when the "let" family of
277 ;;; of forms don't cut it. E.g.:
279 ;;; (apply-to-args (return-3d-mouse-coords)
284 (define (apply-to-args args fn) (apply fn args))
286 (defmacro false-if-exception (expr)
287 `(catch #t (lambda () ,expr)
292 ;;; {General Properties}
295 ;; This is a more modern interface to properties. It will replace all
296 ;; other property-like things eventually.
298 (define (make-object-property)
299 (let ((prop (primitive-make-property #f)))
300 (make-procedure-with-setter
301 (lambda (obj) (primitive-property-ref prop obj))
302 (lambda (obj val) (primitive-property-set! prop obj val)))))
306 ;;; {Symbol Properties}
309 (define (symbol-property sym prop)
310 (let ((pair (assoc prop (symbol-pref sym))))
311 (and pair (cdr pair))))
313 (define (set-symbol-property! sym prop val)
314 (let ((pair (assoc prop (symbol-pref sym))))
317 (symbol-pset! sym (acons prop val (symbol-pref sym))))))
319 (define (symbol-property-remove! sym prop)
320 (let ((pair (assoc prop (symbol-pref sym))))
322 (symbol-pset! sym (delq! pair (symbol-pref sym))))))
329 (define (array-shape a)
330 (map (lambda (ind) (if (number? ind) (list 0 (+ -1 ind)) ind))
331 (array-dimensions a)))
338 (define (kw-arg-ref args kw)
339 (let ((rem (member kw args)))
340 (and rem (pair? (cdr rem)) (cadr rem))))
347 (define (struct-layout s)
348 (struct-ref (struct-vtable s) vtable-index-layout))
355 ;; Printing records: by default, records are printed as
357 ;; #<type-name field1: val1 field2: val2 ...>
359 ;; You can change that by giving a custom printing function to
360 ;; MAKE-RECORD-TYPE (after the list of field symbols). This function
361 ;; will be called like
363 ;; (<printer> object port)
365 ;; It should print OBJECT to PORT.
367 (define (inherit-print-state old-port new-port)
368 (if (get-print-state old-port)
369 (port-with-print-state new-port (get-print-state old-port))
372 ;; 0: type-name, 1: fields
373 (define record-type-vtable
374 (make-vtable-vtable "prpr" 0
376 (cond ((eq? s record-type-vtable)
377 (display "#<record-type-vtable>" p))
379 (display "#<record-type " p)
380 (display (record-type-name s) p)
383 (define (record-type? obj)
384 (and (struct? obj) (eq? record-type-vtable (struct-vtable obj))))
386 (define (make-record-type type-name fields . opt)
387 (let ((printer-fn (and (pair? opt) (car opt))))
388 (let ((struct (make-struct record-type-vtable 0
391 (map (lambda (f) "pw") fields)))
395 (display type-name p)
396 (let loop ((fields fields)
399 ((not (null? fields))
401 (display (car fields) p)
403 (display (struct-ref s off) p)
404 (loop (cdr fields) (+ 1 off)))))
407 (copy-tree fields))))
408 ;; Temporary solution: Associate a name to the record type descriptor
409 ;; so that the object system can create a wrapper class for it.
410 (set-struct-vtable-name! struct (if (symbol? type-name)
412 (string->symbol type-name)))
415 (define (record-type-name obj)
416 (if (record-type? obj)
417 (struct-ref obj vtable-offset-user)
418 (error 'not-a-record-type obj)))
420 (define (record-type-fields obj)
421 (if (record-type? obj)
422 (struct-ref obj (+ 1 vtable-offset-user))
423 (error 'not-a-record-type obj)))
425 (define (record-constructor rtd . opt)
426 (let ((field-names (if (pair? opt) (car opt) (record-type-fields rtd))))
428 `(lambda ,field-names
429 (make-struct ',rtd 0 ,@(map (lambda (f)
430 (if (memq f field-names)
433 (record-type-fields rtd)))))))
435 (define (record-predicate rtd)
436 (lambda (obj) (and (struct? obj) (eq? rtd (struct-vtable obj)))))
438 (define (%record-type-error rtd obj) ;; private helper
439 (or (eq? rtd (record-type-descriptor obj))
440 (scm-error 'wrong-type-arg "%record-type-check"
441 "Wrong type record (want `~S'): ~S"
442 (list (record-type-name rtd) obj)
445 (define (record-accessor rtd field-name)
446 (let ((pos (list-index (record-type-fields rtd) field-name)))
448 (error 'no-such-field field-name))
450 (if (eq? (struct-vtable obj) rtd)
452 (%record-type-error rtd obj)))))
454 (define (record-modifier rtd field-name)
455 (let ((pos (list-index (record-type-fields rtd) field-name)))
457 (error 'no-such-field field-name))
459 (if (eq? (struct-vtable obj) rtd)
460 (struct-set! obj pos val)
461 (%record-type-error rtd obj)))))
463 (define (record? obj)
464 (and (struct? obj) (record-type? (struct-vtable obj))))
466 (define (record-type-descriptor obj)
469 (error 'not-a-record obj)))
478 (define (->bool x) (not (not x)))
485 (define (symbol-append . args)
486 (string->symbol (apply string-append (map symbol->string args))))
488 (define (list->symbol . args)
489 (string->symbol (apply list->string args)))
491 (define (symbol . args)
492 (string->symbol (apply string args)))
499 (define (list-index l k)
505 (loop (+ n 1) (cdr l))))))
509 (if (provided? 'posix)
510 (primitive-load-path "ice-9/posix"))
512 (if (provided? 'socket)
513 (primitive-load-path "ice-9/networking"))
515 ;; For reference, Emacs file-exists-p uses stat in this same way.
516 ;; ENHANCE-ME: Catching an exception from stat is a bit wasteful, do this in
517 ;; C where all that's needed is to inspect the return from stat().
519 (if (provided? 'posix)
521 (->bool (false-if-exception (stat str))))
523 (let ((port (catch 'system-error (lambda () (open-file str OPEN_READ))
525 (if port (begin (close-port port) #t)
528 (define file-is-directory?
529 (if (provided? 'posix)
531 (eq? (stat:type (stat str)) 'directory))
533 (let ((port (catch 'system-error
534 (lambda () (open-file (string-append str "/.")
537 (if port (begin (close-port port) #t)
540 (define (has-suffix? str suffix)
541 (string-suffix? suffix str))
543 (define (system-error-errno args)
544 (if (eq? (car args) 'system-error)
545 (car (list-ref args 4))
553 (define (error . args)
556 (scm-error 'misc-error #f "?" #f #f)
557 (let loop ((msg "~A")
559 (if (not (null? rest))
560 (loop (string-append msg " ~S")
562 (scm-error 'misc-error #f msg args #f)))))
564 ;; bad-throw is the hook that is called upon a throw to a an unhandled
565 ;; key (unless the throw has four arguments, in which case
566 ;; it's usually interpreted as an error throw.)
567 ;; If the key has a default handler (a throw-handler-default property),
568 ;; it is applied to the throw.
570 (define (bad-throw key . args)
571 (let ((default (symbol-property key 'throw-handler-default)))
572 (or (and default (apply default key args))
573 (apply error "unhandled-exception:" key args))))
577 (define (tm:sec obj) (vector-ref obj 0))
578 (define (tm:min obj) (vector-ref obj 1))
579 (define (tm:hour obj) (vector-ref obj 2))
580 (define (tm:mday obj) (vector-ref obj 3))
581 (define (tm:mon obj) (vector-ref obj 4))
582 (define (tm:year obj) (vector-ref obj 5))
583 (define (tm:wday obj) (vector-ref obj 6))
584 (define (tm:yday obj) (vector-ref obj 7))
585 (define (tm:isdst obj) (vector-ref obj 8))
586 (define (tm:gmtoff obj) (vector-ref obj 9))
587 (define (tm:zone obj) (vector-ref obj 10))
589 (define (set-tm:sec obj val) (vector-set! obj 0 val))
590 (define (set-tm:min obj val) (vector-set! obj 1 val))
591 (define (set-tm:hour obj val) (vector-set! obj 2 val))
592 (define (set-tm:mday obj val) (vector-set! obj 3 val))
593 (define (set-tm:mon obj val) (vector-set! obj 4 val))
594 (define (set-tm:year obj val) (vector-set! obj 5 val))
595 (define (set-tm:wday obj val) (vector-set! obj 6 val))
596 (define (set-tm:yday obj val) (vector-set! obj 7 val))
597 (define (set-tm:isdst obj val) (vector-set! obj 8 val))
598 (define (set-tm:gmtoff obj val) (vector-set! obj 9 val))
599 (define (set-tm:zone obj val) (vector-set! obj 10 val))
601 (define (tms:clock obj) (vector-ref obj 0))
602 (define (tms:utime obj) (vector-ref obj 1))
603 (define (tms:stime obj) (vector-ref obj 2))
604 (define (tms:cutime obj) (vector-ref obj 3))
605 (define (tms:cstime obj) (vector-ref obj 4))
607 (define file-position ftell)
608 (define (file-set-position port offset . whence)
609 (let ((whence (if (eq? whence '()) SEEK_SET (car whence))))
610 (seek port offset whence)))
612 (define (move->fdes fd/port fd)
613 (cond ((integer? fd/port)
614 (dup->fdes fd/port fd)
618 (primitive-move->fdes fd/port fd)
619 (set-port-revealed! fd/port 1)
622 (define (release-port-handle port)
623 (let ((revealed (port-revealed port)))
625 (set-port-revealed! port (- revealed 1)))))
627 (define (dup->port port/fd mode . maybe-fd)
628 (let ((port (fdopen (apply dup->fdes port/fd maybe-fd)
631 (set-port-revealed! port 1))
634 (define (dup->inport port/fd . maybe-fd)
635 (apply dup->port port/fd "r" maybe-fd))
637 (define (dup->outport port/fd . maybe-fd)
638 (apply dup->port port/fd "w" maybe-fd))
640 (define (dup port/fd . maybe-fd)
641 (if (integer? port/fd)
642 (apply dup->fdes port/fd maybe-fd)
643 (apply dup->port port/fd (port-mode port/fd) maybe-fd)))
645 (define (duplicate-port port modes)
646 (dup->port port modes))
648 (define (fdes->inport fdes)
649 (let loop ((rest-ports (fdes->ports fdes)))
650 (cond ((null? rest-ports)
651 (let ((result (fdopen fdes "r")))
652 (set-port-revealed! result 1)
654 ((input-port? (car rest-ports))
655 (set-port-revealed! (car rest-ports)
656 (+ (port-revealed (car rest-ports)) 1))
659 (loop (cdr rest-ports))))))
661 (define (fdes->outport fdes)
662 (let loop ((rest-ports (fdes->ports fdes)))
663 (cond ((null? rest-ports)
664 (let ((result (fdopen fdes "w")))
665 (set-port-revealed! result 1)
667 ((output-port? (car rest-ports))
668 (set-port-revealed! (car rest-ports)
669 (+ (port-revealed (car rest-ports)) 1))
672 (loop (cdr rest-ports))))))
674 (define (port->fdes port)
675 (set-port-revealed! port (+ (port-revealed port) 1))
678 (define (setenv name value)
680 (putenv (string-append name "=" value))
683 (define (unsetenv name)
684 "Remove the entry for NAME from the environment."
692 ;;; Here for backward compatability
694 (define scheme-file-suffix (lambda () ".scm"))
696 (define (in-vicinity vicinity file)
697 (let ((tail (let ((len (string-length vicinity)))
700 (string-ref vicinity (- len 1))))))
701 (string-append vicinity
710 ;;; {Help for scm_shell}
712 ;;; The argument-processing code used by Guile-based shells generates
713 ;;; Scheme code based on the argument list. This page contains help
714 ;;; functions for the code it generates.
717 (define (command-line) (program-arguments))
719 ;; This is mostly for the internal use of the code generated by
720 ;; scm_compile_shell_switches.
722 (define (turn-on-debugging)
723 (debug-enable 'debug)
724 (debug-enable 'backtrace)
725 (read-enable 'positions))
727 (define (load-user-init)
728 (let* ((home (or (getenv "HOME")
729 (false-if-exception (passwd:dir (getpwuid (getuid))))
730 "/")) ;; fallback for cygwin etc.
731 (init-file (in-vicinity home ".guile")))
732 (if (file-exists? init-file)
733 (primitive-load init-file))))
737 ;;; {The interpreter stack}
740 (defmacro start-stack (tag exp)
741 `(%start-stack ,tag (lambda () ,exp)))
745 ;;; {Loading by paths}
748 ;;; Load a Scheme source file named NAME, searching for it in the
749 ;;; directories listed in %load-path, and applying each of the file
750 ;;; name extensions listed in %load-extensions.
751 (define (load-from-path name)
752 (start-stack 'load-stack
753 (primitive-load-path name)))
755 (define %load-verbosely #f)
756 (define (assert-load-verbosity v) (set! %load-verbosely v))
758 (define (%load-announce file)
760 (with-output-to-port (current-error-port)
768 (set! %load-hook %load-announce)
770 (define (load name . reader)
771 (with-fluid* current-reader (and (pair? reader) (car reader))
773 (start-stack 'load-stack
774 (primitive-load name)))))
778 ;;; {Transcendental Functions}
780 ;;; Derived from "Transcen.scm", Complex trancendental functions for SCM.
781 ;;; Written by Jerry D. Hedden, (C) FSF.
782 ;;; See the file `COPYING' for terms applying to this program.
786 (let ((integer-expt integer-expt))
788 (cond ((and (exact? z2) (integer? z2))
789 (integer-expt z1 z2))
790 ((and (real? z2) (real? z1) (>= z1 0))
793 (exp (* z2 (log z1))))))))
796 (if (real? z) ($sinh z)
797 (let ((x (real-part z)) (y (imag-part z)))
798 (make-rectangular (* ($sinh x) ($cos y))
799 (* ($cosh x) ($sin y))))))
801 (if (real? z) ($cosh z)
802 (let ((x (real-part z)) (y (imag-part z)))
803 (make-rectangular (* ($cosh x) ($cos y))
804 (* ($sinh x) ($sin y))))))
806 (if (real? z) ($tanh z)
807 (let* ((x (* 2 (real-part z)))
808 (y (* 2 (imag-part z)))
809 (w (+ ($cosh x) ($cos y))))
810 (make-rectangular (/ ($sinh x) w) (/ ($sin y) w)))))
813 (if (real? z) ($asinh z)
814 (log (+ z (sqrt (+ (* z z) 1))))))
817 (if (and (real? z) (>= z 1))
819 (log (+ z (sqrt (- (* z z) 1))))))
822 (if (and (real? z) (> z -1) (< z 1))
824 (/ (log (/ (+ 1 z) (- 1 z))) 2)))
827 (if (real? z) ($sin z)
828 (let ((x (real-part z)) (y (imag-part z)))
829 (make-rectangular (* ($sin x) ($cosh y))
830 (* ($cos x) ($sinh y))))))
832 (if (real? z) ($cos z)
833 (let ((x (real-part z)) (y (imag-part z)))
834 (make-rectangular (* ($cos x) ($cosh y))
835 (- (* ($sin x) ($sinh y)))))))
837 (if (real? z) ($tan z)
838 (let* ((x (* 2 (real-part z)))
839 (y (* 2 (imag-part z)))
840 (w (+ ($cos x) ($cosh y))))
841 (make-rectangular (/ ($sin x) w) (/ ($sinh y) w)))))
844 (if (and (real? z) (>= z -1) (<= z 1))
846 (* -i (asinh (* +i z)))))
849 (if (and (real? z) (>= z -1) (<= z 1))
851 (+ (/ (angle -1) 2) (* +i (asinh (* +i z))))))
855 (if (real? z) ($atan z)
856 (/ (log (/ (- +i z) (+ +i z))) +2i))
861 ;;; {Reader Extensions}
863 ;;; Reader code for various "#c" forms.
866 (read-hash-extend #\' (lambda (c port)
869 (define read-eval? (make-fluid))
870 (fluid-set! read-eval? #f)
871 (read-hash-extend #\.
873 (if (fluid-ref read-eval?)
874 (eval (read port) (interaction-environment))
876 "#. read expansion found and read-eval? is #f."))))
880 ;;; {Command Line Options}
883 (define (get-option argv kw-opts kw-args return)
888 ((or (not (eq? #\- (string-ref (car argv) 0)))
889 (eq? (string-length (car argv)) 1))
890 (return 'normal-arg (car argv) (cdr argv)))
892 ((eq? #\- (string-ref (car argv) 1))
893 (let* ((kw-arg-pos (or (string-index (car argv) #\=)
894 (string-length (car argv))))
895 (kw (symbol->keyword (substring (car argv) 2 kw-arg-pos)))
896 (kw-opt? (member kw kw-opts))
897 (kw-arg? (member kw kw-args))
898 (arg (or (and (not (eq? kw-arg-pos (string-length (car argv))))
899 (substring (car argv)
901 (string-length (car argv))))
903 (begin (set! argv (cdr argv)) (car argv))))))
904 (if (or kw-opt? kw-arg?)
905 (return kw arg (cdr argv))
906 (return 'usage-error kw (cdr argv)))))
909 (let* ((char (substring (car argv) 1 2))
910 (kw (symbol->keyword char)))
914 (let* ((rest-car (substring (car argv) 2 (string-length (car argv))))
915 (new-argv (if (= 0 (string-length rest-car))
917 (cons (string-append "-" rest-car) (cdr argv)))))
918 (return kw #f new-argv)))
921 (let* ((rest-car (substring (car argv) 2 (string-length (car argv))))
922 (arg (if (= 0 (string-length rest-car))
925 (new-argv (if (= 0 (string-length rest-car))
928 (return kw arg new-argv)))
930 (else (return 'usage-error kw argv)))))))
932 (define (for-next-option proc argv kw-opts kw-args)
933 (let loop ((argv argv))
934 (get-option argv kw-opts kw-args
935 (lambda (opt opt-arg argv)
936 (and opt (proc opt opt-arg argv loop))))))
938 (define (display-usage-report kw-desc)
941 (or (eq? (car kw) #t)
944 (help (cadr opt-desc))
945 (opts (car opt-desc))
946 (opts-proper (if (string? (car opts)) (cdr opts) opts))
947 (arg-name (if (string? (car opts))
948 (string-append "<" (car opts) ">")
950 (left-part (string-append
951 (with-output-to-string
953 (map (lambda (x) (display (keyword->symbol x)) (display " "))
956 (middle-part (if (and (< (string-length left-part) 30)
957 (< (string-length help) 40))
958 (make-string (- 30 (string-length left-part)) #\ )
961 (display middle-part)
968 (define (transform-usage-lambda cases)
969 (let* ((raw-usage (delq! 'else (map car cases)))
970 (usage-sans-specials (map (lambda (x)
971 (or (and (not (list? x)) x)
972 (and (symbol? (car x)) #t)
973 (and (boolean? (car x)) #t)
976 (usage-desc (delq! #t usage-sans-specials))
977 (kw-desc (map car usage-desc))
978 (kw-opts (apply append (map (lambda (x) (and (not (string? (car x))) x)) kw-desc)))
979 (kw-args (apply append (map (lambda (x) (and (string? (car x)) (cdr x))) kw-desc)))
980 (transmogrified-cases (map (lambda (case)
981 (cons (let ((opts (car case)))
982 (if (or (boolean? opts) (eq? 'else opts))
985 ((symbol? (car opts)) opts)
986 ((boolean? (car opts)) opts)
987 ((string? (caar opts)) (cdar opts))
991 `(let ((%display-usage (lambda () (display-usage-report ',usage-desc))))
993 (let %next-arg ((%argv %argv))
997 (lambda (%opt %arg %new-argv)
999 ,@ transmogrified-cases))))))))
1004 ;;; {Low Level Modules}
1006 ;;; These are the low level data structures for modules.
1008 ;;; Every module object is of the type 'module-type', which is a record
1009 ;;; consisting of the following members:
1011 ;;; - eval-closure: the function that defines for its module the strategy that
1012 ;;; shall be followed when looking up symbols in the module.
1014 ;;; An eval-closure is a function taking two arguments: the symbol to be
1015 ;;; looked up and a boolean value telling whether a binding for the symbol
1016 ;;; should be created if it does not exist yet. If the symbol lookup
1017 ;;; succeeded (either because an existing binding was found or because a new
1018 ;;; binding was created), a variable object representing the binding is
1019 ;;; returned. Otherwise, the value #f is returned. Note that the eval
1020 ;;; closure does not take the module to be searched as an argument: During
1021 ;;; construction of the eval-closure, the eval-closure has to store the
1022 ;;; module it belongs to in its environment. This means, that any
1023 ;;; eval-closure can belong to only one module.
1025 ;;; The eval-closure of a module can be defined arbitrarily. However, three
1026 ;;; special cases of eval-closures are to be distinguished: During startup
1027 ;;; the module system is not yet activated. In this phase, no modules are
1028 ;;; defined and all bindings are automatically stored by the system in the
1029 ;;; pre-modules-obarray. Since no eval-closures exist at this time, the
1030 ;;; functions which require an eval-closure as their argument need to be
1031 ;;; passed the value #f.
1033 ;;; The other two special cases of eval-closures are the
1034 ;;; standard-eval-closure and the standard-interface-eval-closure. Both
1035 ;;; behave equally for the case that no new binding is to be created. The
1036 ;;; difference between the two comes in, when the boolean argument to the
1037 ;;; eval-closure indicates that a new binding shall be created if it is not
1040 ;;; Given that no new binding shall be created, both standard eval-closures
1041 ;;; define the following standard strategy of searching bindings in the
1042 ;;; module: First, the module's obarray is searched for the symbol. Second,
1043 ;;; if no binding for the symbol was found in the module's obarray, the
1044 ;;; module's binder procedure is exececuted. If this procedure did not
1045 ;;; return a binding for the symbol, the modules referenced in the module's
1046 ;;; uses list are recursively searched for a binding of the symbol. If the
1047 ;;; binding can not be found in these modules also, the symbol lookup has
1050 ;;; If a new binding shall be created, the standard-interface-eval-closure
1051 ;;; immediately returns indicating failure. That is, it does not even try
1052 ;;; to look up the symbol. In contrast, the standard-eval-closure would
1053 ;;; first search the obarray, and if no binding was found there, would
1054 ;;; create a new binding in the obarray, therefore not calling the binder
1055 ;;; procedure or searching the modules in the uses list.
1057 ;;; The explanation of the following members obarray, binder and uses
1058 ;;; assumes that the symbol lookup follows the strategy that is defined in
1059 ;;; the standard-eval-closure and the standard-interface-eval-closure.
1061 ;;; - obarray: a hash table that maps symbols to variable objects. In this
1062 ;;; hash table, the definitions are found that are local to the module (that
1063 ;;; is, not imported from other modules). When looking up bindings in the
1064 ;;; module, this hash table is searched first.
1066 ;;; - binder: either #f or a function taking a module and a symbol argument.
1067 ;;; If it is a function it is called after the obarray has been
1068 ;;; unsuccessfully searched for a binding. It then can provide bindings
1069 ;;; that would otherwise not be found locally in the module.
1071 ;;; - uses: a list of modules from which non-local bindings can be inherited.
1072 ;;; These modules are the third place queried for bindings after the obarray
1073 ;;; has been unsuccessfully searched and the binder function did not deliver
1074 ;;; a result either.
1076 ;;; - transformer: either #f or a function taking a scheme expression as
1077 ;;; delivered by read. If it is a function, it will be called to perform
1078 ;;; syntax transformations (e. g. makro expansion) on the given scheme
1079 ;;; expression. The output of the transformer function will then be passed
1080 ;;; to Guile's internal memoizer. This means that the output must be valid
1081 ;;; scheme code. The only exception is, that the output may make use of the
1082 ;;; syntax extensions provided to identify the modules that a binding
1085 ;;; - name: the name of the module. This is used for all kinds of printing
1086 ;;; outputs. In certain places the module name also serves as a way of
1087 ;;; identification. When adding a module to the uses list of another
1088 ;;; module, it is made sure that the new uses list will not contain two
1089 ;;; modules of the same name.
1091 ;;; - kind: classification of the kind of module. The value is (currently?)
1092 ;;; only used for printing. It has no influence on how a module is treated.
1093 ;;; Currently the following values are used when setting the module kind:
1094 ;;; 'module, 'directory, 'interface, 'custom-interface. If no explicit kind
1095 ;;; is set, it defaults to 'module.
1097 ;;; - duplicates-handlers: a list of procedures that get called to make a
1098 ;;; choice between two duplicate bindings when name clashes occur. See the
1099 ;;; `duplicate-handlers' global variable below.
1101 ;;; - observers: a list of procedures that get called when the module is
1104 ;;; - weak-observers: a weak-key hash table of procedures that get called
1105 ;;; when the module is modified. See `module-observe-weak' for details.
1107 ;;; In addition, the module may (must?) contain a binding for
1108 ;;; `%module-public-interface'. This variable should be bound to a module
1109 ;;; representing the exported interface of a module. See the
1110 ;;; `module-public-interface' and `module-export!' procedures.
1112 ;;; !!! warning: The interface to lazy binder procedures is going
1113 ;;; to be changed in an incompatible way to permit all the basic
1114 ;;; module ops to be virtualized.
1116 ;;; (make-module size use-list lazy-binding-proc) => module
1117 ;;; module-{obarray,uses,binder}[|-set!]
1118 ;;; (module? obj) => [#t|#f]
1119 ;;; (module-locally-bound? module symbol) => [#t|#f]
1120 ;;; (module-bound? module symbol) => [#t|#f]
1121 ;;; (module-symbol-locally-interned? module symbol) => [#t|#f]
1122 ;;; (module-symbol-interned? module symbol) => [#t|#f]
1123 ;;; (module-local-variable module symbol) => [#<variable ...> | #f]
1124 ;;; (module-variable module symbol) => [#<variable ...> | #f]
1125 ;;; (module-symbol-binding module symbol opt-value)
1126 ;;; => [ <obj> | opt-value | an error occurs ]
1127 ;;; (module-make-local-var! module symbol) => #<variable...>
1128 ;;; (module-add! module symbol var) => unspecified
1129 ;;; (module-remove! module symbol) => unspecified
1130 ;;; (module-for-each proc module) => unspecified
1131 ;;; (make-scm-module) => module ; a lazy copy of the symhash module
1132 ;;; (set-current-module module) => unspecified
1133 ;;; (current-module) => #<module...>
1139 ;;; {Printing Modules}
1142 ;; This is how modules are printed. You can re-define it.
1143 ;; (Redefining is actually more complicated than simply redefining
1144 ;; %print-module because that would only change the binding and not
1145 ;; the value stored in the vtable that determines how record are
1148 (define (%print-module mod port) ; unused args: depth length style table)
1150 (display (or (module-kind mod) "module") port)
1151 (let ((name (module-name mod)))
1155 (display name port))))
1157 (display (number->string (object-address mod) 16) port)
1162 ;; A module is characterized by an obarray in which local symbols
1163 ;; are interned, a list of modules, "uses", from which non-local
1164 ;; bindings can be inherited, and an optional lazy-binder which
1165 ;; is a (CLOSURE module symbol) which, as a last resort, can provide
1166 ;; bindings that would otherwise not be found locally in the module.
1168 ;; NOTE: If you change anything here, you also need to change
1169 ;; libguile/modules.h.
1172 (make-record-type 'module
1173 '(obarray uses binder eval-closure transformer name kind
1174 duplicates-handlers import-obarray
1175 observers weak-observers)
1178 ;; make-module &opt size uses binder
1180 ;; Create a new module, perhaps with a particular size of obarray,
1181 ;; initial uses list, or binding procedure.
1186 (define (parse-arg index default)
1187 (if (> (length args) index)
1188 (list-ref args index)
1191 (define %default-import-size
1192 ;; Typical number of imported bindings actually used by a module.
1195 (if (> (length args) 3)
1196 (error "Too many args to make-module." args))
1198 (let ((size (parse-arg 0 31))
1199 (uses (parse-arg 1 '()))
1200 (binder (parse-arg 2 #f)))
1202 (if (not (integer? size))
1203 (error "Illegal size to make-module." size))
1204 (if (not (and (list? uses)
1205 (and-map module? uses)))
1206 (error "Incorrect use list." uses))
1207 (if (and binder (not (procedure? binder)))
1209 "Lazy-binder expected to be a procedure or #f." binder))
1211 (let ((module (module-constructor (make-hash-table size)
1212 uses binder #f %pre-modules-transformer
1214 (make-hash-table %default-import-size)
1216 (make-weak-key-hash-table 31))))
1218 ;; We can't pass this as an argument to module-constructor,
1219 ;; because we need it to close over a pointer to the module
1221 (set-module-eval-closure! module (standard-eval-closure module))
1225 (define module-constructor (record-constructor module-type))
1226 (define module-obarray (record-accessor module-type 'obarray))
1227 (define set-module-obarray! (record-modifier module-type 'obarray))
1228 (define module-uses (record-accessor module-type 'uses))
1229 (define set-module-uses! (record-modifier module-type 'uses))
1230 (define module-binder (record-accessor module-type 'binder))
1231 (define set-module-binder! (record-modifier module-type 'binder))
1233 ;; NOTE: This binding is used in libguile/modules.c.
1234 (define module-eval-closure (record-accessor module-type 'eval-closure))
1236 (define module-transformer (record-accessor module-type 'transformer))
1237 (define set-module-transformer! (record-modifier module-type 'transformer))
1238 ;; (define module-name (record-accessor module-type 'name)) wait until mods are booted
1239 (define set-module-name! (record-modifier module-type 'name))
1240 (define module-kind (record-accessor module-type 'kind))
1241 (define set-module-kind! (record-modifier module-type 'kind))
1242 (define module-duplicates-handlers
1243 (record-accessor module-type 'duplicates-handlers))
1244 (define set-module-duplicates-handlers!
1245 (record-modifier module-type 'duplicates-handlers))
1246 (define module-observers (record-accessor module-type 'observers))
1247 (define set-module-observers! (record-modifier module-type 'observers))
1248 (define module-weak-observers (record-accessor module-type 'weak-observers))
1249 (define module? (record-predicate module-type))
1251 (define module-import-obarray (record-accessor module-type 'import-obarray))
1253 (define set-module-eval-closure!
1254 (let ((setter (record-modifier module-type 'eval-closure)))
1255 (lambda (module closure)
1256 (setter module closure)
1257 ;; Make it possible to lookup the module from the environment.
1258 ;; This implementation is correct since an eval closure can belong
1259 ;; to maximally one module.
1260 (set-procedure-property! closure 'module module))))
1264 ;;; {Observer protocol}
1267 (define (module-observe module proc)
1268 (set-module-observers! module (cons proc (module-observers module)))
1271 (define (module-observe-weak module observer-id . proc)
1272 ;; Register PROC as an observer of MODULE under name OBSERVER-ID (which can
1273 ;; be any Scheme object). PROC is invoked and passed MODULE any time
1274 ;; MODULE is modified. PROC gets unregistered when OBSERVER-ID gets GC'd
1275 ;; (thus, it is never unregistered if OBSERVER-ID is an immediate value,
1278 ;; The two-argument version is kept for backward compatibility: when called
1279 ;; with two arguments, the observer gets unregistered when closure PROC
1280 ;; gets GC'd (making it impossible to use an anonymous lambda for PROC).
1282 (let ((proc (if (null? proc) observer-id (car proc))))
1283 (hashq-set! (module-weak-observers module) observer-id proc)))
1285 (define (module-unobserve token)
1286 (let ((module (car token))
1289 (hash-remove! (module-weak-observers module) id)
1290 (set-module-observers! module (delq1! id (module-observers module)))))
1293 (define module-defer-observers #f)
1294 (define module-defer-observers-mutex (make-mutex 'recursive))
1295 (define module-defer-observers-table (make-hash-table))
1297 (define (module-modified m)
1298 (if module-defer-observers
1299 (hash-set! module-defer-observers-table m #t)
1300 (module-call-observers m)))
1302 ;;; This function can be used to delay calls to observers so that they
1303 ;;; can be called once only in the face of massive updating of modules.
1305 (define (call-with-deferred-observers thunk)
1308 (lock-mutex module-defer-observers-mutex)
1309 (set! module-defer-observers #t))
1312 (set! module-defer-observers #f)
1313 (hash-for-each (lambda (m dummy)
1314 (module-call-observers m))
1315 module-defer-observers-table)
1316 (hash-clear! module-defer-observers-table)
1317 (unlock-mutex module-defer-observers-mutex))))
1319 (define (module-call-observers m)
1320 (for-each (lambda (proc) (proc m)) (module-observers m))
1322 ;; We assume that weak observers don't (un)register themselves as they are
1323 ;; called since this would preclude proper iteration over the hash table
1325 (hash-for-each (lambda (id proc) (proc m)) (module-weak-observers m)))
1329 ;;; {Module Searching in General}
1331 ;;; We sometimes want to look for properties of a symbol
1332 ;;; just within the obarray of one module. If the property
1333 ;;; holds, then it is said to hold ``locally'' as in, ``The symbol
1334 ;;; DISPLAY is locally rebound in the module `safe-guile'.''
1337 ;;; Other times, we want to test for a symbol property in the obarray
1338 ;;; of M and, if it is not found there, try each of the modules in the
1339 ;;; uses list of M. This is the normal way of testing for some
1340 ;;; property, so we state these properties without qualification as
1341 ;;; in: ``The symbol 'fnord is interned in module M because it is
1342 ;;; interned locally in module M2 which is a member of the uses list
1346 ;; module-search fn m
1348 ;; return the first non-#f result of FN applied to M and then to
1349 ;; the modules in the uses of m, and so on recursively. If all applications
1350 ;; return #f, then so does this function.
1352 (define (module-search fn m v)
1355 (or (module-search fn (car pos) v)
1358 (loop (module-uses m))))
1361 ;;; {Is a symbol bound in a module?}
1363 ;;; Symbol S in Module M is bound if S is interned in M and if the binding
1364 ;;; of S in M has been set to some well-defined value.
1367 ;; module-locally-bound? module symbol
1369 ;; Is a symbol bound (interned and defined) locally in a given module?
1371 (define (module-locally-bound? m v)
1372 (let ((var (module-local-variable m v)))
1374 (variable-bound? var))))
1376 ;; module-bound? module symbol
1378 ;; Is a symbol bound (interned and defined) anywhere in a given module
1381 (define (module-bound? m v)
1382 (let ((var (module-variable m v)))
1384 (variable-bound? var))))
1386 ;;; {Is a symbol interned in a module?}
1388 ;;; Symbol S in Module M is interned if S occurs in
1389 ;;; of S in M has been set to some well-defined value.
1391 ;;; It is possible to intern a symbol in a module without providing
1392 ;;; an initial binding for the corresponding variable. This is done
1394 ;;; (module-add! module symbol (make-undefined-variable))
1396 ;;; In that case, the symbol is interned in the module, but not
1397 ;;; bound there. The unbound symbol shadows any binding for that
1398 ;;; symbol that might otherwise be inherited from a member of the uses list.
1401 (define (module-obarray-get-handle ob key)
1402 ((if (symbol? key) hashq-get-handle hash-get-handle) ob key))
1404 (define (module-obarray-ref ob key)
1405 ((if (symbol? key) hashq-ref hash-ref) ob key))
1407 (define (module-obarray-set! ob key val)
1408 ((if (symbol? key) hashq-set! hash-set!) ob key val))
1410 (define (module-obarray-remove! ob key)
1411 ((if (symbol? key) hashq-remove! hash-remove!) ob key))
1413 ;; module-symbol-locally-interned? module symbol
1415 ;; is a symbol interned (not neccessarily defined) locally in a given module
1416 ;; or its uses? Interned symbols shadow inherited bindings even if
1417 ;; they are not themselves bound to a defined value.
1419 (define (module-symbol-locally-interned? m v)
1420 (not (not (module-obarray-get-handle (module-obarray m) v))))
1422 ;; module-symbol-interned? module symbol
1424 ;; is a symbol interned (not neccessarily defined) anywhere in a given module
1425 ;; or its uses? Interned symbols shadow inherited bindings even if
1426 ;; they are not themselves bound to a defined value.
1428 (define (module-symbol-interned? m v)
1429 (module-search module-symbol-locally-interned? m v))
1432 ;;; {Mapping modules x symbols --> variables}
1435 ;; module-local-variable module symbol
1436 ;; return the local variable associated with a MODULE and SYMBOL.
1438 ;;; This function is very important. It is the only function that can
1439 ;;; return a variable from a module other than the mutators that store
1440 ;;; new variables in modules. Therefore, this function is the location
1441 ;;; of the "lazy binder" hack.
1443 ;;; If symbol is defined in MODULE, and if the definition binds symbol
1444 ;;; to a variable, return that variable object.
1446 ;;; If the symbols is not found at first, but the module has a lazy binder,
1447 ;;; then try the binder.
1449 ;;; If the symbol is not found at all, return #f.
1451 ;;; (This is now written in C, see `modules.c'.)
1454 ;;; {Mapping modules x symbols --> bindings}
1456 ;;; These are similar to the mapping to variables, except that the
1457 ;;; variable is dereferenced.
1460 ;; module-symbol-binding module symbol opt-value
1462 ;; return the binding of a variable specified by name within
1463 ;; a given module, signalling an error if the variable is unbound.
1464 ;; If the OPT-VALUE is passed, then instead of signalling an error,
1465 ;; return OPT-VALUE.
1467 (define (module-symbol-local-binding m v . opt-val)
1468 (let ((var (module-local-variable m v)))
1469 (if (and var (variable-bound? var))
1471 (if (not (null? opt-val))
1473 (error "Locally unbound variable." v)))))
1475 ;; module-symbol-binding module symbol opt-value
1477 ;; return the binding of a variable specified by name within
1478 ;; a given module, signalling an error if the variable is unbound.
1479 ;; If the OPT-VALUE is passed, then instead of signalling an error,
1480 ;; return OPT-VALUE.
1482 (define (module-symbol-binding m v . opt-val)
1483 (let ((var (module-variable m v)))
1484 (if (and var (variable-bound? var))
1486 (if (not (null? opt-val))
1488 (error "Unbound variable." v)))))
1493 ;;; {Adding Variables to Modules}
1496 ;; module-make-local-var! module symbol
1498 ;; ensure a variable for V in the local namespace of M.
1499 ;; If no variable was already there, then create a new and uninitialzied
1502 ;; This function is used in modules.c.
1504 (define (module-make-local-var! m v)
1505 (or (let ((b (module-obarray-ref (module-obarray m) v)))
1508 ;; Mark as modified since this function is called when
1509 ;; the standard eval closure defines a binding
1513 ;; Create a new local variable.
1514 (let ((local-var (make-undefined-variable)))
1515 (module-add! m v local-var)
1518 ;; module-ensure-local-variable! module symbol
1520 ;; Ensure that there is a local variable in MODULE for SYMBOL. If
1521 ;; there is no binding for SYMBOL, create a new uninitialized
1522 ;; variable. Return the local variable.
1524 (define (module-ensure-local-variable! module symbol)
1525 (or (module-local-variable module symbol)
1526 (let ((var (make-undefined-variable)))
1527 (module-add! module symbol var)
1530 ;; module-add! module symbol var
1532 ;; ensure a particular variable for V in the local namespace of M.
1534 (define (module-add! m v var)
1535 (if (not (variable? var))
1536 (error "Bad variable to module-add!" var))
1537 (module-obarray-set! (module-obarray m) v var)
1538 (module-modified m))
1542 ;; make sure that a symbol is undefined in the local namespace of M.
1544 (define (module-remove! m v)
1545 (module-obarray-remove! (module-obarray m) v)
1546 (module-modified m))
1548 (define (module-clear! m)
1549 (hash-clear! (module-obarray m))
1550 (module-modified m))
1552 ;; MODULE-FOR-EACH -- exported
1554 ;; Call PROC on each symbol in MODULE, with arguments of (SYMBOL VARIABLE).
1556 (define (module-for-each proc module)
1557 (hash-for-each proc (module-obarray module)))
1559 (define (module-map proc module)
1560 (hash-map->list proc (module-obarray module)))
1564 ;;; {Low Level Bootstrapping}
1569 ;; A root module uses the pre-modules-obarray as its obarray. This
1570 ;; special obarray accumulates all bindings that have been established
1571 ;; before the module system is fully booted.
1573 ;; (The obarray continues to be used by code that has been closed over
1574 ;; before the module system has been booted.)
1576 (define (make-root-module)
1577 (let ((m (make-module 0)))
1578 (set-module-obarray! m (%get-pre-modules-obarray))
1583 ;; The root interface is a module that uses the same obarray as the
1584 ;; root module. It does not allow new definitions, tho.
1586 (define (make-scm-module)
1587 (let ((m (make-module 0)))
1588 (set-module-obarray! m (%get-pre-modules-obarray))
1589 (set-module-eval-closure! m (standard-interface-eval-closure m))
1595 ;;; {Module-based Loading}
1598 (define (save-module-excursion thunk)
1599 (let ((inner-module (current-module))
1601 (dynamic-wind (lambda ()
1602 (set! outer-module (current-module))
1603 (set-current-module inner-module)
1604 (set! inner-module #f))
1607 (set! inner-module (current-module))
1608 (set-current-module outer-module)
1609 (set! outer-module #f)))))
1611 (define basic-load load)
1613 (define (load-module filename . reader)
1614 (save-module-excursion
1616 (let ((oldname (and (current-load-port)
1617 (port-filename (current-load-port)))))
1620 (> (string-length filename) 0)
1621 (not (char=? (string-ref filename 0) #\/))
1622 (not (string=? (dirname oldname) ".")))
1623 (string-append (dirname oldname) "/" filename)
1630 ;;; {MODULE-REF -- exported}
1633 ;; Returns the value of a variable called NAME in MODULE or any of its
1634 ;; used modules. If there is no such variable, then if the optional third
1635 ;; argument DEFAULT is present, it is returned; otherwise an error is signaled.
1637 (define (module-ref module name . rest)
1638 (let ((variable (module-variable module name)))
1639 (if (and variable (variable-bound? variable))
1640 (variable-ref variable)
1642 (error "No variable named" name 'in module)
1643 (car rest) ; default value
1646 ;; MODULE-SET! -- exported
1648 ;; Sets the variable called NAME in MODULE (or in a module that MODULE uses)
1649 ;; to VALUE; if there is no such variable, an error is signaled.
1651 (define (module-set! module name value)
1652 (let ((variable (module-variable module name)))
1654 (variable-set! variable value)
1655 (error "No variable named" name 'in module))))
1657 ;; MODULE-DEFINE! -- exported
1659 ;; Sets the variable called NAME in MODULE to VALUE; if there is no such
1660 ;; variable, it is added first.
1662 (define (module-define! module name value)
1663 (let ((variable (module-local-variable module name)))
1666 (variable-set! variable value)
1667 (module-modified module))
1668 (let ((variable (make-variable value)))
1669 (module-add! module name variable)))))
1671 ;; MODULE-DEFINED? -- exported
1673 ;; Return #t iff NAME is defined in MODULE (or in a module that MODULE
1676 (define (module-defined? module name)
1677 (let ((variable (module-variable module name)))
1678 (and variable (variable-bound? variable))))
1680 ;; MODULE-USE! module interface
1682 ;; Add INTERFACE to the list of interfaces used by MODULE.
1684 (define (module-use! module interface)
1685 (if (not (or (eq? module interface)
1686 (memq interface (module-uses module))))
1688 ;; Newly used modules must be appended rather than consed, so that
1689 ;; `module-variable' traverses the use list starting from the first
1691 (set-module-uses! module
1692 (append (filter (lambda (m)
1694 (equal? (module-name m)
1695 (module-name interface))))
1696 (module-uses module))
1699 (module-modified module))))
1701 ;; MODULE-USE-INTERFACES! module interfaces
1703 ;; Same as MODULE-USE! but add multiple interfaces and check for duplicates
1705 (define (module-use-interfaces! module interfaces)
1706 (set-module-uses! module
1707 (append (module-uses module) interfaces))
1708 (module-modified module))
1712 ;;; {Recursive Namespaces}
1714 ;;; A hierarchical namespace emerges if we consider some module to be
1715 ;;; root, and variables bound to modules as nested namespaces.
1717 ;;; The routines in this file manage variable names in hierarchical namespace.
1718 ;;; Each variable name is a list of elements, looked up in successively nested
1721 ;;; (nested-ref some-root-module '(foo bar baz))
1722 ;;; => <value of a variable named baz in the module bound to bar in
1723 ;;; the module bound to foo in some-root-module>
1728 ;;; ;; a-root is a module
1729 ;;; ;; name is a list of symbols
1731 ;;; nested-ref a-root name
1732 ;;; nested-set! a-root name val
1733 ;;; nested-define! a-root name val
1734 ;;; nested-remove! a-root name
1737 ;;; (current-module) is a natural choice for a-root so for convenience there are
1740 ;;; local-ref name == nested-ref (current-module) name
1741 ;;; local-set! name val == nested-set! (current-module) name val
1742 ;;; local-define! name val == nested-define! (current-module) name val
1743 ;;; local-remove! name == nested-remove! (current-module) name
1747 (define (nested-ref root names)
1748 (let loop ((cur root)
1752 ((not (module? cur)) #f)
1753 (else (loop (module-ref cur (car elts) #f) (cdr elts))))))
1755 (define (nested-set! root names val)
1756 (let loop ((cur root)
1758 (if (null? (cdr elts))
1759 (module-set! cur (car elts) val)
1760 (loop (module-ref cur (car elts)) (cdr elts)))))
1762 (define (nested-define! root names val)
1763 (let loop ((cur root)
1765 (if (null? (cdr elts))
1766 (module-define! cur (car elts) val)
1767 (loop (module-ref cur (car elts)) (cdr elts)))))
1769 (define (nested-remove! root names)
1770 (let loop ((cur root)
1772 (if (null? (cdr elts))
1773 (module-remove! cur (car elts))
1774 (loop (module-ref cur (car elts)) (cdr elts)))))
1776 (define (local-ref names) (nested-ref (current-module) names))
1777 (define (local-set! names val) (nested-set! (current-module) names val))
1778 (define (local-define names val) (nested-define! (current-module) names val))
1779 (define (local-remove names) (nested-remove! (current-module) names))
1784 ;;; {The (%app) module}
1786 ;;; The root of conventionally named objects not directly in the top level.
1789 ;;; (%app modules guile)
1791 ;;; The directory of all modules and the standard root module.
1794 ;; module-public-interface is defined in C.
1795 (define (set-module-public-interface! m i)
1796 (module-define! m '%module-public-interface i))
1797 (define (set-system-module! m s)
1798 (set-procedure-property! (module-eval-closure m) 'system-module s))
1799 (define the-root-module (make-root-module))
1800 (define the-scm-module (make-scm-module))
1801 (set-module-public-interface! the-root-module the-scm-module)
1802 (set-module-name! the-root-module '(guile))
1803 (set-module-name! the-scm-module '(guile))
1804 (set-module-kind! the-scm-module 'interface)
1805 (set-system-module! the-root-module #t)
1806 (set-system-module! the-scm-module #t)
1808 ;; NOTE: This binding is used in libguile/modules.c.
1810 (define (make-modules-in module name)
1814 (let* ((var (module-local-variable module (car name)))
1815 (val (and var (variable-bound? var) (variable-ref var))))
1818 (let ((m (make-module 31)))
1819 (set-module-kind! m 'directory)
1820 (set-module-name! m (append (or (module-name module) '())
1822 (module-define! module (car name) m)
1826 (define (beautify-user-module! module)
1827 (let ((interface (module-public-interface module)))
1828 (if (or (not interface)
1829 (eq? interface module))
1830 (let ((interface (make-module 31)))
1831 (set-module-name! interface (module-name module))
1832 (set-module-kind! interface 'interface)
1833 (set-module-public-interface! module interface))))
1834 (if (and (not (memq the-scm-module (module-uses module)))
1835 (not (eq? module the-root-module)))
1836 ;; Import the default set of bindings (from the SCM module) in MODULE.
1837 (module-use! module the-scm-module)))
1839 ;; NOTE: This binding is used in libguile/modules.c.
1841 (define resolve-module
1842 (let ((the-root-module the-root-module))
1843 (lambda (name . maybe-autoload)
1844 (if (equal? name '(guile))
1846 (let ((full-name (append '(%app modules) name)))
1847 (let ((already (nested-ref the-root-module full-name))
1848 (autoload (or (null? maybe-autoload) (car maybe-autoload))))
1850 ((and already (module? already)
1851 (or (not autoload) (module-public-interface already)))
1852 ;; A hit, a palpable hit.
1855 ;; Try to autoload the module, and recurse.
1856 (try-load-module name)
1857 (resolve-module name #f))
1859 ;; A module is not bound (but maybe something else is),
1860 ;; we're not autoloading -- here's the weird semantics,
1861 ;; we create an empty module.
1862 (make-modules-in the-root-module full-name)))))))))
1864 ;; Cheat. These bindings are needed by modules.c, but we don't want
1865 ;; to move their real definition here because that would be unnatural.
1867 (define try-module-autoload #f)
1868 (define process-define-module #f)
1869 (define process-use-modules #f)
1870 (define module-export! #f)
1871 (define default-duplicate-binding-procedures #f)
1873 (define %app (make-module 31))
1874 (define app %app) ;; for backwards compatability
1876 (local-define '(%app modules) (make-module 31))
1877 (local-define '(%app modules guile) the-root-module)
1879 ;; This boots the module system. All bindings needed by modules.c
1880 ;; must have been defined by now.
1882 (set-current-module the-root-module)
1883 ;; definition deferred for syncase's benefit
1884 (define module-name (record-accessor module-type 'name))
1886 ;; (define-special-value '(%app modules new-ws) (lambda () (make-scm-module)))
1888 (define (try-load-module name)
1889 (try-module-autoload name))
1891 (define (purify-module! module)
1892 "Removes bindings in MODULE which are inherited from the (guile) module."
1893 (let ((use-list (module-uses module)))
1894 (if (and (pair? use-list)
1895 (eq? (car (last-pair use-list)) the-scm-module))
1896 (set-module-uses! module (reverse (cdr (reverse use-list)))))))
1898 ;; Return a module that is an interface to the module designated by
1901 ;; `resolve-interface' takes four keyword arguments:
1903 ;; #:select SELECTION
1905 ;; SELECTION is a list of binding-specs to be imported; A binding-spec
1906 ;; is either a symbol or a pair of symbols (ORIG . SEEN), where ORIG
1907 ;; is the name in the used module and SEEN is the name in the using
1908 ;; module. Note that SEEN is also passed through RENAMER, below. The
1909 ;; default is to select all bindings. If you specify no selection but
1910 ;; a renamer, only the bindings that already exist in the used module
1911 ;; are made available in the interface. Bindings that are added later
1912 ;; are not picked up.
1916 ;; BINDINGS is a list of bindings which should not be imported.
1920 ;; PREFIX is a symbol that will be appended to each exported name.
1921 ;; The default is to not perform any renaming.
1923 ;; #:renamer RENAMER
1925 ;; RENAMER is a procedure that takes a symbol and returns its new
1926 ;; name. The default is not perform any renaming.
1928 ;; Signal "no code for module" error if module name is not resolvable
1929 ;; or its public interface is not available. Signal "no binding"
1930 ;; error if selected binding does not exist in the used module.
1932 (define (resolve-interface name . args)
1934 (define (get-keyword-arg args kw def)
1935 (cond ((memq kw args)
1937 (if (null? (cdr kw-arg))
1938 (error "keyword without value: " kw))
1943 (let* ((select (get-keyword-arg args #:select #f))
1944 (hide (get-keyword-arg args #:hide '()))
1945 (renamer (or (get-keyword-arg args #:renamer #f)
1946 (let ((prefix (get-keyword-arg args #:prefix #f)))
1947 (and prefix (symbol-prefix-proc prefix)))
1949 (module (resolve-module name))
1950 (public-i (and module (module-public-interface module))))
1951 (and (or (not module) (not public-i))
1952 (error "no code for module" name))
1953 (if (and (not select) (null? hide) (eq? renamer identity))
1955 (let ((selection (or select (module-map (lambda (sym var) sym)
1957 (custom-i (make-module 31)))
1958 (set-module-kind! custom-i 'custom-interface)
1959 (set-module-name! custom-i name)
1960 ;; XXX - should use a lazy binder so that changes to the
1961 ;; used module are picked up automatically.
1962 (for-each (lambda (bspec)
1963 (let* ((direct? (symbol? bspec))
1964 (orig (if direct? bspec (car bspec)))
1965 (seen (if direct? bspec (cdr bspec)))
1966 (var (or (module-local-variable public-i orig)
1967 (module-local-variable module orig)
1969 ;; fixme: format manually for now
1971 #f "no binding `~A' in module ~A"
1973 (if (memq orig hide)
1974 (set! hide (delq! orig hide))
1975 (module-add! custom-i
1979 ;; Check that we are not hiding bindings which don't exist
1980 (for-each (lambda (binding)
1981 (if (not (module-local-variable public-i binding))
1984 #f "no binding `~A' to hide in module ~A"
1989 (define (symbol-prefix-proc prefix)
1991 (symbol-append prefix symbol)))
1993 ;; This function is called from "modules.c". If you change it, be
1994 ;; sure to update "modules.c" as well.
1996 (define (process-define-module args)
1997 (let* ((module-id (car args))
1998 (module (resolve-module module-id #f))
2000 (unrecognized (lambda (arg)
2001 (error "unrecognized define-module argument" arg))))
2002 (beautify-user-module! module)
2003 (let loop ((kws kws)
2004 (reversed-interfaces '())
2011 (call-with-deferred-observers
2013 (module-use-interfaces! module (reverse reversed-interfaces))
2014 (module-export! module exports)
2015 (module-replace! module replacements)
2016 (module-re-export! module re-exports)
2017 (if (not (null? autoloads))
2018 (apply module-autoload! module autoloads))))
2020 ((#:use-module #:use-syntax)
2021 (or (pair? (cdr kws))
2024 ((equal? (caadr kws) '(ice-9 syncase))
2025 (issue-deprecation-warning
2026 "(ice-9 syncase) is deprecated. Support for syntax-case is now in Guile core.")
2034 (let* ((interface-args (cadr kws))
2035 (interface (apply resolve-interface interface-args)))
2036 (and (eq? (car kws) #:use-syntax)
2037 (or (symbol? (caar interface-args))
2038 (error "invalid module name for use-syntax"
2039 (car interface-args)))
2040 (set-module-transformer!
2042 (module-ref interface
2043 (car (last-pair (car interface-args)))
2046 (cons interface reversed-interfaces)
2052 (or (and (pair? (cdr kws)) (pair? (cddr kws)))
2059 (let ((name (cadr kws))
2060 (bindings (caddr kws)))
2061 (cons* name bindings autoloads))))
2063 (set-system-module! module #t)
2064 (loop (cdr kws) reversed-interfaces exports re-exports
2065 replacements autoloads))
2067 (purify-module! module)
2068 (loop (cdr kws) reversed-interfaces exports re-exports
2069 replacements autoloads))
2071 (if (not (pair? (cdr kws)))
2073 (set-module-duplicates-handlers!
2075 (lookup-duplicates-handlers (cadr kws)))
2076 (loop (cddr kws) reversed-interfaces exports re-exports
2077 replacements autoloads))
2078 ((#:export #:export-syntax)
2079 (or (pair? (cdr kws))
2083 (append (cadr kws) exports)
2087 ((#:re-export #:re-export-syntax)
2088 (or (pair? (cdr kws))
2093 (append (cadr kws) re-exports)
2096 ((#:replace #:replace-syntax)
2097 (or (pair? (cdr kws))
2103 (append (cadr kws) replacements)
2106 (unrecognized kws)))))
2107 (run-hook module-defined-hook module)
2110 ;; `module-defined-hook' is a hook that is run whenever a new module
2111 ;; is defined. Its members are called with one argument, the new
2113 (define module-defined-hook (make-hook 1))
2120 (define (make-autoload-interface module name bindings)
2121 (let ((b (lambda (a sym definep)
2122 (and (memq sym bindings)
2123 (let ((i (module-public-interface (resolve-module name))))
2125 (error "missing interface for module" name))
2126 (let ((autoload (memq a (module-uses module))))
2127 ;; Replace autoload-interface with actual interface if
2128 ;; that has not happened yet.
2129 (if (pair? autoload)
2130 (set-car! autoload i)))
2131 (module-local-variable i sym))))))
2132 (module-constructor (make-hash-table 0) '() b #f #f name 'autoload #f
2133 (make-hash-table 0) '() (make-weak-value-hash-table 31))))
2135 (define (module-autoload! module . args)
2136 "Have @var{module} automatically load the module named @var{name} when one
2137 of the symbols listed in @var{bindings} is looked up. @var{args} should be a
2138 list of module-name/binding-list pairs, e.g., as in @code{(module-autoload!
2139 module '(ice-9 q) '(make-q q-length))}."
2140 (let loop ((args args))
2144 (error "invalid name+binding autoload list" args))
2146 (let ((name (car args))
2147 (bindings (cadr args)))
2148 (module-use! module (make-autoload-interface module
2150 (loop (cddr args)))))))
2155 ;;; {Autoloading modules}
2158 (define autoloads-in-progress '())
2160 ;; This function is called from "modules.c". If you change it, be
2161 ;; sure to update "modules.c" as well.
2163 (define (try-module-autoload module-name)
2164 (let* ((reverse-name (reverse module-name))
2165 (name (symbol->string (car reverse-name)))
2166 (dir-hint-module-name (reverse (cdr reverse-name)))
2167 (dir-hint (apply string-append
2169 (string-append (symbol->string elt) "/"))
2170 dir-hint-module-name))))
2171 (resolve-module dir-hint-module-name #f)
2172 (and (not (autoload-done-or-in-progress? dir-hint name))
2174 (define (load-file proc file)
2175 (save-module-excursion (lambda () (proc file)))
2178 (lambda () (autoload-in-progress! dir-hint name))
2180 (let ((file (in-vicinity dir-hint name)))
2181 (let ((compiled (and load-compiled
2183 (string-append file ".go"))))
2184 (source (%search-load-path file)))
2187 (< (stat:mtime (stat compiled))
2188 (stat:mtime (stat source)))))
2190 (warn "source file" source "newer than" compiled))
2191 (with-fluid* current-reader #f
2192 (lambda () (load-file primitive-load source))))
2194 (load-file load-compiled compiled))))))
2195 (lambda () (set-autoloaded! dir-hint name didit)))
2200 ;;; {Dynamic linking of modules}
2203 (define autoloads-done '((guile . guile)))
2205 (define (autoload-done-or-in-progress? p m)
2206 (let ((n (cons p m)))
2207 (->bool (or (member n autoloads-done)
2208 (member n autoloads-in-progress)))))
2210 (define (autoload-done! p m)
2211 (let ((n (cons p m)))
2212 (set! autoloads-in-progress
2213 (delete! n autoloads-in-progress))
2214 (or (member n autoloads-done)
2215 (set! autoloads-done (cons n autoloads-done)))))
2217 (define (autoload-in-progress! p m)
2218 (let ((n (cons p m)))
2219 (set! autoloads-done
2220 (delete! n autoloads-done))
2221 (set! autoloads-in-progress (cons n autoloads-in-progress))))
2223 (define (set-autoloaded! p m done?)
2225 (autoload-done! p m)
2226 (let ((n (cons p m)))
2227 (set! autoloads-done (delete! n autoloads-done))
2228 (set! autoloads-in-progress (delete! n autoloads-in-progress)))))
2232 ;;; {Run-time options}
2235 (defmacro define-option-interface (option-group)
2236 (let* ((option-name car)
2238 (option-documentation caddr)
2240 ;; Below follow the macros defining the run-time option interfaces.
2242 (make-options (lambda (interface)
2244 (cond ((null? args) (,interface))
2246 (,interface (car args)) (,interface))
2249 (display (option-name option))
2250 (if (< (string-length
2251 (symbol->string (option-name option)))
2255 (display (option-value option))
2257 (display (option-documentation option))
2259 (,interface #t)))))))
2261 (make-enable (lambda (interface)
2263 (,interface (append flags (,interface)))
2266 (make-disable (lambda (interface)
2268 (let ((options (,interface)))
2269 (for-each (lambda (flag)
2270 (set! options (delq! flag options)))
2272 (,interface options)
2274 (let* ((interface (car option-group))
2275 (options/enable/disable (cadr option-group)))
2277 (define ,(car options/enable/disable)
2278 ,(make-options interface))
2279 (define ,(cadr options/enable/disable)
2280 ,(make-enable interface))
2281 (define ,(caddr options/enable/disable)
2282 ,(make-disable interface))
2283 (defmacro ,(caaddr option-group) (opt val)
2284 `(,',(car options/enable/disable)
2285 (append (,',(car options/enable/disable))
2286 (list ',opt ,val))))))))
2288 (define-option-interface
2289 (eval-options-interface
2290 (eval-options eval-enable eval-disable)
2293 (define-option-interface
2294 (debug-options-interface
2295 (debug-options debug-enable debug-disable)
2298 (define-option-interface
2299 (evaluator-traps-interface
2300 (traps trap-enable trap-disable)
2303 (define-option-interface
2304 (read-options-interface
2305 (read-options read-enable read-disable)
2308 (define-option-interface
2309 (print-options-interface
2310 (print-options print-enable print-disable)
2318 (define (repl read evaler print)
2319 (let loop ((source (read (current-input-port))))
2320 (print (evaler source))
2321 (loop (read (current-input-port)))))
2323 ;; A provisional repl that acts like the SCM repl:
2325 (define scm-repl-silent #f)
2326 (define (assert-repl-silence v) (set! scm-repl-silent v))
2328 (define *unspecified* (if #f #f))
2329 (define (unspecified? v) (eq? v *unspecified*))
2331 (define scm-repl-print-unspecified #f)
2332 (define (assert-repl-print-unspecified v) (set! scm-repl-print-unspecified v))
2334 (define scm-repl-verbose #f)
2335 (define (assert-repl-verbosity v) (set! scm-repl-verbose v))
2337 (define scm-repl-prompt "guile> ")
2339 (define (set-repl-prompt! v) (set! scm-repl-prompt v))
2341 (define (default-pre-unwind-handler key . args)
2342 (save-stack pre-unwind-handler-dispatch)
2343 (apply throw key args))
2345 (define (pre-unwind-handler-dispatch key . args)
2346 (apply default-pre-unwind-handler key args))
2348 (define abort-hook (make-hook))
2350 ;; these definitions are used if running a script.
2351 ;; otherwise redefined in error-catching-loop.
2352 (define (set-batch-mode?! arg) #t)
2353 (define (batch-mode?) #t)
2355 (define (error-catching-loop thunk)
2358 (define (loop first)
2363 (call-with-unblocked-asyncs
2369 ;; This line is needed because mark
2370 ;; doesn't do closures quite right.
2371 ;; Unreferenced locals should be
2374 (let loop ((v (thunk)))
2378 (lambda (key . args)
2385 (apply throw 'switch-repl args))
2388 ;; This is one of the closures that require
2389 ;; (set! first #f) above
2392 (run-hook abort-hook)
2393 (force-output (current-output-port))
2394 (display "ABORT: " (current-error-port))
2395 (write args (current-error-port))
2396 (newline (current-error-port))
2400 (not has-shown-debugger-hint?)
2401 (not (memq 'backtrace
2402 (debug-options-interface)))
2403 (stack? (fluid-ref the-last-stack)))
2405 (newline (current-error-port))
2407 "Type \"(backtrace)\" to get more information or \"(debug)\" to enter the debugger.\n"
2408 (current-error-port))
2409 (set! has-shown-debugger-hint? #t)))
2410 (force-output (current-error-port)))
2412 (primitive-exit 1)))
2413 (set! stack-saved? #f)))
2416 ;; This is the other cons-leak closure...
2418 (cond ((= (length args) 4)
2419 (apply handle-system-error key args))
2421 (apply bad-throw key args)))))))
2423 ;; Note that having just `pre-unwind-handler-dispatch'
2424 ;; here is connected with the mechanism that
2425 ;; produces a nice backtrace upon error. If, for
2426 ;; example, this is replaced with (lambda args
2427 ;; (apply pre-unwind-handler-dispatch args)), the stack
2428 ;; cutting (in save-stack) goes wrong and ends up
2429 ;; saving no stack at all, so there is no
2431 pre-unwind-handler-dispatch)))
2433 (if next (loop next) status)))
2434 (set! set-batch-mode?! (lambda (arg)
2436 (set! interactive #f)
2439 (error "sorry, not implemented")))))
2440 (set! batch-mode? (lambda () (not interactive)))
2441 (call-with-blocked-asyncs
2442 (lambda () (loop (lambda () #t))))))
2444 ;;(define the-last-stack (make-fluid)) Defined by scm_init_backtrace ()
2445 (define before-signal-stack (make-fluid))
2446 (define stack-saved? #f)
2448 (define (save-stack . narrowing)
2450 (cond ((not (memq 'debug (debug-options-interface)))
2451 (fluid-set! the-last-stack #f)
2452 (set! stack-saved? #t))
2458 (apply make-stack #t save-stack primitive-eval #t 0 narrowing))
2460 (apply make-stack #t save-stack 0 #t 0 narrowing))
2462 (apply make-stack #t save-stack tk-stack-mark #t 0 narrowing))
2464 (apply make-stack #t save-stack 0 1 narrowing))
2466 (let ((id (stack-id #t)))
2467 (and (procedure? id)
2468 (apply make-stack #t save-stack id #t 0 narrowing))))))
2469 (set! stack-saved? #t)))))
2471 (define before-error-hook (make-hook))
2472 (define after-error-hook (make-hook))
2473 (define before-backtrace-hook (make-hook))
2474 (define after-backtrace-hook (make-hook))
2476 (define has-shown-debugger-hint? #f)
2478 (define (handle-system-error key . args)
2479 (let ((cep (current-error-port)))
2480 (cond ((not (stack? (fluid-ref the-last-stack))))
2481 ((memq 'backtrace (debug-options-interface))
2482 (let ((highlights (if (or (eq? key 'wrong-type-arg)
2483 (eq? key 'out-of-range))
2486 (run-hook before-backtrace-hook)
2488 (display "Backtrace:\n")
2489 (display-backtrace (fluid-ref the-last-stack) cep
2492 (run-hook after-backtrace-hook))))
2493 (run-hook before-error-hook)
2494 (apply display-error (fluid-ref the-last-stack) cep args)
2495 (run-hook after-error-hook)
2497 (throw 'abort key)))
2499 (define (quit . args)
2500 (apply throw 'quit args))
2504 ;;(define has-shown-backtrace-hint? #f) Defined by scm_init_backtrace ()
2506 ;; Replaced by C code:
2507 ;;(define (backtrace)
2508 ;; (if (fluid-ref the-last-stack)
2511 ;; (display-backtrace (fluid-ref the-last-stack) (current-output-port))
2513 ;; (if (and (not has-shown-backtrace-hint?)
2514 ;; (not (memq 'backtrace (debug-options-interface))))
2517 ;;"Type \"(debug-enable 'backtrace)\" if you would like a backtrace
2518 ;;automatically if an error occurs in the future.\n")
2519 ;; (set! has-shown-backtrace-hint? #t))))
2520 ;; (display "No backtrace available.\n")))
2522 (define (error-catching-repl r e p)
2523 (error-catching-loop
2525 (call-with-values (lambda () (e (r)))
2526 (lambda the-values (for-each p the-values))))))
2528 (define (gc-run-time)
2529 (cdr (assq 'gc-time-taken (gc-stats))))
2531 (define before-read-hook (make-hook))
2532 (define after-read-hook (make-hook))
2533 (define before-eval-hook (make-hook 1))
2534 (define after-eval-hook (make-hook 1))
2535 (define before-print-hook (make-hook 1))
2536 (define after-print-hook (make-hook 1))
2538 ;;; The default repl-reader function. We may override this if we've
2539 ;;; the readline library.
2542 (display (if (string? prompt) prompt (prompt)))
2544 (run-hook before-read-hook)
2545 ((or (fluid-ref current-reader) read) (current-input-port))))
2547 (define (scm-style-repl)
2552 (repl-report-start-timing (lambda ()
2553 (set! start-gc-rt (gc-run-time))
2554 (set! start-rt (get-internal-run-time))))
2555 (repl-report (lambda ()
2557 (display (inexact->exact
2558 (* 1000 (/ (- (get-internal-run-time) start-rt)
2559 internal-time-units-per-second))))
2561 (display (inexact->exact
2562 (* 1000 (/ (- (gc-run-time) start-gc-rt)
2563 internal-time-units-per-second))))
2564 (display " msec in gc)\n")))
2566 (consume-trailing-whitespace
2568 (let ((ch (peek-char)))
2571 ((or (char=? ch #\space) (char=? ch #\tab))
2573 (consume-trailing-whitespace))
2574 ((char=? ch #\newline)
2578 (let ((prompt (cond ((string? scm-repl-prompt)
2580 ((thunk? scm-repl-prompt)
2582 (scm-repl-prompt "> ")
2584 (repl-reader prompt))))
2586 ;; As described in R4RS, the READ procedure updates the
2587 ;; port to point to the first character past the end of
2588 ;; the external representation of the object. This
2589 ;; means that it doesn't consume the newline typically
2590 ;; found after an expression. This means that, when
2591 ;; debugging Guile with GDB, GDB gets the newline, which
2592 ;; it often interprets as a "continue" command, making
2593 ;; breakpoints kind of useless. So, consume any
2594 ;; trailing newline here, as well as any whitespace
2596 ;; But not if EOF, for control-D.
2597 (if (not (eof-object? val))
2598 (consume-trailing-whitespace))
2599 (run-hook after-read-hook)
2600 (if (eof-object? val)
2602 (repl-report-start-timing)
2603 (if scm-repl-verbose
2606 (display ";;; EOF -- quitting")
2611 (-eval (lambda (sourc)
2612 (repl-report-start-timing)
2613 (run-hook before-eval-hook sourc)
2614 (let ((val (start-stack 'repl-stack
2615 ;; If you change this procedure
2616 ;; (primitive-eval), please also
2617 ;; modify the repl-stack case in
2618 ;; save-stack so that stack cutting
2619 ;; continues to work.
2620 (primitive-eval sourc))))
2621 (run-hook after-eval-hook sourc)
2625 (-print (let ((maybe-print (lambda (result)
2626 (if (or scm-repl-print-unspecified
2627 (not (unspecified? result)))
2632 (if (not scm-repl-silent)
2634 (run-hook before-print-hook result)
2635 (maybe-print result)
2636 (run-hook after-print-hook result)
2637 (if scm-repl-verbose
2641 (-quit (lambda (args)
2642 (if scm-repl-verbose
2644 (display ";;; QUIT executed, repl exitting")
2650 (if scm-repl-verbose
2652 (display ";;; ABORT executed.")
2655 (repl -read -eval -print))))
2657 (let ((status (error-catching-repl -read
2665 ;;; {IOTA functions: generating lists of numbers}
2669 (let loop ((count (1- n)) (result '()))
2670 (if (< count 0) result
2671 (loop (1- count) (cons count result)))))
2677 ;;; Similar to `begin' but returns a list of the results of all constituent
2678 ;;; forms instead of the result of the last form.
2679 ;;; (The definition relies on the current left-to-right
2680 ;;; order of evaluation of operands in applications.)
2683 (defmacro collect forms
2691 ;; with-fluids is a convenience wrapper for the builtin procedure
2692 ;; `with-fluids*'. The syntax is just like `let':
2694 ;; (with-fluids ((fluid val)
2698 (defmacro with-fluids (bindings . body)
2699 (let ((fluids (map car bindings))
2700 (values (map cadr bindings)))
2701 (if (and (= (length fluids) 1) (= (length values) 1))
2702 `(with-fluid* ,(car fluids) ,(car values) (lambda () ,@body))
2703 `(with-fluids* (list ,@fluids) (list ,@values)
2704 (lambda () ,@body)))))
2708 ;;; with `continue' and `break'.
2711 ;; The inner `do' loop avoids re-establishing a catch every iteration,
2712 ;; that's only necessary if continue is actually used. A new key is
2713 ;; generated every time, so break and continue apply to their originating
2714 ;; `while' even when recursing.
2716 ;; FIXME: This macro is unintentionally unhygienic with respect to let,
2717 ;; make-symbol, do, throw, catch, lambda, and not.
2719 (define-macro (while cond . body)
2720 (let ((keyvar (make-symbol "while-keyvar")))
2721 `(let ((,keyvar (make-symbol "while-key")))
2725 (let ((break (lambda () (throw ,keyvar #t)))
2726 (continue (lambda () (throw ,keyvar #f))))
2737 ;;; {Module System Macros}
2740 ;; Return a list of expressions that evaluate to the appropriate
2741 ;; arguments for resolve-interface according to SPEC.
2745 (if (memq 'prefix (read-options))
2746 (error "boot-9 must be compiled with #:kw, not :kw")))
2748 (define (compile-interface-spec spec)
2749 (define (make-keyarg sym key quote?)
2750 (cond ((or (memq sym spec)
2754 (list key (list 'quote (cadr rest)))
2755 (list key (cadr rest)))))
2758 (define (map-apply func list)
2759 (map (lambda (args) (apply func args)) list))
2762 '((:select #:select #t)
2764 (:prefix #:prefix #t)
2765 (:renamer #:renamer #f)))
2766 (if (not (pair? (car spec)))
2769 ,@(apply append (map-apply make-keyarg keys)))))
2771 (define (keyword-like-symbol->keyword sym)
2772 (symbol->keyword (string->symbol (substring (symbol->string sym) 1))))
2774 (define (compile-define-module-args args)
2775 ;; Just quote everything except #:use-module and #:use-syntax. We
2776 ;; need to know about all arguments regardless since we want to turn
2777 ;; symbols that look like keywords into real keywords, and the
2778 ;; keyword args in a define-module form are not regular
2779 ;; (i.e. no-backtrace doesn't take a value).
2780 (let loop ((compiled-args `((quote ,(car args))))
2783 (reverse! compiled-args))
2784 ;; symbol in keyword position
2785 ((symbol? (car args))
2787 (cons (keyword-like-symbol->keyword (car args)) (cdr args))))
2788 ((memq (car args) '(#:no-backtrace #:pure))
2789 (loop (cons (car args) compiled-args)
2792 (error "keyword without value:" (car args)))
2793 ((memq (car args) '(#:use-module #:use-syntax))
2794 (loop (cons* `(list ,@(compile-interface-spec (cadr args)))
2798 ((eq? (car args) #:autoload)
2799 (loop (cons* `(quote ,(caddr args))
2800 `(quote ,(cadr args))
2805 (loop (cons* `(quote ,(cadr args))
2810 (defmacro define-module args
2813 (let ((m (process-define-module
2814 (list ,@(compile-define-module-args args)))))
2815 (set-current-module m)
2818 ;; The guts of the use-modules macro. Add the interfaces of the named
2819 ;; modules to the use-list of the current module, in order.
2821 ;; This function is called by "modules.c". If you change it, be sure
2822 ;; to change scm_c_use_module as well.
2824 (define (process-use-modules module-interface-args)
2825 (let ((interfaces (map (lambda (mif-args)
2826 (or (apply resolve-interface mif-args)
2827 (error "no such module" mif-args)))
2828 module-interface-args)))
2829 (call-with-deferred-observers
2831 (module-use-interfaces! (current-module) interfaces)))))
2833 (defmacro use-modules modules
2836 (process-use-modules
2837 (list ,@(map (lambda (m)
2838 `(list ,@(compile-interface-spec m)))
2842 (defmacro use-syntax (spec)
2845 (issue-deprecation-warning
2846 "`use-syntax' is deprecated. Please contact guile-devel for more info.")
2847 (process-use-modules (list (list ,@(compile-interface-spec spec))))
2850 ;; Dirk:FIXME:: This incorrect (according to R5RS) syntax needs to be changed
2851 ;; as soon as guile supports hygienic macros.
2852 (define-syntax define-private
2857 (define-syntax define-public
2859 ((_ (name . args) . body)
2860 (define-public name (lambda args . body)))
2866 (define-syntax defmacro-public
2868 ((_ name args . body)
2870 (defmacro name args . body)
2871 (export-syntax name)))))
2873 ;; Export a local variable
2875 ;; This function is called from "modules.c". If you change it, be
2876 ;; sure to update "modules.c" as well.
2878 (define (module-export! m names)
2879 (let ((public-i (module-public-interface m)))
2880 (for-each (lambda (name)
2881 (let ((var (module-ensure-local-variable! m name)))
2882 (module-add! public-i name var)))
2885 (define (module-replace! m names)
2886 (let ((public-i (module-public-interface m)))
2887 (for-each (lambda (name)
2888 (let ((var (module-ensure-local-variable! m name)))
2889 (set-object-property! var 'replace #t)
2890 (module-add! public-i name var)))
2893 ;; Re-export a imported variable
2895 (define (module-re-export! m names)
2896 (let ((public-i (module-public-interface m)))
2897 (for-each (lambda (name)
2898 (let ((var (module-variable m name)))
2900 (error "Undefined variable:" name))
2901 ((eq? var (module-local-variable m name))
2902 (error "re-exporting local variable:" name))
2904 (module-add! public-i name var)))))
2907 (defmacro export names
2908 `(call-with-deferred-observers
2910 (module-export! (current-module) ',names))))
2912 (defmacro re-export names
2913 `(call-with-deferred-observers
2915 (module-re-export! (current-module) ',names))))
2917 (defmacro export-syntax names
2920 (defmacro re-export-syntax names
2921 `(re-export ,@names))
2923 (define load load-module)
2927 ;;; {Compiler interface}
2929 ;;; The full compiler interface can be found in (system). Here we put a
2930 ;;; few useful procedures into the global namespace.
2932 (module-autoload! the-scm-module
2933 '(system base compile)
2935 compile-time-environment))
2943 (define make-mutable-parameter
2944 (let ((make (lambda (fluid converter)
2948 (fluid-set! fluid (converter (car args))))))))
2949 (lambda (init . converter)
2950 (let ((fluid (make-fluid))
2951 (converter (if (null? converter)
2954 (fluid-set! fluid (converter init))
2955 (make fluid converter)))))
2959 ;;; {Handling of duplicate imported bindings}
2962 ;; Duplicate handlers take the following arguments:
2964 ;; module importing module
2965 ;; name conflicting name
2966 ;; int1 old interface where name occurs
2967 ;; val1 value of binding in old interface
2968 ;; int2 new interface where name occurs
2969 ;; val2 value of binding in new interface
2970 ;; var previous resolution or #f
2971 ;; val value of previous resolution
2973 ;; A duplicate handler can take three alternative actions:
2975 ;; 1. return #f => leave responsibility to next handler
2976 ;; 2. exit with an error
2977 ;; 3. return a variable resolving the conflict
2980 (define duplicate-handlers
2981 (let ((m (make-module 7)))
2983 (define (check module name int1 val1 int2 val2 var val)
2984 (scm-error 'misc-error
2986 "~A: `~A' imported from both ~A and ~A"
2987 (list (module-name module)
2993 (define (warn module name int1 val1 int2 val2 var val)
2994 (format (current-error-port)
2995 "WARNING: ~A: `~A' imported from both ~A and ~A\n"
2996 (module-name module)
3002 (define (replace module name int1 val1 int2 val2 var val)
3003 (let ((old (or (and var (object-property var 'replace) var)
3004 (module-variable int1 name)))
3005 (new (module-variable int2 name)))
3006 (if (object-property old 'replace)
3007 (and (or (eq? old new)
3008 (not (object-property new 'replace)))
3010 (and (object-property new 'replace)
3013 (define (warn-override-core module name int1 val1 int2 val2 var val)
3014 (and (eq? int1 the-scm-module)
3016 (format (current-error-port)
3017 "WARNING: ~A: imported module ~A overrides core binding `~A'\n"
3018 (module-name module)
3021 (module-local-variable int2 name))))
3023 (define (first module name int1 val1 int2 val2 var val)
3024 (or var (module-local-variable int1 name)))
3026 (define (last module name int1 val1 int2 val2 var val)
3027 (module-local-variable int2 name))
3029 (define (noop module name int1 val1 int2 val2 var val)
3032 (set-module-name! m 'duplicate-handlers)
3033 (set-module-kind! m 'interface)
3034 (module-define! m 'check check)
3035 (module-define! m 'warn warn)
3036 (module-define! m 'replace replace)
3037 (module-define! m 'warn-override-core warn-override-core)
3038 (module-define! m 'first first)
3039 (module-define! m 'last last)
3040 (module-define! m 'merge-generics noop)
3041 (module-define! m 'merge-accessors noop)
3044 (define (lookup-duplicates-handlers handler-names)
3046 (map (lambda (handler-name)
3047 (or (module-symbol-local-binding
3048 duplicate-handlers handler-name #f)
3049 (error "invalid duplicate handler name:"
3051 (if (list? handler-names)
3053 (list handler-names)))))
3055 (define default-duplicate-binding-procedures
3056 (make-mutable-parameter #f))
3058 (define default-duplicate-binding-handler
3059 (make-mutable-parameter '(replace warn-override-core warn last)
3060 (lambda (handler-names)
3061 (default-duplicate-binding-procedures
3062 (lookup-duplicates-handlers handler-names))
3067 ;;; {`cond-expand' for SRFI-0 support.}
3069 ;;; This syntactic form expands into different commands or
3070 ;;; definitions, depending on the features provided by the Scheme
3076 ;;; --> (cond-expand <cond-expand-clause>+)
3077 ;;; | (cond-expand <cond-expand-clause>* (else <command-or-definition>))
3078 ;;; <cond-expand-clause>
3079 ;;; --> (<feature-requirement> <command-or-definition>*)
3080 ;;; <feature-requirement>
3081 ;;; --> <feature-identifier>
3082 ;;; | (and <feature-requirement>*)
3083 ;;; | (or <feature-requirement>*)
3084 ;;; | (not <feature-requirement>)
3085 ;;; <feature-identifier>
3086 ;;; --> <a symbol which is the name or alias of a SRFI>
3088 ;;; Additionally, this implementation provides the
3089 ;;; <feature-identifier>s `guile' and `r5rs', so that programs can
3090 ;;; determine the implementation type and the supported standard.
3092 ;;; Currently, the following feature identifiers are supported:
3094 ;;; guile r5rs srfi-0 srfi-4 srfi-6 srfi-13 srfi-14 srfi-55 srfi-61
3096 ;;; Remember to update the features list when adding more SRFIs.
3099 (define %cond-expand-features
3100 ;; Adjust the above comment when changing this.
3103 srfi-0 ;; cond-expand itself
3104 srfi-4 ;; homogenous numeric vectors
3105 srfi-6 ;; open-input-string etc, in the guile core
3106 srfi-13 ;; string library
3107 srfi-14 ;; character sets
3108 srfi-55 ;; require-extension
3109 srfi-61 ;; general cond clause
3112 ;; This table maps module public interfaces to the list of features.
3114 (define %cond-expand-table (make-hash-table 31))
3116 ;; Add one or more features to the `cond-expand' feature list of the
3119 (define (cond-expand-provide module features)
3120 (let ((mod (module-public-interface module)))
3122 (hashq-set! %cond-expand-table mod
3123 (append (hashq-ref %cond-expand-table mod '())
3127 (procedure->memoizing-macro
3129 (let ((clauses (cdr exp))
3130 (syntax-error (lambda (cl)
3131 (error "invalid clause in `cond-expand'" cl))))
3137 (or (memq clause %cond-expand-features)
3138 (let lp ((uses (module-uses (env-module env))))
3141 (hashq-ref %cond-expand-table
3147 ((eq? 'and (car clause))
3148 (let lp ((l (cdr clause)))
3152 (and (test-clause (car l)) (lp (cdr l))))
3154 (syntax-error clause)))))
3155 ((eq? 'or (car clause))
3156 (let lp ((l (cdr clause)))
3160 (or (test-clause (car l)) (lp (cdr l))))
3162 (syntax-error clause)))))
3163 ((eq? 'not (car clause))
3164 (cond ((not (pair? (cdr clause)))
3165 (syntax-error clause))
3166 ((pair? (cddr clause))
3167 ((syntax-error clause))))
3168 (not (test-clause (cadr clause))))
3170 (syntax-error clause))))
3172 (syntax-error clause))))))
3173 (let lp ((c clauses))
3176 (error "Unfulfilled `cond-expand'"))
3179 ((not (pair? (car c)))
3180 (syntax-error (car c)))
3181 ((test-clause (caar c))
3182 `(begin ,@(cdar c)))
3183 ((eq? (caar c) 'else)
3186 `(begin ,@(cdar c)))
3188 (lp (cdr c))))))))))
3190 ;; This procedure gets called from the startup code with a list of
3191 ;; numbers, which are the numbers of the SRFIs to be loaded on startup.
3193 (define (use-srfis srfis)
3194 (process-use-modules
3196 (list (list 'srfi (string->symbol
3197 (string-append "srfi-" (number->string num))))))
3202 ;;; srfi-55: require-extension
3205 (define-macro (require-extension extension-spec)
3206 ;; This macro only handles the srfi extension, which, at present, is
3207 ;; the only one defined by the standard.
3208 (if (not (pair? extension-spec))
3209 (scm-error 'wrong-type-arg "require-extension"
3210 "Not an extension: ~S" (list extension-spec) #f))
3211 (let ((extension (car extension-spec))
3212 (extension-args (cdr extension-spec)))
3215 (let ((use-list '()))
3218 (if (not (integer? i))
3219 (scm-error 'wrong-type-arg "require-extension"
3220 "Invalid srfi name: ~S" (list i) #f))
3221 (let ((srfi-sym (string->symbol
3222 (string-append "srfi-" (number->string i)))))
3223 (if (not (memq srfi-sym %cond-expand-features))
3224 (set! use-list (cons `(use-modules (srfi ,srfi-sym))
3227 (if (pair? use-list)
3228 ;; i.e. (begin (use-modules x) (use-modules y) (use-modules z))
3229 `(begin ,@(reverse! use-list)))))
3232 'wrong-type-arg "require-extension"
3233 "Not a recognized extension type: ~S" (list extension) #f)))))
3237 ;;; {Load emacs interface support if emacs option is given.}
3240 (define (named-module-use! user usee)
3241 (module-use! (resolve-module user) (resolve-interface usee)))
3243 (define (load-emacs-interface)
3244 (and (provided? 'debug-extensions)
3245 (debug-enable 'backtrace))
3246 (named-module-use! '(guile-user) '(ice-9 emacs)))
3250 (define using-readline?
3251 (let ((using-readline? (make-fluid)))
3252 (make-procedure-with-setter
3253 (lambda () (fluid-ref using-readline?))
3254 (lambda (v) (fluid-set! using-readline? v)))))
3257 (let ((guile-user-module (resolve-module '(guile-user))))
3259 ;; Load emacs interface support if emacs option is given.
3260 (if (and (module-defined? guile-user-module 'use-emacs-interface)
3261 (module-ref guile-user-module 'use-emacs-interface))
3262 (load-emacs-interface))
3264 ;; Use some convenient modules (in reverse order)
3266 (set-current-module guile-user-module)
3267 (process-use-modules
3272 (if (provided? 'regex)
3275 (if (provided? 'threads)
3276 '(((ice-9 threads)))
3278 ;; load debugger on demand
3279 (module-autoload! guile-user-module '(ice-9 debugger) '(debug))
3281 ;; Note: SIGFPE, SIGSEGV and SIGBUS are actually "query-only" (see
3282 ;; scmsigs.c scm_sigaction_for_thread), so the handlers setup here have
3284 (let ((old-handlers #f)
3285 (start-repl (module-ref (resolve-interface '(system repl repl))
3287 (signals (if (provided? 'posix)
3288 `((,SIGINT . "User interrupt")
3289 (,SIGFPE . "Arithmetic error")
3291 . "Bad memory access (Segmentation violation)"))
3293 ;; no SIGBUS on mingw
3294 (if (defined? 'SIGBUS)
3295 (set! signals (acons SIGBUS "Bad memory access (bus error)"
3302 (let ((make-handler (lambda (msg)
3304 ;; Make a backup copy of the stack
3305 (fluid-set! before-signal-stack
3306 (fluid-ref the-last-stack))
3314 (map (lambda (sig-msg)
3315 (sigaction (car sig-msg)
3316 (make-handler (cdr sig-msg))))
3319 ;; the protected thunk.
3321 (let ((status (start-repl 'scheme)))
3322 (run-hook exit-hook)
3327 (map (lambda (sig-msg old-handler)
3328 (if (not (car old-handler))
3329 ;; restore original C handler.
3330 (sigaction (car sig-msg) #f)
3331 ;; restore Scheme handler, SIG_IGN or SIG_DFL.
3332 (sigaction (car sig-msg)
3334 (cdr old-handler))))
3335 signals old-handlers))))))
3337 ;;; This hook is run at the very end of an interactive session.
3339 (define exit-hook (make-hook))
3343 ;;; {Deprecated stuff}
3347 (define (feature? sym)
3348 (issue-deprecation-warning
3349 "`feature?' is deprecated. Use `provided?' instead.")
3353 (primitive-load-path "ice-9/deprecated"))
3357 ;;; Place the user in the guile-user module.
3360 ;;; FIXME: annotate ?
3361 ;; (define (syncase exp)
3362 ;; (with-fluids ((expansion-eval-closure
3363 ;; (module-eval-closure (current-module))))
3364 ;; (deannotate/source-properties (sc-expand (annotate exp)))))
3366 (define-module (guile-user))
3368 ;;; boot-9.scm ends here