3 ;;;; Copyright (C) 1995, 1996, 1997, 1998, 1999 Free Software Foundation, Inc.
5 ;;;; This program is free software; you can redistribute it and/or modify
6 ;;;; it under the terms of the GNU General Public License as published by
7 ;;;; the Free Software Foundation; either version 2, or (at your option)
8 ;;;; any later version.
10 ;;;; This program is distributed in the hope that it will be useful,
11 ;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
12 ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 ;;;; GNU General Public License for more details.
15 ;;;; You should have received a copy of the GNU General Public License
16 ;;;; along with this software; see the file COPYING. If not, write to
17 ;;;; the Free Software Foundation, Inc., 59 Temple Place, Suite 330,
18 ;;;; Boston, MA 02111-1307 USA
22 ;;; This file is the first thing loaded into Guile. It adds many mundane
23 ;;; definitions and a few that are interesting.
25 ;;; The module system (hence the hierarchical namespace) are defined in this
34 (if (not (memq sym *features*))
35 (set! *features* (cons sym *features*))))
37 ;;; Return #t iff FEATURE is available to this Guile interpreter.
38 ;;; In SLIB, provided? also checks to see if the module is available.
39 ;;; We should do that too, but don't.
40 (define (provided? feature)
41 (and (memq feature *features*) #t))
43 ;;; presumably deprecated.
44 (define feature? provided?)
49 (primitive-load-path "ice-9/r4rs.scm")
52 ;;; {Simple Debugging Tools}
56 ;; peek takes any number of arguments, writes them to the
57 ;; current ouput port, and returns the last argument.
58 ;; It is handy to wrap around an expression to look at
59 ;; a value each time is evaluated, e.g.:
61 ;; (+ 10 (troublesome-fn))
62 ;; => (+ 10 (pk 'troublesome-fn-returned (troublesome-fn)))
65 (define (peek . stuff)
70 (car (last-pair stuff)))
74 (define (warn . stuff)
75 (with-output-to-port (current-error-port)
78 (display ";;; WARNING ")
81 (car (last-pair stuff)))))
84 ;;; {Trivial Functions}
88 (define (1+ n) (+ n 1))
89 (define (-1+ n) (+ n -1))
91 (define return-it noop)
92 (define (and=> value procedure) (and value (procedure value)))
93 (define (make-hash-table k) (make-vector k '()))
95 ;;; apply-to-args is functionally redunant with apply and, worse,
96 ;;; is less general than apply since it only takes two arguments.
98 ;;; On the other hand, apply-to-args is a syntacticly convenient way to
99 ;;; perform binding in many circumstances when the "let" family of
100 ;;; of forms don't cut it. E.g.:
102 ;;; (apply-to-args (return-3d-mouse-coords)
107 (define (apply-to-args args fn) (apply fn args))
113 (define (ipow-by-squaring x k acc proc)
114 (cond ((zero? k) acc)
115 ((= 1 k) (proc acc x))
116 (else (ipow-by-squaring (proc x x)
118 (if (even? k) acc (proc acc x))
121 (define string-character-length string-length)
125 ;; A convenience function for combining flag bits. Like logior, but
126 ;; handles the cases of 0 and 1 arguments.
128 (define (flags . args)
131 ((null? (cdr args)) (car args))
132 (else (apply logior args))))
135 ;;; {Symbol Properties}
138 (define (symbol-property sym prop)
139 (let ((pair (assoc prop (symbol-pref sym))))
140 (and pair (cdr pair))))
142 (define (set-symbol-property! sym prop val)
143 (let ((pair (assoc prop (symbol-pref sym))))
146 (symbol-pset! sym (acons prop val (symbol-pref sym))))))
148 (define (symbol-property-remove! sym prop)
149 (let ((pair (assoc prop (symbol-pref sym))))
151 (symbol-pset! sym (delq! pair (symbol-pref sym))))))
155 ;;; {Line and Delimited I/O}
157 ;;; corresponds to SCM_LINE_INCREMENTORS in libguile.
158 (define scm-line-incrementors "\n")
160 (define (read-line! string . maybe-port)
161 (let* ((port (if (pair? maybe-port)
163 (current-input-port))))
164 (let* ((rv (%read-delimited! scm-line-incrementors
168 (terminator (car rv))
170 (cond ((and (= nchars 0)
171 (eof-object? terminator))
173 ((not terminator) #f)
176 (define (read-delimited! delims buf . args)
177 (let* ((num-args (length args))
178 (port (if (> num-args 0)
180 (current-input-port)))
181 (handle-delim (if (> num-args 1)
184 (start (if (> num-args 2)
187 (end (if (> num-args 3)
189 (string-length buf))))
190 (let* ((rv (%read-delimited! delims
192 (not (eq? handle-delim 'peek))
196 (terminator (car rv))
198 (cond ((or (not terminator) ; buffer filled
199 (eof-object? terminator))
201 (if (eq? handle-delim 'split)
202 (cons terminator terminator)
204 (if (eq? handle-delim 'split)
205 (cons nchars terminator)
210 ((concat) (string-set! buf (+ nchars start) terminator)
212 ((split) (cons nchars terminator))
213 (else (error "unexpected handle-delim value: "
216 (define (read-delimited delims . args)
217 (let* ((port (if (pair? args)
218 (let ((pt (car args)))
219 (set! args (cdr args))
221 (current-input-port)))
222 (handle-delim (if (pair? args)
225 (let loop ((substrings ())
227 (buf-size 100)) ; doubled each time through.
228 (let* ((buf (make-string buf-size))
229 (rv (%read-delimited! delims
231 (not (eq? handle-delim 'peek))
233 (terminator (car rv))
239 (cons (if (and (eq? handle-delim 'concat)
240 (not (eof-object? terminator)))
243 (cons (make-shared-substring buf 0 nchars)
245 (new-total (+ total-chars nchars)))
246 (cond ((not terminator)
248 (loop (cons (substring buf 0 nchars) substrings)
251 ((eof-object? terminator)
252 (if (zero? new-total)
253 (if (eq? handle-delim 'split)
254 (cons terminator terminator)
256 (if (eq? handle-delim 'split)
257 (cons (join-substrings) terminator)
261 ((trim peek concat) (join-substrings))
262 ((split) (cons (join-substrings) terminator))
265 (else (error "unexpected handle-delim value: "
266 handle-delim)))))))))
268 ;;; read-line [PORT [HANDLE-DELIM]] reads a newline-terminated string
269 ;;; from PORT. The return value depends on the value of HANDLE-DELIM,
270 ;;; which may be one of the symbols `trim', `concat', `peek' and
271 ;;; `split'. If it is `trim' (the default), the trailing newline is
272 ;;; removed and the string is returned. If `concat', the string is
273 ;;; returned with the trailing newline intact. If `peek', the newline
274 ;;; is left in the input port buffer and the string is returned. If
275 ;;; `split', the newline is split from the string and read-line
276 ;;; returns a pair consisting of the truncated string and the newline.
278 (define (read-line . args)
279 (let* ((port (if (null? args)
282 (handle-delim (if (> (length args) 1)
285 (line/delim (%read-line port))
286 (line (car line/delim))
287 (delim (cdr line/delim)))
291 ((concat) (if (and (string? line) (char? delim))
292 (string-append line (string delim))
294 ((peek) (if (char? delim)
295 (unread-char delim port))
298 (error "unexpected handle-delim value: " handle-delim)))))
305 (define uniform-vector? array?)
306 (define make-uniform-vector dimensions->uniform-array)
307 ; (define uniform-vector-ref array-ref)
308 (define (uniform-vector-set! u i o)
309 (uniform-array-set1! u o i))
310 (define uniform-vector-fill! array-fill!)
311 (define uniform-vector-read! uniform-array-read!)
312 (define uniform-vector-write uniform-array-write)
314 (define (make-array fill . args)
315 (dimensions->uniform-array args () fill))
316 (define (make-uniform-array prot . args)
317 (dimensions->uniform-array args prot))
318 (define (list->array ndim lst)
319 (list->uniform-array ndim '() lst))
320 (define (list->uniform-vector prot lst)
321 (list->uniform-array 1 prot lst))
322 (define (array-shape a)
323 (map (lambda (ind) (if (number? ind) (list 0 (+ -1 ind)) ind))
324 (array-dimensions a))))
330 (define (symbol->keyword symbol)
331 (make-keyword-from-dash-symbol (symbol-append '- symbol)))
333 (define (keyword->symbol kw)
334 (let ((sym (keyword-dash-symbol kw)))
335 (string->symbol (substring sym 1 (string-length sym)))))
337 (define (kw-arg-ref args kw)
338 (let ((rem (member kw args)))
339 (and rem (pair? (cdr rem)) (cadr rem))))
345 (define (struct-layout s)
346 (struct-ref (struct-vtable s) vtable-index-layout))
352 ;; Printing records: by default, records are printed as
354 ;; #<type-name field1: val1 field2: val2 ...>
356 ;; You can change that by giving a custom printing function to
357 ;; MAKE-RECORD-TYPE (after the list of field symbols). This function
358 ;; will be called like
360 ;; (<printer> object port)
362 ;; It should print OBJECT to PORT.
364 (define (inherit-print-state old-port new-port)
365 (if (get-print-state old-port)
366 (port-with-print-state new-port (get-print-state old-port))
369 ;; 0: type-name, 1: fields
370 (define record-type-vtable
371 (make-vtable-vtable "prpr" 0
373 (cond ((eq? s record-type-vtable)
374 (display "#<record-type-vtable>" p))
376 (display "#<record-type " p)
377 (display (record-type-name s) p)
380 (define (record-type? obj)
381 (and (struct? obj) (eq? record-type-vtable (struct-vtable obj))))
383 (define (make-record-type type-name fields . opt)
384 (let ((printer-fn (and (pair? opt) (car opt))))
385 (let ((struct (make-struct record-type-vtable 0
388 (map (lambda (f) "pw") fields)))
392 (display type-name p)
393 (let loop ((fields fields)
396 ((not (null? fields))
398 (display (car fields) p)
400 (display (struct-ref s off) p)
401 (loop (cdr fields) (+ 1 off)))))
404 (copy-tree fields))))
405 ;; Temporary solution: Associate a name to the record type descriptor
406 ;; so that the object system can create a wrapper class for it.
407 (set-struct-vtable-name! struct (if (symbol? type-name)
409 (string->symbol type-name)))
412 (define (record-type-name obj)
413 (if (record-type? obj)
414 (struct-ref obj vtable-offset-user)
415 (error 'not-a-record-type obj)))
417 (define (record-type-fields obj)
418 (if (record-type? obj)
419 (struct-ref obj (+ 1 vtable-offset-user))
420 (error 'not-a-record-type obj)))
422 (define (record-constructor rtd . opt)
423 (let ((field-names (if (pair? opt) (car opt) (record-type-fields rtd))))
424 (eval `(lambda ,field-names
425 (make-struct ',rtd 0 ,@(map (lambda (f)
426 (if (memq f field-names)
429 (record-type-fields rtd)))))))
431 (define (record-predicate rtd)
432 (lambda (obj) (and (struct? obj) (eq? rtd (struct-vtable obj)))))
434 (define (record-accessor rtd field-name)
435 (let* ((pos (list-index (record-type-fields rtd) field-name)))
437 (error 'no-such-field field-name))
439 (and (eq? ',rtd (record-type-descriptor obj))
440 (struct-ref obj ,pos))))))
442 (define (record-modifier rtd field-name)
443 (let* ((pos (list-index (record-type-fields rtd) field-name)))
445 (error 'no-such-field field-name))
446 (eval `(lambda (obj val)
447 (and (eq? ',rtd (record-type-descriptor obj))
448 (struct-set! obj ,pos val))))))
451 (define (record? obj)
452 (and (struct? obj) (record-type? (struct-vtable obj))))
454 (define (record-type-descriptor obj)
457 (error 'not-a-record obj)))
465 (define (->bool x) (not (not x)))
471 (define (symbol-append . args)
472 (string->symbol (apply string-append args)))
474 (define (list->symbol . args)
475 (string->symbol (apply list->string args)))
477 (define (symbol . args)
478 (string->symbol (apply string args)))
480 (define (obarray-symbol-append ob . args)
481 (string->obarray-symbol (apply string-append ob args)))
483 (define (obarray-gensym obarray . opt)
485 (gensym "%%gensym" obarray)
486 (gensym (car opt) obarray)))
492 (define (list-index l k)
498 (loop (+ n 1) (cdr l))))))
500 (define (make-list n . init)
501 (if (pair? init) (set! init (car init)))
502 (let loop ((answer '())
506 (loop (cons init answer) (- n 1)))))
510 ;;; {Multiple return values}
513 (make-record-type "values"
517 (let ((make-values (record-constructor *values-rtd*)))
519 (if (and (not (null? x))
524 (define call-with-values
525 (let ((access-values (record-accessor *values-rtd* 'values))
526 (values-predicate? (record-predicate *values-rtd*)))
527 (lambda (producer consumer)
528 (let ((result (producer)))
529 (if (values-predicate? result)
530 (apply consumer (access-values result))
531 (consumer result))))))
536 ;;; {and-map and or-map}
538 ;;; (and-map fn lst) is like (and (fn (car lst)) (fn (cadr lst)) (fn...) ...)
539 ;;; (or-map fn lst) is like (or (fn (car lst)) (fn (cadr lst)) (fn...) ...)
540 ;;; (map-in-order fn lst) is like (map fn lst) but definately in order of lst.
545 ;; Apply f to successive elements of l until exhaustion or f returns #f.
546 ;; If returning early, return #f. Otherwise, return the last value returned
547 ;; by f. If f has never been called because l is empty, return #t.
549 (define (and-map f lst)
550 (let loop ((result #t)
555 (loop (f (car l)) (cdr l))))))
559 ;; Apply f to successive elements of l until exhaustion or while f returns #f.
560 ;; If returning early, return the return value of f.
562 (define (or-map f lst)
563 (let loop ((result #f)
567 (loop (f (car l)) (cdr l))))))
571 (if (provided? 'posix)
572 (primitive-load-path "ice-9/posix.scm"))
574 (if (provided? 'socket)
575 (primitive-load-path "ice-9/networking.scm"))
578 (if (provided? 'posix)
582 (let ((port (catch 'system-error (lambda () (open-file str OPEN_READ))
584 (if port (begin (close-port port) #t)
587 (define file-is-directory?
588 (if (provided? 'posix)
590 (eq? (stat:type (stat str)) 'directory))
592 (let ((port (catch 'system-error
593 (lambda () (open-file (string-append str "/.")
596 (if port (begin (close-port port) #t)
599 (define (has-suffix? str suffix)
600 (let ((sufl (string-length suffix))
601 (sl (string-length str)))
603 (string=? (substring str (- sl sufl) sl) suffix))))
609 (define (error . args)
612 (scm-error 'misc-error #f "?" #f #f)
613 (let loop ((msg "%s")
615 (if (not (null? rest))
616 (loop (string-append msg " %S")
618 (scm-error 'misc-error #f msg args #f)))))
620 ;; bad-throw is the hook that is called upon a throw to a an unhandled
621 ;; key (unless the throw has four arguments, in which case
622 ;; it's usually interpreted as an error throw.)
623 ;; If the key has a default handler (a throw-handler-default property),
624 ;; it is applied to the throw.
626 (define (bad-throw key . args)
627 (let ((default (symbol-property key 'throw-handler-default)))
628 (or (and default (apply default key args))
629 (apply error "unhandled-exception:" key args))))
633 (define (tm:sec obj) (vector-ref obj 0))
634 (define (tm:min obj) (vector-ref obj 1))
635 (define (tm:hour obj) (vector-ref obj 2))
636 (define (tm:mday obj) (vector-ref obj 3))
637 (define (tm:mon obj) (vector-ref obj 4))
638 (define (tm:year obj) (vector-ref obj 5))
639 (define (tm:wday obj) (vector-ref obj 6))
640 (define (tm:yday obj) (vector-ref obj 7))
641 (define (tm:isdst obj) (vector-ref obj 8))
642 (define (tm:gmtoff obj) (vector-ref obj 9))
643 (define (tm:zone obj) (vector-ref obj 10))
645 (define (set-tm:sec obj val) (vector-set! obj 0 val))
646 (define (set-tm:min obj val) (vector-set! obj 1 val))
647 (define (set-tm:hour obj val) (vector-set! obj 2 val))
648 (define (set-tm:mday obj val) (vector-set! obj 3 val))
649 (define (set-tm:mon obj val) (vector-set! obj 4 val))
650 (define (set-tm:year obj val) (vector-set! obj 5 val))
651 (define (set-tm:wday obj val) (vector-set! obj 6 val))
652 (define (set-tm:yday obj val) (vector-set! obj 7 val))
653 (define (set-tm:isdst obj val) (vector-set! obj 8 val))
654 (define (set-tm:gmtoff obj val) (vector-set! obj 9 val))
655 (define (set-tm:zone obj val) (vector-set! obj 10 val))
657 (define (tms:clock obj) (vector-ref obj 0))
658 (define (tms:utime obj) (vector-ref obj 1))
659 (define (tms:stime obj) (vector-ref obj 2))
660 (define (tms:cutime obj) (vector-ref obj 3))
661 (define (tms:cstime obj) (vector-ref obj 4))
663 (define (file-position . args) (apply ftell args))
664 (define (file-set-position . args) (apply fseek args))
666 (define (move->fdes fd/port fd)
667 (cond ((integer? fd/port)
668 (dup->fdes fd/port fd)
672 (primitive-move->fdes fd/port fd)
673 (set-port-revealed! fd/port 1)
676 (define (release-port-handle port)
677 (let ((revealed (port-revealed port)))
679 (set-port-revealed! port (- revealed 1)))))
681 (define (dup->port port/fd mode . maybe-fd)
682 (let ((port (fdopen (apply dup->fdes port/fd maybe-fd)
685 (set-port-revealed! port 1))
688 (define (dup->inport port/fd . maybe-fd)
689 (apply dup->port port/fd "r" maybe-fd))
691 (define (dup->outport port/fd . maybe-fd)
692 (apply dup->port port/fd "w" maybe-fd))
694 (define (dup port/fd . maybe-fd)
695 (if (integer? port/fd)
696 (apply dup->fdes port/fd maybe-fd)
697 (apply dup->port port/fd (port-mode port/fd) maybe-fd)))
699 (define (duplicate-port port modes)
700 (dup->port port modes))
702 (define (fdes->inport fdes)
703 (let loop ((rest-ports (fdes->ports fdes)))
704 (cond ((null? rest-ports)
705 (let ((result (fdopen fdes "r")))
706 (set-port-revealed! result 1)
708 ((input-port? (car rest-ports))
709 (set-port-revealed! (car rest-ports)
710 (+ (port-revealed (car rest-ports)) 1))
713 (loop (cdr rest-ports))))))
715 (define (fdes->outport fdes)
716 (let loop ((rest-ports (fdes->ports fdes)))
717 (cond ((null? rest-ports)
718 (let ((result (fdopen fdes "w")))
719 (set-port-revealed! result 1)
721 ((output-port? (car rest-ports))
722 (set-port-revealed! (car rest-ports)
723 (+ (port-revealed (car rest-ports)) 1))
726 (loop (cdr rest-ports))))))
728 (define (port->fdes port)
729 (set-port-revealed! port (+ (port-revealed port) 1))
732 (define (setenv name value)
734 (putenv (string-append name "=" value))
741 ;;; Here for backward compatability
743 (define scheme-file-suffix (lambda () ".scm"))
745 (define (in-vicinity vicinity file)
746 (let ((tail (let ((len (string-length vicinity)))
749 (string-ref vicinity (- len 1))))))
750 (string-append vicinity
758 ;;; {Help for scm_shell}
759 ;;; The argument-processing code used by Guile-based shells generates
760 ;;; Scheme code based on the argument list. This page contains help
761 ;;; functions for the code it generates.
763 (define (command-line) (program-arguments))
765 ;; This is mostly for the internal use of the code generated by
766 ;; scm_compile_shell_switches.
767 (define (load-user-init)
768 (define (existing-file dir)
769 (let ((path (in-vicinity dir ".guile")))
770 (if (and (file-exists? path)
771 (not (file-is-directory? path)))
774 (let ((path (or (existing-file (or (getenv "HOME") "/"))
775 (and (provided? 'posix)
776 (existing-file (passwd:dir (getpw (getuid))))))))
777 (if path (primitive-load path))))
780 ;;; {Loading by paths}
782 ;;; Load a Scheme source file named NAME, searching for it in the
783 ;;; directories listed in %load-path, and applying each of the file
784 ;;; name extensions listed in %load-extensions.
785 (define (load-from-path name)
786 (start-stack 'load-stack
787 (primitive-load-path name)))
791 ;;; {Transcendental Functions}
793 ;;; Derived from "Transcen.scm", Complex trancendental functions for SCM.
794 ;;; Written by Jerry D. Hedden, (C) FSF.
795 ;;; See the file `COPYING' for terms applying to this program.
799 (if (real? z) ($exp z)
800 (make-polar ($exp (real-part z)) (imag-part z))))
803 (if (and (real? z) (>= z 0))
805 (make-rectangular ($log (magnitude z)) (angle z))))
809 (if (negative? z) (make-rectangular 0 ($sqrt (- z)))
811 (make-polar ($sqrt (magnitude z)) (/ (angle z) 2))))
814 (let ((integer-expt integer-expt))
817 (integer-expt z1 z2))
818 ((and (real? z2) (real? z1) (>= z1 0))
821 (exp (* z2 (log z1))))))))
824 (if (real? z) ($sinh z)
825 (let ((x (real-part z)) (y (imag-part z)))
826 (make-rectangular (* ($sinh x) ($cos y))
827 (* ($cosh x) ($sin y))))))
829 (if (real? z) ($cosh z)
830 (let ((x (real-part z)) (y (imag-part z)))
831 (make-rectangular (* ($cosh x) ($cos y))
832 (* ($sinh x) ($sin y))))))
834 (if (real? z) ($tanh z)
835 (let* ((x (* 2 (real-part z)))
836 (y (* 2 (imag-part z)))
837 (w (+ ($cosh x) ($cos y))))
838 (make-rectangular (/ ($sinh x) w) (/ ($sin y) w)))))
841 (if (real? z) ($asinh z)
842 (log (+ z (sqrt (+ (* z z) 1))))))
845 (if (and (real? z) (>= z 1))
847 (log (+ z (sqrt (- (* z z) 1))))))
850 (if (and (real? z) (> z -1) (< z 1))
852 (/ (log (/ (+ 1 z) (- 1 z))) 2)))
855 (if (real? z) ($sin z)
856 (let ((x (real-part z)) (y (imag-part z)))
857 (make-rectangular (* ($sin x) ($cosh y))
858 (* ($cos x) ($sinh y))))))
860 (if (real? z) ($cos z)
861 (let ((x (real-part z)) (y (imag-part z)))
862 (make-rectangular (* ($cos x) ($cosh y))
863 (- (* ($sin x) ($sinh y)))))))
865 (if (real? z) ($tan z)
866 (let* ((x (* 2 (real-part z)))
867 (y (* 2 (imag-part z)))
868 (w (+ ($cos x) ($cosh y))))
869 (make-rectangular (/ ($sin x) w) (/ ($sinh y) w)))))
872 (if (and (real? z) (>= z -1) (<= z 1))
874 (* -i (asinh (* +i z)))))
877 (if (and (real? z) (>= z -1) (<= z 1))
879 (+ (/ (angle -1) 2) (* +i (asinh (* +i z))))))
883 (if (real? z) ($atan z)
884 (/ (log (/ (- +i z) (+ +i z))) +2i))
890 (/ (log arg) (log 10)))
894 ;;; {Reader Extensions}
897 ;;; Reader code for various "#c" forms.
900 (read-hash-extend #\' (lambda (c port)
902 (read-hash-extend #\. (lambda (c port)
905 (if (provided? 'array)
907 (let ((make-array-proc (lambda (template)
909 (read:uniform-vector template port)))))
910 (for-each (lambda (char template)
911 (read-hash-extend char
912 (make-array-proc template)))
913 '(#\b #\a #\u #\e #\s #\i #\c #\y #\h #\l)
914 '(#t #\a 1 -1 1.0 1/3 0+i #\nul s l)))
915 (let ((array-proc (lambda (c port)
916 (read:array c port))))
917 (for-each (lambda (char) (read-hash-extend char array-proc))
918 '(#\0 #\1 #\2 #\3 #\4 #\5 #\6 #\7 #\8 #\9)))))
920 (define (read:array digit port)
921 (define chr0 (char->integer #\0))
922 (let ((rank (let readnum ((val (- (char->integer digit) chr0)))
923 (if (char-numeric? (peek-char port))
924 (readnum (+ (* 10 val)
925 (- (char->integer (read-char port)) chr0)))
927 (prot (if (eq? #\( (peek-char port))
929 (let ((c (read-char port)))
937 (else (error "read:array unknown option " c)))))))
938 (if (eq? (peek-char port) #\()
939 (list->uniform-array rank prot (read port))
940 (error "read:array list not found"))))
942 (define (read:uniform-vector proto port)
943 (if (eq? #\( (peek-char port))
944 (list->uniform-array 1 proto (read port))
945 (error "read:uniform-vector list not found")))
948 ;;; {Command Line Options}
951 (define (get-option argv kw-opts kw-args return)
956 ((or (not (eq? #\- (string-ref (car argv) 0)))
957 (eq? (string-length (car argv)) 1))
958 (return 'normal-arg (car argv) (cdr argv)))
960 ((eq? #\- (string-ref (car argv) 1))
961 (let* ((kw-arg-pos (or (string-index (car argv) #\=)
962 (string-length (car argv))))
963 (kw (symbol->keyword (substring (car argv) 2 kw-arg-pos)))
964 (kw-opt? (member kw kw-opts))
965 (kw-arg? (member kw kw-args))
966 (arg (or (and (not (eq? kw-arg-pos (string-length (car argv))))
967 (substring (car argv)
969 (string-length (car argv))))
971 (begin (set! argv (cdr argv)) (car argv))))))
972 (if (or kw-opt? kw-arg?)
973 (return kw arg (cdr argv))
974 (return 'usage-error kw (cdr argv)))))
977 (let* ((char (substring (car argv) 1 2))
978 (kw (symbol->keyword char)))
982 (let* ((rest-car (substring (car argv) 2 (string-length (car argv))))
983 (new-argv (if (= 0 (string-length rest-car))
985 (cons (string-append "-" rest-car) (cdr argv)))))
986 (return kw #f new-argv)))
989 (let* ((rest-car (substring (car argv) 2 (string-length (car argv))))
990 (arg (if (= 0 (string-length rest-car))
993 (new-argv (if (= 0 (string-length rest-car))
996 (return kw arg new-argv)))
998 (else (return 'usage-error kw argv)))))))
1000 (define (for-next-option proc argv kw-opts kw-args)
1001 (let loop ((argv argv))
1002 (get-option argv kw-opts kw-args
1003 (lambda (opt opt-arg argv)
1004 (and opt (proc opt opt-arg argv loop))))))
1006 (define (display-usage-report kw-desc)
1009 (or (eq? (car kw) #t)
1010 (eq? (car kw) 'else)
1011 (let* ((opt-desc kw)
1012 (help (cadr opt-desc))
1013 (opts (car opt-desc))
1014 (opts-proper (if (string? (car opts)) (cdr opts) opts))
1015 (arg-name (if (string? (car opts))
1016 (string-append "<" (car opts) ">")
1018 (left-part (string-append
1019 (with-output-to-string
1021 (map (lambda (x) (display (keyword-symbol x)) (display " "))
1024 (middle-part (if (and (< (string-length left-part) 30)
1025 (< (string-length help) 40))
1026 (make-string (- 30 (string-length left-part)) #\ )
1029 (display middle-part)
1036 (define (transform-usage-lambda cases)
1037 (let* ((raw-usage (delq! 'else (map car cases)))
1038 (usage-sans-specials (map (lambda (x)
1039 (or (and (not (list? x)) x)
1040 (and (symbol? (car x)) #t)
1041 (and (boolean? (car x)) #t)
1044 (usage-desc (delq! #t usage-sans-specials))
1045 (kw-desc (map car usage-desc))
1046 (kw-opts (apply append (map (lambda (x) (and (not (string? (car x))) x)) kw-desc)))
1047 (kw-args (apply append (map (lambda (x) (and (string? (car x)) (cdr x))) kw-desc)))
1048 (transmogrified-cases (map (lambda (case)
1049 (cons (let ((opts (car case)))
1050 (if (or (boolean? opts) (eq? 'else opts))
1053 ((symbol? (car opts)) opts)
1054 ((boolean? (car opts)) opts)
1055 ((string? (caar opts)) (cdar opts))
1056 (else (car opts)))))
1059 `(let ((%display-usage (lambda () (display-usage-report ',usage-desc))))
1061 (let %next-arg ((%argv %argv))
1065 (lambda (%opt %arg %new-argv)
1067 ,@ transmogrified-cases))))))))
1072 ;;; {Low Level Modules}
1074 ;;; These are the low level data structures for modules.
1076 ;;; !!! warning: The interface to lazy binder procedures is going
1077 ;;; to be changed in an incompatible way to permit all the basic
1078 ;;; module ops to be virtualized.
1080 ;;; (make-module size use-list lazy-binding-proc) => module
1081 ;;; module-{obarray,uses,binder}[|-set!]
1082 ;;; (module? obj) => [#t|#f]
1083 ;;; (module-locally-bound? module symbol) => [#t|#f]
1084 ;;; (module-bound? module symbol) => [#t|#f]
1085 ;;; (module-symbol-locally-interned? module symbol) => [#t|#f]
1086 ;;; (module-symbol-interned? module symbol) => [#t|#f]
1087 ;;; (module-local-variable module symbol) => [#<variable ...> | #f]
1088 ;;; (module-variable module symbol) => [#<variable ...> | #f]
1089 ;;; (module-symbol-binding module symbol opt-value)
1090 ;;; => [ <obj> | opt-value | an error occurs ]
1091 ;;; (module-make-local-var! module symbol) => #<variable...>
1092 ;;; (module-add! module symbol var) => unspecified
1093 ;;; (module-remove! module symbol) => unspecified
1094 ;;; (module-for-each proc module) => unspecified
1095 ;;; (make-scm-module) => module ; a lazy copy of the symhash module
1096 ;;; (set-current-module module) => unspecified
1097 ;;; (current-module) => #<module...>
1102 ;;; {Printing Modules}
1103 ;; This is how modules are printed. You can re-define it.
1104 ;; (Redefining is actually more complicated than simply redefining
1105 ;; %print-module because that would only change the binding and not
1106 ;; the value stored in the vtable that determines how record are
1109 (define (%print-module mod port) ; unused args: depth length style table)
1111 (display (or (module-kind mod) "module") port)
1112 (let ((name (module-name mod)))
1116 (display name port))))
1118 (display (number->string (object-address mod) 16) port)
1123 ;; A module is characterized by an obarray in which local symbols
1124 ;; are interned, a list of modules, "uses", from which non-local
1125 ;; bindings can be inherited, and an optional lazy-binder which
1126 ;; is a (CLOSURE module symbol) which, as a last resort, can provide
1127 ;; bindings that would otherwise not be found locally in the module.
1130 (make-record-type 'module
1131 '(obarray uses binder eval-closure transformer name kind
1132 observers weak-observers observer-id)
1135 ;; make-module &opt size uses binder
1137 ;; Create a new module, perhaps with a particular size of obarray,
1138 ;; initial uses list, or binding procedure.
1143 (define (parse-arg index default)
1144 (if (> (length args) index)
1145 (list-ref args index)
1148 (if (> (length args) 3)
1149 (error "Too many args to make-module." args))
1151 (let ((size (parse-arg 0 1021))
1152 (uses (parse-arg 1 '()))
1153 (binder (parse-arg 2 #f)))
1155 (if (not (integer? size))
1156 (error "Illegal size to make-module." size))
1157 (if (not (and (list? uses)
1158 (and-map module? uses)))
1159 (error "Incorrect use list." uses))
1160 (if (and binder (not (procedure? binder)))
1162 "Lazy-binder expected to be a procedure or #f." binder))
1164 (let ((module (module-constructor (make-vector size '())
1165 uses binder #f #f #f #f
1167 (make-weak-value-hash-table 31)
1170 ;; We can't pass this as an argument to module-constructor,
1171 ;; because we need it to close over a pointer to the module
1173 (set-module-eval-closure! module
1174 (lambda (symbol define?)
1176 (module-make-local-var! module symbol)
1177 (module-variable module symbol))))
1181 (define module-constructor (record-constructor module-type))
1182 (define module-obarray (record-accessor module-type 'obarray))
1183 (define set-module-obarray! (record-modifier module-type 'obarray))
1184 (define module-uses (record-accessor module-type 'uses))
1185 (define set-module-uses! (record-modifier module-type 'uses))
1186 (define module-binder (record-accessor module-type 'binder))
1187 (define set-module-binder! (record-modifier module-type 'binder))
1189 ;; NOTE: This binding is used in libguile/modules.c.
1190 (define module-eval-closure (record-accessor module-type 'eval-closure))
1192 (define module-transformer (record-accessor module-type 'transformer))
1193 (define set-module-transformer! (record-modifier module-type 'transformer))
1194 (define module-name (record-accessor module-type 'name))
1195 (define set-module-name! (record-modifier module-type 'name))
1196 (define module-kind (record-accessor module-type 'kind))
1197 (define set-module-kind! (record-modifier module-type 'kind))
1198 (define module-observers (record-accessor module-type 'observers))
1199 (define set-module-observers! (record-modifier module-type 'observers))
1200 (define module-weak-observers (record-accessor module-type 'weak-observers))
1201 (define module-observer-id (record-accessor module-type 'observer-id))
1202 (define set-module-observer-id! (record-modifier module-type 'observer-id))
1203 (define module? (record-predicate module-type))
1205 (define set-module-eval-closure!
1206 (let ((setter (record-modifier module-type 'eval-closure)))
1207 (lambda (module closure)
1208 (setter module closure)
1209 ;; Make it possible to lookup the module from the environment.
1210 ;; This implementation is correct since an eval closure can belong
1211 ;; to maximally one module.
1212 (set-procedure-property! closure 'module module))))
1214 (define (eval-in-module exp module)
1215 (eval2 exp (module-eval-closure module)))
1218 ;;; {Observer protocol}
1221 (define (module-observe module proc)
1222 (set-module-observers! module (cons proc (module-observers module)))
1225 (define (module-observe-weak module proc)
1226 (let ((id (module-observer-id module)))
1227 (hash-set! (module-weak-observers module) id proc)
1228 (set-module-observer-id! module (+ 1 id))
1231 (define (module-unobserve token)
1232 (let ((module (car token))
1235 (hash-remove! (module-weak-observers module) id)
1236 (set-module-observers! module (delq1! id (module-observers module)))))
1239 (define (module-modified m)
1240 (for-each (lambda (proc) (proc m)) (module-observers m))
1241 (hash-fold (lambda (id proc res) (proc m)) #f (module-weak-observers m)))
1244 ;;; {Module Searching in General}
1246 ;;; We sometimes want to look for properties of a symbol
1247 ;;; just within the obarray of one module. If the property
1248 ;;; holds, then it is said to hold ``locally'' as in, ``The symbol
1249 ;;; DISPLAY is locally rebound in the module `safe-guile'.''
1252 ;;; Other times, we want to test for a symbol property in the obarray
1253 ;;; of M and, if it is not found there, try each of the modules in the
1254 ;;; uses list of M. This is the normal way of testing for some
1255 ;;; property, so we state these properties without qualification as
1256 ;;; in: ``The symbol 'fnord is interned in module M because it is
1257 ;;; interned locally in module M2 which is a member of the uses list
1261 ;; module-search fn m
1263 ;; return the first non-#f result of FN applied to M and then to
1264 ;; the modules in the uses of m, and so on recursively. If all applications
1265 ;; return #f, then so does this function.
1267 (define (module-search fn m v)
1270 (or (module-search fn (car pos) v)
1273 (loop (module-uses m))))
1276 ;;; {Is a symbol bound in a module?}
1278 ;;; Symbol S in Module M is bound if S is interned in M and if the binding
1279 ;;; of S in M has been set to some well-defined value.
1282 ;; module-locally-bound? module symbol
1284 ;; Is a symbol bound (interned and defined) locally in a given module?
1286 (define (module-locally-bound? m v)
1287 (let ((var (module-local-variable m v)))
1289 (variable-bound? var))))
1291 ;; module-bound? module symbol
1293 ;; Is a symbol bound (interned and defined) anywhere in a given module
1296 (define (module-bound? m v)
1297 (module-search module-locally-bound? m v))
1299 ;;; {Is a symbol interned in a module?}
1301 ;;; Symbol S in Module M is interned if S occurs in
1302 ;;; of S in M has been set to some well-defined value.
1304 ;;; It is possible to intern a symbol in a module without providing
1305 ;;; an initial binding for the corresponding variable. This is done
1307 ;;; (module-add! module symbol (make-undefined-variable))
1309 ;;; In that case, the symbol is interned in the module, but not
1310 ;;; bound there. The unbound symbol shadows any binding for that
1311 ;;; symbol that might otherwise be inherited from a member of the uses list.
1314 (define (module-obarray-get-handle ob key)
1315 ((if (symbol? key) hashq-get-handle hash-get-handle) ob key))
1317 (define (module-obarray-ref ob key)
1318 ((if (symbol? key) hashq-ref hash-ref) ob key))
1320 (define (module-obarray-set! ob key val)
1321 ((if (symbol? key) hashq-set! hash-set!) ob key val))
1323 (define (module-obarray-remove! ob key)
1324 ((if (symbol? key) hashq-remove! hash-remove!) ob key))
1326 ;; module-symbol-locally-interned? module symbol
1328 ;; is a symbol interned (not neccessarily defined) locally in a given module
1329 ;; or its uses? Interned symbols shadow inherited bindings even if
1330 ;; they are not themselves bound to a defined value.
1332 (define (module-symbol-locally-interned? m v)
1333 (not (not (module-obarray-get-handle (module-obarray m) v))))
1335 ;; module-symbol-interned? module symbol
1337 ;; is a symbol interned (not neccessarily defined) anywhere in a given module
1338 ;; or its uses? Interned symbols shadow inherited bindings even if
1339 ;; they are not themselves bound to a defined value.
1341 (define (module-symbol-interned? m v)
1342 (module-search module-symbol-locally-interned? m v))
1345 ;;; {Mapping modules x symbols --> variables}
1348 ;; module-local-variable module symbol
1349 ;; return the local variable associated with a MODULE and SYMBOL.
1351 ;;; This function is very important. It is the only function that can
1352 ;;; return a variable from a module other than the mutators that store
1353 ;;; new variables in modules. Therefore, this function is the location
1354 ;;; of the "lazy binder" hack.
1356 ;;; If symbol is defined in MODULE, and if the definition binds symbol
1357 ;;; to a variable, return that variable object.
1359 ;;; If the symbols is not found at first, but the module has a lazy binder,
1360 ;;; then try the binder.
1362 ;;; If the symbol is not found at all, return #f.
1364 (define (module-local-variable m v)
1367 (let ((b (module-obarray-ref (module-obarray m) v)))
1368 (or (and (variable? b) b)
1369 (and (module-binder m)
1370 ((module-binder m) m v #f)))))
1373 ;; module-variable module symbol
1375 ;; like module-local-variable, except search the uses in the
1376 ;; case V is not found in M.
1378 (define (module-variable m v)
1379 (module-search module-local-variable m v))
1382 ;;; {Mapping modules x symbols --> bindings}
1384 ;;; These are similar to the mapping to variables, except that the
1385 ;;; variable is dereferenced.
1388 ;; module-symbol-binding module symbol opt-value
1390 ;; return the binding of a variable specified by name within
1391 ;; a given module, signalling an error if the variable is unbound.
1392 ;; If the OPT-VALUE is passed, then instead of signalling an error,
1393 ;; return OPT-VALUE.
1395 (define (module-symbol-local-binding m v . opt-val)
1396 (let ((var (module-local-variable m v)))
1399 (if (not (null? opt-val))
1401 (error "Locally unbound variable." v)))))
1403 ;; module-symbol-binding module symbol opt-value
1405 ;; return the binding of a variable specified by name within
1406 ;; a given module, signalling an error if the variable is unbound.
1407 ;; If the OPT-VALUE is passed, then instead of signalling an error,
1408 ;; return OPT-VALUE.
1410 (define (module-symbol-binding m v . opt-val)
1411 (let ((var (module-variable m v)))
1414 (if (not (null? opt-val))
1416 (error "Unbound variable." v)))))
1420 ;;; {Adding Variables to Modules}
1425 ;; module-make-local-var! module symbol
1427 ;; ensure a variable for V in the local namespace of M.
1428 ;; If no variable was already there, then create a new and uninitialzied
1431 (define (module-make-local-var! m v)
1432 (or (let ((b (module-obarray-ref (module-obarray m) v)))
1437 (and (module-binder m)
1438 ((module-binder m) m v #t))
1440 (let ((answer (make-undefined-variable v)))
1441 (module-obarray-set! (module-obarray m) v answer)
1445 ;; module-add! module symbol var
1447 ;; ensure a particular variable for V in the local namespace of M.
1449 (define (module-add! m v var)
1450 (if (not (variable? var))
1451 (error "Bad variable to module-add!" var))
1452 (module-obarray-set! (module-obarray m) v var)
1453 (module-modified m))
1457 ;; make sure that a symbol is undefined in the local namespace of M.
1459 (define (module-remove! m v)
1460 (module-obarray-remove! (module-obarray m) v)
1461 (module-modified m))
1463 (define (module-clear! m)
1464 (vector-fill! (module-obarray m) '())
1465 (module-modified m))
1467 ;; MODULE-FOR-EACH -- exported
1469 ;; Call PROC on each symbol in MODULE, with arguments of (SYMBOL VARIABLE).
1471 (define (module-for-each proc module)
1472 (let ((obarray (module-obarray module)))
1473 (do ((index 0 (+ index 1))
1474 (end (vector-length obarray)))
1478 (proc (car bucket) (cdr bucket)))
1479 (vector-ref obarray index)))))
1482 (define (module-map proc module)
1483 (let* ((obarray (module-obarray module))
1484 (end (vector-length obarray)))
1492 (map (lambda (bucket)
1493 (proc (car bucket) (cdr bucket)))
1494 (vector-ref obarray i))
1498 ;;; {Low Level Bootstrapping}
1503 ;; A root module uses the symhash table (the system's privileged
1504 ;; obarray). Being inside a root module is like using SCM without
1505 ;; any module system.
1509 (define (root-module-closure m s define?)
1510 (let ((bi (and (symbol-interned? #f s)
1511 (builtin-variable s))))
1513 (or define? (variable-bound? bi))
1515 (module-add! m s bi)
1518 (define (make-root-module)
1519 (make-module 1019 '() root-module-closure))
1524 ;; An scm module is a module into which the lazy binder copies
1525 ;; variable bindings from the system symhash table. The mapping is
1526 ;; one way only; newly introduced bindings in an scm module are not
1527 ;; copied back into the system symhash table (and can be used to override
1528 ;; bindings from the symhash table).
1531 (define (make-scm-module)
1532 (make-module 1019 '()
1533 (lambda (m s define?)
1534 (let ((bi (and (symbol-interned? #f s)
1535 (builtin-variable s))))
1537 (variable-bound? bi)
1539 (module-add! m s bi)
1547 ;; NOTE: This binding is used in libguile/modules.c.
1549 (define the-module #f)
1551 ;; scm:eval-transformer
1553 (define scm:eval-transformer #f)
1555 ;; set-current-module module
1557 ;; set the current module as viewed by the normalizer.
1559 ;; NOTE: This binding is used in libguile/modules.c.
1561 (define (set-current-module m)
1565 (set! *top-level-lookup-closure* (module-eval-closure the-module))
1566 (set! scm:eval-transformer (module-transformer the-module)))
1567 (set! *top-level-lookup-closure* #f)))
1572 ;; return the current module as viewed by the normalizer.
1574 (define (current-module) the-module)
1576 ;;; {Module-based Loading}
1579 (define (save-module-excursion thunk)
1580 (let ((inner-module (current-module))
1582 (dynamic-wind (lambda ()
1583 (set! outer-module (current-module))
1584 (set-current-module inner-module)
1585 (set! inner-module #f))
1588 (set! inner-module (current-module))
1589 (set-current-module outer-module)
1590 (set! outer-module #f)))))
1592 (define basic-load load)
1594 (define (load-module filename)
1595 (save-module-excursion
1597 (let ((oldname (and (current-load-port)
1598 (port-filename (current-load-port)))))
1599 (basic-load (if (and oldname
1600 (> (string-length filename) 0)
1601 (not (char=? (string-ref filename 0) #\/))
1602 (not (string=? (dirname oldname) ".")))
1603 (string-append (dirname oldname) "/" filename)
1608 ;;; {MODULE-REF -- exported}
1610 ;; Returns the value of a variable called NAME in MODULE or any of its
1611 ;; used modules. If there is no such variable, then if the optional third
1612 ;; argument DEFAULT is present, it is returned; otherwise an error is signaled.
1614 (define (module-ref module name . rest)
1615 (let ((variable (module-variable module name)))
1616 (if (and variable (variable-bound? variable))
1617 (variable-ref variable)
1619 (error "No variable named" name 'in module)
1620 (car rest) ; default value
1623 ;; MODULE-SET! -- exported
1625 ;; Sets the variable called NAME in MODULE (or in a module that MODULE uses)
1626 ;; to VALUE; if there is no such variable, an error is signaled.
1628 (define (module-set! module name value)
1629 (let ((variable (module-variable module name)))
1631 (variable-set! variable value)
1632 (error "No variable named" name 'in module))))
1634 ;; MODULE-DEFINE! -- exported
1636 ;; Sets the variable called NAME in MODULE to VALUE; if there is no such
1637 ;; variable, it is added first.
1639 (define (module-define! module name value)
1640 (let ((variable (module-local-variable module name)))
1643 (variable-set! variable value)
1644 (module-modified module))
1645 (module-add! module name (make-variable value name)))))
1647 ;; MODULE-DEFINED? -- exported
1649 ;; Return #t iff NAME is defined in MODULE (or in a module that MODULE
1652 (define (module-defined? module name)
1653 (let ((variable (module-variable module name)))
1654 (and variable (variable-bound? variable))))
1656 ;; MODULE-USE! module interface
1658 ;; Add INTERFACE to the list of interfaces used by MODULE.
1660 (define (module-use! module interface)
1661 (set-module-uses! module
1662 (cons interface (delq! interface (module-uses module))))
1663 (module-modified module))
1666 ;;; {Recursive Namespaces}
1669 ;;; A hierarchical namespace emerges if we consider some module to be
1670 ;;; root, and variables bound to modules as nested namespaces.
1672 ;;; The routines in this file manage variable names in hierarchical namespace.
1673 ;;; Each variable name is a list of elements, looked up in successively nested
1676 ;;; (nested-ref some-root-module '(foo bar baz))
1677 ;;; => <value of a variable named baz in the module bound to bar in
1678 ;;; the module bound to foo in some-root-module>
1683 ;;; ;; a-root is a module
1684 ;;; ;; name is a list of symbols
1686 ;;; nested-ref a-root name
1687 ;;; nested-set! a-root name val
1688 ;;; nested-define! a-root name val
1689 ;;; nested-remove! a-root name
1692 ;;; (current-module) is a natural choice for a-root so for convenience there are
1695 ;;; local-ref name == nested-ref (current-module) name
1696 ;;; local-set! name val == nested-set! (current-module) name val
1697 ;;; local-define! name val == nested-define! (current-module) name val
1698 ;;; local-remove! name == nested-remove! (current-module) name
1702 (define (nested-ref root names)
1703 (let loop ((cur root)
1707 ((not (module? cur)) #f)
1708 (else (loop (module-ref cur (car elts) #f) (cdr elts))))))
1710 (define (nested-set! root names val)
1711 (let loop ((cur root)
1713 (if (null? (cdr elts))
1714 (module-set! cur (car elts) val)
1715 (loop (module-ref cur (car elts)) (cdr elts)))))
1717 (define (nested-define! root names val)
1718 (let loop ((cur root)
1720 (if (null? (cdr elts))
1721 (module-define! cur (car elts) val)
1722 (loop (module-ref cur (car elts)) (cdr elts)))))
1724 (define (nested-remove! root names)
1725 (let loop ((cur root)
1727 (if (null? (cdr elts))
1728 (module-remove! cur (car elts))
1729 (loop (module-ref cur (car elts)) (cdr elts)))))
1731 (define (local-ref names) (nested-ref (current-module) names))
1732 (define (local-set! names val) (nested-set! (current-module) names val))
1733 (define (local-define names val) (nested-define! (current-module) names val))
1734 (define (local-remove names) (nested-remove! (current-module) names))
1738 ;;; {The (app) module}
1740 ;;; The root of conventionally named objects not directly in the top level.
1743 ;;; (app modules guile)
1745 ;;; The directory of all modules and the standard root module.
1748 (define (module-public-interface m)
1749 (module-ref m '%module-public-interface #f))
1750 (define (set-module-public-interface! m i)
1751 (module-define! m '%module-public-interface i))
1752 (define (set-system-module! m s)
1753 (set-procedure-property! (module-eval-closure m) 'system-module s))
1754 (define the-root-module (make-root-module))
1755 (define the-scm-module (make-scm-module))
1756 (set-module-public-interface! the-root-module the-scm-module)
1757 (set-module-name! the-root-module 'the-root-module)
1758 (set-module-name! the-scm-module 'the-scm-module)
1759 (for-each set-system-module! (list the-root-module the-scm-module) '(#t #t))
1761 (set-current-module the-root-module)
1763 (define app (make-module 31))
1764 (local-define '(app modules) (make-module 31))
1765 (local-define '(app modules guile) the-root-module)
1767 ;; (define-special-value '(app modules new-ws) (lambda () (make-scm-module)))
1769 (define (try-load-module name)
1770 (or (try-module-linked name)
1771 (try-module-autoload name)
1772 (try-module-dynamic-link name)))
1774 ;; NOTE: This binding is used in libguile/modules.c.
1776 (define (resolve-module name . maybe-autoload)
1777 (let ((full-name (append '(app modules) name)))
1778 (let ((already (local-ref full-name)))
1780 ;; The module already exists...
1781 (if (and (or (null? maybe-autoload) (car maybe-autoload))
1782 (not (module-ref already '%module-public-interface #f)))
1783 ;; ...but we are told to load and it doesn't contain source, so
1785 (try-load-module name)
1787 ;; simply return it.
1790 ;; Try to autoload it if we are told so
1791 (if (or (null? maybe-autoload) (car maybe-autoload))
1792 (try-load-module name))
1794 (make-modules-in (current-module) full-name))))))
1796 (define (beautify-user-module! module)
1797 (let ((interface (module-public-interface module)))
1798 (if (or (not interface)
1799 (eq? interface module))
1800 (let ((interface (make-module 31)))
1801 (set-module-name! interface (module-name module))
1802 (set-module-kind! interface 'interface)
1803 (set-module-public-interface! module interface))))
1804 (if (and (not (memq the-scm-module (module-uses module)))
1805 (not (eq? module the-root-module)))
1806 (set-module-uses! module (append (module-uses module) (list the-scm-module)))))
1808 ;; NOTE: This binding is used in libguile/modules.c.
1810 (define (make-modules-in module name)
1814 ((module-ref module (car name) #f)
1815 => (lambda (m) (make-modules-in m (cdr name))))
1816 (else (let ((m (make-module 31)))
1817 (set-module-kind! m 'directory)
1818 (set-module-name! m (car name))
1819 (module-define! module (car name) m)
1820 (make-modules-in m (cdr name)))))))
1822 (define (resolve-interface name)
1823 (let ((module (resolve-module name)))
1824 (and module (module-public-interface module))))
1827 (define %autoloader-developer-mode #t)
1829 (define (process-define-module args)
1830 (let* ((module-id (car args))
1831 (module (resolve-module module-id #f))
1833 (beautify-user-module! module)
1834 (let loop ((kws kws)
1835 (reversed-interfaces '()))
1837 (for-each (lambda (interface)
1838 (module-use! module interface))
1839 reversed-interfaces)
1840 (let ((keyword (cond ((keyword? (car kws))
1841 (keyword->symbol (car kws)))
1842 ((and (symbol? (car kws))
1843 (eq? (string-ref (car kws) 0) #\:))
1844 (string->symbol (substring (car kws) 1)))
1847 ((use-module use-syntax)
1848 (if (not (pair? (cdr kws)))
1849 (error "unrecognized defmodule argument" kws))
1850 (let* ((used-name (cadr kws))
1851 (used-module (resolve-module used-name)))
1852 (if (not (module-ref used-module
1853 '%module-public-interface
1856 ((if %autoloader-developer-mode warn error)
1857 "no code for module" (module-name used-module))
1858 (beautify-user-module! used-module)))
1859 (let ((interface (module-public-interface used-module)))
1861 (error "missing interface for use-module"
1863 (if (eq? keyword 'use-syntax)
1864 (set-module-transformer!
1866 (module-ref interface (car (last-pair used-name))
1869 (cons interface reversed-interfaces)))))
1871 (if (not (and (pair? (cdr kws)) (pair? (cddr kws))))
1872 (error "unrecognized defmodule argument" kws))
1874 (cons (make-autoload-interface module
1877 reversed-interfaces)))
1879 (set-system-module! module #t)
1880 (loop (cdr kws) reversed-interfaces))
1882 (error "unrecognized defmodule argument" kws))))))
1887 (define (make-autoload-interface module name bindings)
1888 (let ((b (lambda (a sym definep)
1889 (and (memq sym bindings)
1890 (let ((i (module-public-interface (resolve-module name))))
1892 (error "missing interface for module" name))
1893 ;; Replace autoload-interface with interface
1894 (set-car! (memq a (module-uses module)) i)
1895 (module-local-variable i sym))))))
1896 (module-constructor #() #f b #f #f name 'autoload
1897 '() (make-weak-value-hash-table 31) 0)))
1900 ;;; {Autoloading modules}
1902 (define autoloads-in-progress '())
1904 (define (try-module-autoload module-name)
1906 (define (sfx name) (string-append name (scheme-file-suffix)))
1907 (let* ((reverse-name (reverse module-name))
1908 (name (car reverse-name))
1909 (dir-hint-module-name (reverse (cdr reverse-name)))
1910 (dir-hint (apply symbol-append (map (lambda (elt) (symbol-append elt "/")) dir-hint-module-name))))
1911 (resolve-module dir-hint-module-name #f)
1912 (and (not (autoload-done-or-in-progress? dir-hint name))
1915 (lambda () (autoload-in-progress! dir-hint name))
1917 (let ((full (%search-load-path (in-vicinity dir-hint name))))
1920 (save-module-excursion (lambda () (primitive-load full)))
1922 (lambda () (set-autoloaded! dir-hint name didit)))
1926 ;;; Dynamic linking of modules
1928 ;; Initializing a module that is written in C is a two step process.
1929 ;; First the module's `module init' function is called. This function
1930 ;; is expected to call `scm_register_module_xxx' to register the `real
1931 ;; init' function. Later, when the module is referenced for the first
1932 ;; time, this real init function is called in the right context. See
1933 ;; gtcltk-lib/gtcltk-module.c for an example.
1935 ;; The code for the module can be in a regular shared library (so that
1936 ;; the `module init' function will be called when libguile is
1937 ;; initialized). Or it can be dynamically linked.
1939 ;; You can safely call `scm_register_module_xxx' before libguile
1940 ;; itself is initialized. You could call it from an C++ constructor
1941 ;; of a static object, for example.
1943 ;; To make your Guile extension into a dynamic linkable module, follow
1944 ;; these easy steps:
1946 ;; - Find a name for your module, like (ice-9 gtcltk)
1947 ;; - Write a function with a name like
1949 ;; scm_init_ice_9_gtcltk_module
1951 ;; This is your `module init' function. It should call
1953 ;; scm_register_module_xxx ("ice-9 gtcltk", scm_init_gtcltk);
1955 ;; "ice-9 gtcltk" is the C version of the module name. Slashes are
1956 ;; replaced by spaces, the rest is untouched. `scm_init_gtcltk' is
1957 ;; the real init function that executes the usual initializations
1958 ;; like making new smobs, etc.
1960 ;; - Make a shared library with your code and a name like
1962 ;; ice-9/libgtcltk.so
1964 ;; and put it somewhere in %load-path.
1966 ;; - Then you can simply write `:use-module (ice-9 gtcltk)' and it
1967 ;; will be linked automatically.
1969 ;; This is all very experimental.
1971 (define (split-c-module-name str)
1972 (let loop ((rev '())
1975 (end (string-length str)))
1978 (reverse (cons (string->symbol (substring str start pos)) rev)))
1979 ((eq? (string-ref str pos) #\space)
1980 (loop (cons (string->symbol (substring str start pos)) rev)
1985 (loop rev start (+ pos 1) end)))))
1987 (define (convert-c-registered-modules dynobj)
1988 (let ((res (map (lambda (c)
1989 (list (split-c-module-name (car c)) (cdr c) dynobj))
1990 (c-registered-modules))))
1991 (c-clear-registered-modules)
1994 (define registered-modules '())
1996 (define (register-modules dynobj)
1997 (set! registered-modules
1998 (append! (convert-c-registered-modules dynobj)
1999 registered-modules)))
2001 (define (init-dynamic-module modname)
2002 ;; Register any linked modules which has been registered on the C level
2003 (register-modules #f)
2004 (or-map (lambda (modinfo)
2005 (if (equal? (car modinfo) modname)
2007 (set! registered-modules (delq! modinfo registered-modules))
2008 (let ((mod (resolve-module modname #f)))
2009 (save-module-excursion
2011 (set-current-module mod)
2012 (set-module-public-interface! mod mod)
2013 (dynamic-call (cadr modinfo) (caddr modinfo))
2017 registered-modules))
2019 (define (dynamic-maybe-call name dynobj)
2020 (catch #t ; could use false-if-exception here
2022 (dynamic-call name dynobj))
2026 (define (dynamic-maybe-link filename)
2027 (catch #t ; could use false-if-exception here
2029 (dynamic-link filename))
2033 (define (find-and-link-dynamic-module module-name)
2034 (define (make-init-name mod-name)
2035 (string-append 'scm_init
2036 (list->string (map (lambda (c)
2037 (if (or (char-alphabetic? c)
2041 (string->list mod-name)))
2044 ;; Put the subdirectory for this module in the car of SUBDIR-AND-LIBNAME,
2045 ;; and the `libname' (the name of the module prepended by `lib') in the cdr
2046 ;; field. For example, if MODULE-NAME is the list (inet tcp-ip udp), then
2047 ;; SUBDIR-AND-LIBNAME will be the pair ("inet/tcp-ip" . "libudp").
2048 (let ((subdir-and-libname
2049 (let loop ((dirs "")
2051 (if (null? (cdr syms))
2052 (cons dirs (string-append "lib" (car syms)))
2053 (loop (string-append dirs (car syms) "/") (cdr syms)))))
2054 (init (make-init-name (apply string-append
2056 (string-append "_" s))
2058 (let ((subdir (car subdir-and-libname))
2059 (libname (cdr subdir-and-libname)))
2061 ;; Now look in each dir in %LOAD-PATH for `subdir/libfoo.la'. If that
2062 ;; file exists, fetch the dlname from that file and attempt to link
2063 ;; against it. If `subdir/libfoo.la' does not exist, or does not seem
2064 ;; to name any shared library, look for `subdir/libfoo.so' instead and
2065 ;; link against that.
2066 (let check-dirs ((dir-list %load-path))
2067 (if (null? dir-list)
2069 (let* ((dir (in-vicinity (car dir-list) subdir))
2071 (or (try-using-libtool-name dir libname)
2072 (try-using-sharlib-name dir libname))))
2073 (if (and sharlib-full (file-exists? sharlib-full))
2074 (link-dynamic-module sharlib-full init)
2075 (check-dirs (cdr dir-list)))))))))
2077 (define (try-using-libtool-name libdir libname)
2078 (let ((libtool-filename (in-vicinity libdir
2079 (string-append libname ".la"))))
2080 (and (file-exists? libtool-filename)
2081 (with-input-from-file libtool-filename
2083 (let loop ((ln (read-line)))
2084 (cond ((eof-object? ln) #f)
2085 ((and (> (string-length ln) 9)
2086 (string=? "dlname='" (substring ln 0 8))
2087 (string-index ln #\' 8))
2090 (in-vicinity libdir (substring ln 8 end))))
2091 (else (loop (read-line))))))))))
2093 (define (try-using-sharlib-name libdir libname)
2094 (in-vicinity libdir (string-append libname ".so")))
2096 (define (link-dynamic-module filename initname)
2097 ;; Register any linked modules which has been registered on the C level
2098 (register-modules #f)
2099 (let ((dynobj (dynamic-link filename)))
2100 (dynamic-call initname dynobj)
2101 (register-modules dynobj)))
2103 (define (try-module-linked module-name)
2104 (init-dynamic-module module-name))
2106 (define (try-module-dynamic-link module-name)
2107 (and (find-and-link-dynamic-module module-name)
2108 (init-dynamic-module module-name)))
2112 (define autoloads-done '((guile . guile)))
2114 (define (autoload-done-or-in-progress? p m)
2115 (let ((n (cons p m)))
2116 (->bool (or (member n autoloads-done)
2117 (member n autoloads-in-progress)))))
2119 (define (autoload-done! p m)
2120 (let ((n (cons p m)))
2121 (set! autoloads-in-progress
2122 (delete! n autoloads-in-progress))
2123 (or (member n autoloads-done)
2124 (set! autoloads-done (cons n autoloads-done)))))
2126 (define (autoload-in-progress! p m)
2127 (let ((n (cons p m)))
2128 (set! autoloads-done
2129 (delete! n autoloads-done))
2130 (set! autoloads-in-progress (cons n autoloads-in-progress))))
2132 (define (set-autoloaded! p m done?)
2134 (autoload-done! p m)
2135 (let ((n (cons p m)))
2136 (set! autoloads-done (delete! n autoloads-done))
2137 (set! autoloads-in-progress (delete! n autoloads-in-progress)))))
2146 (define (primitive-macro? m)
2148 (not (macro-transformer m))))
2152 (define macro-table (make-weak-key-hash-table 523))
2153 (define xformer-table (make-weak-key-hash-table 523))
2155 (define (defmacro? m) (hashq-ref macro-table m))
2156 (define (assert-defmacro?! m) (hashq-set! macro-table m #t))
2157 (define (defmacro-transformer m) (hashq-ref xformer-table m))
2158 (define (set-defmacro-transformer! m t) (hashq-set! xformer-table m t))
2160 (define defmacro:transformer
2162 (let* ((xform (lambda (exp env)
2163 (copy-tree (apply f (cdr exp)))))
2164 (a (procedure->memoizing-macro xform)))
2165 (assert-defmacro?! a)
2166 (set-defmacro-transformer! a f)
2171 (let ((defmacro-transformer
2172 (lambda (name parms . body)
2173 (let ((transformer `(lambda ,parms ,@body)))
2175 (,(lambda (transformer)
2176 (defmacro:transformer transformer))
2178 (defmacro:transformer defmacro-transformer)))
2180 (define defmacro:syntax-transformer
2184 (copy-tree (apply f (cdr exp)))))))
2187 ;; XXX - should the definition of the car really be looked up in the
2190 (define (macroexpand-1 e)
2192 ((pair? e) (let* ((a (car e))
2193 (val (and (symbol? a) (local-ref (list a)))))
2195 (apply (defmacro-transformer val) (cdr e))
2199 (define (macroexpand e)
2201 ((pair? e) (let* ((a (car e))
2202 (val (and (symbol? a) (local-ref (list a)))))
2204 (macroexpand (apply (defmacro-transformer val) (cdr e)))
2215 ;;; {Run-time options}
2217 ((let* ((names '((eval-options-interface
2218 (eval-options eval-enable eval-disable)
2221 (debug-options-interface
2222 (debug-options debug-enable debug-disable)
2225 (evaluator-traps-interface
2226 (traps trap-enable trap-disable)
2229 (read-options-interface
2230 (read-options read-enable read-disable)
2233 (print-options-interface
2234 (print-options print-enable print-disable)
2237 (readline-options-interface
2238 (readline-options readline-enable readline-disable)
2243 (option-documentation caddr)
2245 (print-option (lambda (option)
2246 (display (option-name option))
2247 (if (< (string-length
2248 (symbol->string (option-name option)))
2252 (display (option-value option))
2254 (display (option-documentation option))
2257 ;; Below follows the macros defining the run-time option interfaces.
2259 (make-options (lambda (interface)
2261 (cond ((null? args) (,interface))
2263 (,interface (car args)) (,interface))
2264 (else (for-each ,print-option
2265 (,interface #t)))))))
2267 (make-enable (lambda (interface)
2269 (,interface (append flags (,interface)))
2272 (make-disable (lambda (interface)
2274 (let ((options (,interface)))
2275 (for-each (lambda (flag)
2276 (set! options (delq! flag options)))
2278 (,interface options)
2281 (make-set! (lambda (interface)
2284 (begin (,interface (append (,interface)
2285 (list '(,'unquote name)
2293 (map (lambda (group)
2294 (let ((interface (car group)))
2295 (append (map (lambda (name constructor)
2297 ,(constructor interface)))
2302 (map (lambda (name constructor)
2304 ,@(constructor interface)))
2306 (list make-set!)))))
2314 (define (repl read evaler print)
2315 (let loop ((source (read (current-input-port))))
2316 (print (evaler source))
2317 (loop (read (current-input-port)))))
2319 ;; A provisional repl that acts like the SCM repl:
2321 (define scm-repl-silent #f)
2322 (define (assert-repl-silence v) (set! scm-repl-silent v))
2324 (define *unspecified* (if #f #f))
2325 (define (unspecified? v) (eq? v *unspecified*))
2327 (define scm-repl-print-unspecified #f)
2328 (define (assert-repl-print-unspecified v) (set! scm-repl-print-unspecified v))
2330 (define scm-repl-verbose #f)
2331 (define (assert-repl-verbosity v) (set! scm-repl-verbose v))
2333 (define scm-repl-prompt "guile> ")
2335 (define (set-repl-prompt! v) (set! scm-repl-prompt v))
2337 (define (default-lazy-handler key . args)
2338 (save-stack lazy-handler-dispatch)
2339 (apply throw key args))
2341 (define enter-frame-handler default-lazy-handler)
2342 (define apply-frame-handler default-lazy-handler)
2343 (define exit-frame-handler default-lazy-handler)
2345 (define (lazy-handler-dispatch key . args)
2348 (apply apply-frame-handler key args))
2350 (apply exit-frame-handler key args))
2352 (apply enter-frame-handler key args))
2354 (apply default-lazy-handler key args))))
2356 (define abort-hook (make-hook))
2358 ;; these definitions are used if running a script.
2359 ;; otherwise redefined in error-catching-loop.
2360 (define (set-batch-mode?! arg) #t)
2361 (define (batch-mode?) #t)
2363 (define (error-catching-loop thunk)
2366 (define (loop first)
2374 (lambda () (unmask-signals))
2380 ;; This line is needed because mark
2381 ;; doesn't do closures quite right.
2382 ;; Unreferenced locals should be
2386 (let loop ((v (thunk)))
2389 (lambda () (mask-signals))))
2391 lazy-handler-dispatch))
2393 (lambda (key . args)
2400 (apply throw 'switch-repl args))
2403 ;; This is one of the closures that require
2404 ;; (set! first #f) above
2407 (run-hook abort-hook)
2408 (force-output (current-output-port))
2409 (display "ABORT: " (current-error-port))
2410 (write args (current-error-port))
2411 (newline (current-error-port))
2415 (not has-shown-debugger-hint?)
2416 (not (memq 'backtrace
2417 (debug-options-interface)))
2418 (stack? (fluid-ref the-last-stack)))
2420 (newline (current-error-port))
2422 "Type \"(backtrace)\" to get more information.\n"
2423 (current-error-port))
2424 (set! has-shown-debugger-hint? #t)))
2425 (force-output (current-error-port)))
2427 (primitive-exit 1)))
2428 (set! stack-saved? #f)))
2431 ;; This is the other cons-leak closure...
2433 (cond ((= (length args) 4)
2434 (apply handle-system-error key args))
2436 (apply bad-throw key args))))))))))
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 (loop (lambda () #t))))
2447 ;;(define the-last-stack (make-fluid)) Defined by scm_init_backtrace ()
2448 (define before-signal-stack (make-fluid))
2449 (define stack-saved? #f)
2451 (define (save-stack . narrowing)
2453 (cond ((not (memq 'debug (debug-options-interface)))
2454 (fluid-set! the-last-stack #f)
2455 (set! stack-saved? #t))
2461 (apply make-stack #t save-stack eval #t 0 narrowing))
2463 (apply make-stack #t save-stack 0 #t 0 narrowing))
2465 (apply make-stack #t save-stack tk-stack-mark #t 0 narrowing))
2467 (apply make-stack #t save-stack 0 1 narrowing))
2469 (let ((id (stack-id #t)))
2470 (and (procedure? id)
2471 (apply make-stack #t save-stack id #t 0 narrowing))))))
2472 (set! stack-saved? #t)))))
2474 (define before-error-hook (make-hook))
2475 (define after-error-hook (make-hook))
2476 (define before-backtrace-hook (make-hook))
2477 (define after-backtrace-hook (make-hook))
2479 (define has-shown-debugger-hint? #f)
2481 (define (handle-system-error key . args)
2482 (let ((cep (current-error-port)))
2483 (cond ((not (stack? (fluid-ref the-last-stack))))
2484 ((memq 'backtrace (debug-options-interface))
2485 (run-hook before-backtrace-hook)
2487 (display "Backtrace:\n")
2488 (display-backtrace (fluid-ref the-last-stack) cep)
2490 (run-hook after-backtrace-hook)))
2491 (run-hook before-error-hook)
2492 (apply display-error (fluid-ref the-last-stack) cep args)
2493 (run-hook after-error-hook)
2495 (throw 'abort key)))
2497 (define (quit . args)
2498 (apply throw 'quit args))
2502 ;;(define has-shown-backtrace-hint? #f) Defined by scm_init_backtrace ()
2504 ;; Replaced by C code:
2505 ;;(define (backtrace)
2506 ;; (if (fluid-ref the-last-stack)
2509 ;; (display-backtrace (fluid-ref the-last-stack) (current-output-port))
2511 ;; (if (and (not has-shown-backtrace-hint?)
2512 ;; (not (memq 'backtrace (debug-options-interface))))
2515 ;;"Type \"(debug-enable 'backtrace)\" if you would like a backtrace
2516 ;;automatically if an error occurs in the future.\n")
2517 ;; (set! has-shown-backtrace-hint? #t))))
2518 ;; (display "No backtrace available.\n")))
2520 (define (error-catching-repl r e p)
2521 (error-catching-loop (lambda () (p (e (r))))))
2523 (define (gc-run-time)
2524 (cdr (assq 'gc-time-taken (gc-stats))))
2526 (define before-read-hook (make-hook))
2527 (define after-read-hook (make-hook))
2529 ;;; The default repl-reader function. We may override this if we've
2530 ;;; the readline library.
2535 (run-hook before-read-hook)
2536 (read (current-input-port))))
2538 (define (scm-style-repl)
2542 (repl-report-start-timing (lambda ()
2543 (set! start-gc-rt (gc-run-time))
2544 (set! start-rt (get-internal-run-time))))
2545 (repl-report (lambda ()
2547 (display (inexact->exact
2548 (* 1000 (/ (- (get-internal-run-time) start-rt)
2549 internal-time-units-per-second))))
2551 (display (inexact->exact
2552 (* 1000 (/ (- (gc-run-time) start-gc-rt)
2553 internal-time-units-per-second))))
2554 (display " msec in gc)\n")))
2556 (consume-trailing-whitespace
2558 (let ((ch (peek-char)))
2561 ((or (char=? ch #\space) (char=? ch #\tab))
2563 (consume-trailing-whitespace))
2564 ((char=? ch #\newline)
2568 (let ((prompt (cond ((string? scm-repl-prompt)
2570 ((thunk? scm-repl-prompt)
2572 (scm-repl-prompt "> ")
2574 (repl-reader prompt))))
2576 ;; As described in R4RS, the READ procedure updates the
2577 ;; port to point to the first character past the end of
2578 ;; the external representation of the object. This
2579 ;; means that it doesn't consume the newline typically
2580 ;; found after an expression. This means that, when
2581 ;; debugging Guile with GDB, GDB gets the newline, which
2582 ;; it often interprets as a "continue" command, making
2583 ;; breakpoints kind of useless. So, consume any
2584 ;; trailing newline here, as well as any whitespace
2586 ;; But not if EOF, for control-D.
2587 (if (not (eof-object? val))
2588 (consume-trailing-whitespace))
2589 (run-hook after-read-hook)
2590 (if (eof-object? val)
2592 (repl-report-start-timing)
2593 (if scm-repl-verbose
2596 (display ";;; EOF -- quitting")
2601 (-eval (lambda (sourc)
2602 (repl-report-start-timing)
2603 (start-stack 'repl-stack (eval sourc))))
2605 (-print (lambda (result)
2606 (if (not scm-repl-silent)
2608 (if (or scm-repl-print-unspecified
2609 (not (unspecified? result)))
2613 (if scm-repl-verbose
2617 (-quit (lambda (args)
2618 (if scm-repl-verbose
2620 (display ";;; QUIT executed, repl exitting")
2626 (if scm-repl-verbose
2628 (display ";;; ABORT executed.")
2631 (repl -read -eval -print))))
2633 (let ((status (error-catching-repl -read
2640 ;;; {IOTA functions: generating lists of numbers}
2643 (let loop ((count (1- n)) (result '()))
2644 (if (< count 0) result
2645 (loop (1- count) (cons count result)))))
2650 ;;; with `continue' and `break'.
2653 (defmacro while (cond . body)
2654 `(letrec ((continue (lambda () (or (not ,cond) (begin (begin ,@ body) (continue)))))
2655 (break (lambda val (apply throw 'break val))))
2657 (lambda () (continue))
2658 (lambda v (cadr v)))))
2662 ;;; Similar to `begin' but returns a list of the results of all constituent
2663 ;;; forms instead of the result of the last form.
2664 ;;; (The definition relies on the current left-to-right
2665 ;;; order of evaluation of operands in applications.)
2667 (defmacro collect forms
2672 ;; with-fluids is a convenience wrapper for the builtin procedure
2673 ;; `with-fluids*'. The syntax is just like `let':
2675 ;; (with-fluids ((fluid val)
2679 (defmacro with-fluids (bindings . body)
2680 `(with-fluids* (list ,@(map car bindings)) (list ,@(map cadr bindings))
2681 (lambda () ,@body)))
2685 (define the-environment
2690 (define (environment-module env)
2691 (let ((closure (and (pair? env) (car (last-pair env)))))
2692 (and closure (procedure-property closure 'module))))
2699 ;; actually....hobbit might be able to hack these with a little
2703 (defmacro define-macro (first . rest)
2704 (let ((name (if (symbol? first) first (car first)))
2708 `(lambda ,(cdr first) ,@rest))))
2709 `(define ,name (defmacro:transformer ,transformer))))
2712 (defmacro define-syntax-macro (first . rest)
2713 (let ((name (if (symbol? first) first (car first)))
2717 `(lambda ,(cdr first) ,@rest))))
2718 `(define ,name (defmacro:syntax-transformer ,transformer))))
2720 ;;; {Module System Macros}
2723 (defmacro define-module args
2724 `(let* ((process-define-module process-define-module)
2725 (set-current-module set-current-module)
2726 (module (process-define-module ',args)))
2727 (set-current-module module)
2730 ;; the guts of the use-modules macro. add the interfaces of the named
2731 ;; modules to the use-list of the current module, in order
2732 (define (process-use-modules module-names)
2733 (for-each (lambda (module-name)
2734 (let ((mod-iface (resolve-interface module-name)))
2736 (error "no such module" module-name))
2737 (module-use! (current-module) mod-iface)))
2738 (reverse module-names)))
2740 (defmacro use-modules modules
2741 `(process-use-modules ',modules))
2743 (defmacro use-syntax (spec)
2746 `((process-use-modules ',(list spec))
2747 (set-module-transformer! (current-module)
2748 ,(car (last-pair spec))))
2749 `((set-module-transformer! (current-module) ,spec)))
2750 (set! scm:eval-transformer (module-transformer (current-module)))))
2752 (define define-private define)
2754 (defmacro define-public args
2756 (error "bad syntax" (list 'define-public args)))
2757 (define (defined-name n)
2760 ((pair? n) (defined-name (car n)))
2763 ((null? args) (syntax))
2765 (#t (let ((name (defined-name (car args))))
2767 (let ((public-i (module-public-interface (current-module))))
2768 ;; Make sure there is a local variable:
2770 (module-define! (current-module)
2772 (module-ref (current-module) ',name #f))
2774 ;; Make sure that local is exported:
2776 (module-add! public-i ',name
2777 (module-variable (current-module) ',name)))
2779 ;; Now (re)define the var normally. Bernard URBAN
2780 ;; suggests we use eval here to accomodate Hobbit; it lets
2781 ;; the interpreter handle the define-private form, which
2782 ;; Hobbit can't digest.
2783 (eval '(define-private ,@ args)))))))
2787 (defmacro defmacro-public args
2789 (error "bad syntax" (list 'defmacro-public args)))
2790 (define (defined-name n)
2795 ((null? args) (syntax))
2797 (#t (let ((name (defined-name (car args))))
2799 (let ((public-i (module-public-interface (current-module))))
2800 ;; Make sure there is a local variable:
2802 (module-define! (current-module)
2804 (module-ref (current-module) ',name #f))
2806 ;; Make sure that local is exported:
2808 (module-add! public-i ',name (module-variable (current-module) ',name)))
2810 ;; Now (re)define the var normally.
2812 (defmacro ,@ args))))))
2815 (defmacro export names
2816 `(let* ((m (current-module))
2817 (public-i (module-public-interface m)))
2818 (for-each (lambda (name)
2819 ;; Make sure there is a local variable:
2820 (module-define! m name (module-ref m name #f))
2821 ;; Make sure that local is exported:
2822 (module-add! public-i name (module-variable m name)))
2825 (define export-syntax export)
2830 (define load load-module)
2834 ;;; {Load emacs interface support if emacs option is given.}
2836 (define (load-emacs-interface)
2837 (if (memq 'debug-extensions *features*)
2838 (debug-enable 'backtrace))
2839 (define-module (guile-user) :use-module (ice-9 emacs)))
2843 (define using-readline?
2844 (let ((using-readline? (make-fluid)))
2845 (make-procedure-with-setter
2846 (lambda () (fluid-ref using-readline?))
2847 (lambda (v) (fluid-set! using-readline? v)))))
2849 ;; this is just (scm-style-repl) with a wrapper to install and remove
2853 ;; Load emacs interface support if emacs option is given.
2854 (if (and (module-defined? the-root-module 'use-emacs-interface)
2855 use-emacs-interface)
2856 (load-emacs-interface))
2858 ;; Place the user in the guile-user module.
2859 (define-module (guile-user)
2860 :use-module (guile) ;so that bindings will be checked here first
2861 :use-module (ice-9 session)
2862 :use-module (ice-9 debug)
2863 :autoload (ice-9 debugger) (debug)) ;load debugger on demand
2864 (if (memq 'threads *features*)
2865 (define-module (guile-user) :use-module (ice-9 threads)))
2866 (if (memq 'regex *features*)
2867 (define-module (guile-user) :use-module (ice-9 regex)))
2869 (let ((old-handlers #f)
2870 (signals (if (provided? 'posix)
2871 `((,SIGINT . "User interrupt")
2872 (,SIGFPE . "Arithmetic error")
2873 (,SIGBUS . "Bad memory access (bus error)")
2875 "Bad memory access (Segmentation violation)"))
2882 (let ((make-handler (lambda (msg)
2884 ;; Make a backup copy of the stack
2885 (fluid-set! before-signal-stack
2886 (fluid-ref the-last-stack))
2887 (save-stack %deliver-signals)
2894 (map (lambda (sig-msg)
2895 (sigaction (car sig-msg)
2896 (make-handler (cdr sig-msg))))
2899 ;; the protected thunk.
2901 (let ((status (scm-style-repl)))
2902 (run-hook exit-hook)
2907 (map (lambda (sig-msg old-handler)
2908 (if (not (car old-handler))
2909 ;; restore original C handler.
2910 (sigaction (car sig-msg) #f)
2911 ;; restore Scheme handler, SIG_IGN or SIG_DFL.
2912 (sigaction (car sig-msg)
2914 (cdr old-handler))))
2915 signals old-handlers)))))
2917 (defmacro false-if-exception (expr)
2918 `(catch #t (lambda () ,expr)
2921 ;;; This hook is run at the very end of an interactive session.
2923 (define exit-hook (make-hook))
2926 (define-module (guile))
2928 (append! %load-path (cons "." ()))