3 ;;;; Copyright (C) 1995, 1996, 1997, 1998 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*))))
40 (primitive-load-path "ice-9/r4rs.scm")
43 ;;; {Simple Debugging Tools}
47 ;; peek takes any number of arguments, writes them to the
48 ;; current ouput port, and returns the last argument.
49 ;; It is handy to wrap around an expression to look at
50 ;; a value each time is evaluated, e.g.:
52 ;; (+ 10 (troublesome-fn))
53 ;; => (+ 10 (pk 'troublesome-fn-returned (troublesome-fn)))
56 (define (peek . stuff)
61 (car (last-pair stuff)))
65 (define (warn . stuff)
66 (with-output-to-port (current-error-port)
69 (display ";;; WARNING ")
72 (car (last-pair stuff)))))
75 ;;; {Trivial Functions}
79 (define (1+ n) (+ n 1))
80 (define (-1+ n) (+ n -1))
82 (define return-it noop)
83 (define (and=> value procedure) (and value (procedure value)))
84 (define (make-hash-table k) (make-vector k '()))
86 ;;; apply-to-args is functionally redunant with apply and, worse,
87 ;;; is less general than apply since it only takes two arguments.
89 ;;; On the other hand, apply-to-args is a syntacticly convenient way to
90 ;;; perform binding in many circumstances when the "let" family of
91 ;;; of forms don't cut it. E.g.:
93 ;;; (apply-to-args (return-3d-mouse-coords)
98 (define (apply-to-args args fn) (apply fn args))
104 (define (ipow-by-squaring x k acc proc)
105 (cond ((zero? k) acc)
106 ((= 1 k) (proc acc x))
107 (else (ipow-by-squaring (proc x x)
109 (if (even? k) acc (proc acc x))
112 (define string-character-length string-length)
116 ;; A convenience function for combining flag bits. Like logior, but
117 ;; handles the cases of 0 and 1 arguments.
119 (define (flags . args)
122 ((null? (cdr args)) (car args))
123 (else (apply logior args))))
126 ;;; {Symbol Properties}
129 (define (symbol-property sym prop)
130 (let ((pair (assoc prop (symbol-pref sym))))
131 (and pair (cdr pair))))
133 (define (set-symbol-property! sym prop val)
134 (let ((pair (assoc prop (symbol-pref sym))))
137 (symbol-pset! sym (acons prop val (symbol-pref sym))))))
139 (define (symbol-property-remove! sym prop)
140 (let ((pair (assoc prop (symbol-pref sym))))
142 (symbol-pset! sym (delq! pair (symbol-pref sym))))))
146 ;;; {Line and Delimited I/O}
148 ;;; corresponds to SCM_LINE_INCREMENTORS in libguile.
149 (define scm-line-incrementors "\n")
151 (define (read-line! string . maybe-port)
152 (let* ((port (if (pair? maybe-port)
154 (current-input-port))))
155 (let* ((rv (%read-delimited! scm-line-incrementors
159 (terminator (car rv))
161 (cond ((and (= nchars 0)
162 (eof-object? terminator))
164 ((not terminator) #f)
167 (define (read-delimited! delims buf . args)
168 (let* ((num-args (length args))
169 (port (if (> num-args 0)
171 (current-input-port)))
172 (handle-delim (if (> num-args 1)
175 (start (if (> num-args 2)
178 (end (if (> num-args 3)
180 (string-length buf))))
181 (let* ((rv (%read-delimited! delims
183 (not (eq? handle-delim 'peek))
187 (terminator (car rv))
189 (cond ((or (not terminator) ; buffer filled
190 (eof-object? terminator))
192 (if (eq? handle-delim 'split)
193 (cons terminator terminator)
195 (if (eq? handle-delim 'split)
196 (cons nchars terminator)
201 ((concat) (string-set! buf nchars terminator)
203 ((split) (cons nchars terminator))
204 (else (error "unexpected handle-delim value: "
207 (define (read-delimited delims . args)
208 (let* ((port (if (pair? args)
209 (let ((pt (car args)))
210 (set! args (cdr args))
212 (current-input-port)))
213 (handle-delim (if (pair? args)
216 (let loop ((substrings ())
218 (buf-size 100)) ; doubled each time through.
219 (let* ((buf (make-string buf-size))
220 (rv (%read-delimited! delims
222 (not (eq? handle-delim 'peek))
224 (terminator (car rv))
230 (cons (if (and (eq? handle-delim 'concat)
231 (not (eof-object? terminator)))
234 (cons (make-shared-substring buf 0 nchars)
236 (new-total (+ total-chars nchars)))
237 (cond ((not terminator)
239 (loop (cons (substring buf 0 nchars) substrings)
242 ((eof-object? terminator)
243 (if (zero? new-total)
244 (if (eq? handle-delim 'split)
245 (cons terminator terminator)
247 (if (eq? handle-delim 'split)
248 (cons (join-substrings) terminator)
252 ((trim peek concat) (join-substrings))
253 ((split) (cons (join-substrings) terminator))
256 (else (error "unexpected handle-delim value: "
257 handle-delim)))))))))
259 ;;; read-line [PORT [HANDLE-DELIM]] reads a newline-terminated string
260 ;;; from PORT. The return value depends on the value of HANDLE-DELIM,
261 ;;; which may be one of the symbols `trim', `concat', `peek' and
262 ;;; `split'. If it is `trim' (the default), the trailing newline is
263 ;;; removed and the string is returned. If `concat', the string is
264 ;;; returned with the trailing newline intact. If `peek', the newline
265 ;;; is left in the input port buffer and the string is returned. If
266 ;;; `split', the newline is split from the string and read-line
267 ;;; returns a pair consisting of the truncated string and the newline.
269 (define (read-line . args)
270 (let* ((port (if (null? args)
273 (handle-delim (if (> (length args) 1)
276 (line/delim (%read-line port))
277 (line (car line/delim))
278 (delim (cdr line/delim)))
282 ((concat) (if (and (string? line) (char? delim))
283 (string-append line (string delim))
285 ((peek) (if (char? delim)
286 (unread-char delim port))
289 (error "unexpected handle-delim value: " handle-delim)))))
296 (define uniform-vector? array?)
297 (define make-uniform-vector dimensions->uniform-array)
298 ; (define uniform-vector-ref array-ref)
299 (define (uniform-vector-set! u i o)
300 (uniform-array-set1! u o i))
301 (define uniform-vector-fill! array-fill!)
302 (define uniform-vector-read! uniform-array-read!)
303 (define uniform-vector-write uniform-array-write)
305 (define (make-array fill . args)
306 (dimensions->uniform-array args () fill))
307 (define (make-uniform-array prot . args)
308 (dimensions->uniform-array args prot))
309 (define (list->array ndim lst)
310 (list->uniform-array ndim '() lst))
311 (define (list->uniform-vector prot lst)
312 (list->uniform-array 1 prot lst))
313 (define (array-shape a)
314 (map (lambda (ind) (if (number? ind) (list 0 (+ -1 ind)) ind))
315 (array-dimensions a))))
321 (define (symbol->keyword symbol)
322 (make-keyword-from-dash-symbol (symbol-append '- symbol)))
324 (define (keyword->symbol kw)
325 (let ((sym (keyword-dash-symbol kw)))
326 (string->symbol (substring sym 1 (string-length sym)))))
328 (define (kw-arg-ref args kw)
329 (let ((rem (member kw args)))
330 (and rem (pair? (cdr rem)) (cadr rem))))
336 (define (struct-layout s)
337 (struct-ref (struct-vtable s) vtable-index-layout))
343 ;; Printing records: by default, records are printed as
345 ;; #<type-name field1: val1 field2: val2 ...>
347 ;; You can change that by giving a custom printing function to
348 ;; MAKE-RECORD-TYPE (after the list of field symbols). This function
349 ;; will be called like
351 ;; (<printer> object port)
353 ;; It should print OBJECT to PORT.
355 (define (inherit-print-state old-port new-port)
357 (cons (if (pair? new-port) (car new-port) new-port)
361 ;; 0: type-name, 1: fields
362 (define record-type-vtable
363 (make-vtable-vtable "prpr" 0
365 (cond ((eq? s record-type-vtable)
366 (display "#<record-type-vtable>" p))
368 (display "#<record-type " p)
369 (display (record-type-name s) p)
372 (define (record-type? obj)
373 (and (struct? obj) (eq? record-type-vtable (struct-vtable obj))))
375 (define (make-record-type type-name fields . opt)
376 (let ((printer-fn (and (pair? opt) (car opt))))
377 (let ((struct (make-struct record-type-vtable 0
380 (map (lambda (f) "pw") fields)))
384 (display type-name p)
385 (let loop ((fields fields)
388 ((not (null? fields))
390 (display (car fields) p)
392 (display (struct-ref s off) p)
393 (loop (cdr fields) (+ 1 off)))))
396 (copy-tree fields))))
399 (define (record-type-name obj)
400 (if (record-type? obj)
401 (struct-ref obj vtable-offset-user)
402 (error 'not-a-record-type obj)))
404 (define (record-type-fields obj)
405 (if (record-type? obj)
406 (struct-ref obj (+ 1 vtable-offset-user))
407 (error 'not-a-record-type obj)))
409 (define (record-constructor rtd . opt)
410 (let ((field-names (if (pair? opt) (car opt) (record-type-fields rtd))))
411 (eval `(lambda ,field-names
412 (make-struct ',rtd 0 ,@(map (lambda (f)
413 (if (memq f field-names)
416 (record-type-fields rtd)))))))
418 (define (record-predicate rtd)
419 (lambda (obj) (and (struct? obj) (eq? rtd (struct-vtable obj)))))
421 (define (record-accessor rtd field-name)
422 (let* ((pos (list-index (record-type-fields rtd) field-name)))
424 (error 'no-such-field field-name))
426 (and (eq? ',rtd (record-type-descriptor obj))
427 (struct-ref obj ,pos))))))
429 (define (record-modifier rtd field-name)
430 (let* ((pos (list-index (record-type-fields rtd) field-name)))
432 (error 'no-such-field field-name))
433 (eval `(lambda (obj val)
434 (and (eq? ',rtd (record-type-descriptor obj))
435 (struct-set! obj ,pos val))))))
438 (define (record? obj)
439 (and (struct? obj) (record-type? (struct-vtable obj))))
441 (define (record-type-descriptor obj)
444 (error 'not-a-record obj)))
452 (define (->bool x) (not (not x)))
458 (define (symbol-append . args)
459 (string->symbol (apply string-append args)))
461 (define (list->symbol . args)
462 (string->symbol (apply list->string args)))
464 (define (symbol . args)
465 (string->symbol (apply string args)))
467 (define (obarray-symbol-append ob . args)
468 (string->obarray-symbol (apply string-append ob args)))
470 (define (obarray-gensym obarray . opt)
472 (gensym "%%gensym" obarray)
473 (gensym (car opt) obarray)))
479 (define (list-index l k)
485 (loop (+ n 1) (cdr l))))))
487 (define (make-list n . init)
488 (if (pair? init) (set! init (car init)))
489 (let loop ((answer '())
493 (loop (cons init answer) (- n 1)))))
497 ;;; {Multiple return values}
500 (make-record-type "values"
504 (let ((make-values (record-constructor *values-rtd*)))
506 (if (and (not (null? x))
511 (define call-with-values
512 (let ((access-values (record-accessor *values-rtd* 'values))
513 (values-predicate? (record-predicate *values-rtd*)))
514 (lambda (producer consumer)
515 (let ((result (producer)))
516 (if (values-predicate? result)
517 (apply consumer (access-values result))
518 (consumer result))))))
522 ;;; {and-map and or-map}
524 ;;; (and-map fn lst) is like (and (fn (car lst)) (fn (cadr lst)) (fn...) ...)
525 ;;; (or-map fn lst) is like (or (fn (car lst)) (fn (cadr lst)) (fn...) ...)
526 ;;; (map-in-order fn lst) is like (map fn lst) but definately in order of lst.
531 ;; Apply f to successive elements of l until exhaustion or f returns #f.
532 ;; If returning early, return #f. Otherwise, return the last value returned
533 ;; by f. If f has never been called because l is empty, return #t.
535 (define (and-map f lst)
536 (let loop ((result #t)
541 (loop (f (car l)) (cdr l))))))
545 ;; Apply f to successive elements of l until exhaustion or while f returns #f.
546 ;; If returning early, return the return value of f.
548 (define (or-map f lst)
549 (let loop ((result #f)
553 (loop (f (car l)) (cdr l))))))
558 ;;; Warning: Hooks are now first class objects and add-hook! and remove-hook!
559 ;;; procedures. This interface is only provided for backward compatibility
560 ;;; and will be removed.
562 (if (not (defined? 'new-add-hook!))
564 (define new-add-hook! add-hook!)
565 (define new-remove-hook! remove-hook!)))
567 (define (run-hooks hook)
568 (if (and (pair? hook) (eq? (car hook) 'hook))
570 (for-each (lambda (thunk) (thunk)) hook)))
573 (procedure->memoizing-macro
575 (let ((hook (local-eval (cadr exp) env)))
576 (if (and (pair? hook) (eq? (car hook) 'hook))
577 `(new-add-hook! ,@(cdr exp))
579 (display "Warning: Old style hooks\n" (current-error-port))
580 `(let ((thunk ,(caddr exp)))
581 (if (not (memq thunk ,(cadr exp)))
583 (cons thunk ,(cadr exp)))))))))))
586 (procedure->memoizing-macro
588 (let ((hook (local-eval (cadr exp) env)))
589 (if (and (pair? hook) (eq? (car hook) 'hook))
590 `(new-remove-hook! ,@(cdr exp))
592 (display "Warning: Old style hooks\n" (current-error-port))
593 `(let ((thunk ,(caddr exp)))
595 (delq! thunk ,(cadr exp))))))))))
600 ;;; If no one can explain this comment to me by 31 Jan 1998, I will
601 ;;; assume it is meaningless and remove it. -twp
602 ;;; !!!! these should be implemented using Tcl commands, not fports.
604 (define (feature? feature)
605 (and (memq feature *features*) #t))
607 ;; Using the vector returned by stat directly is probably not a good
608 ;; idea (it could just as well be a record). Hence some accessors.
609 (define (stat:dev f) (vector-ref f 0))
610 (define (stat:ino f) (vector-ref f 1))
611 (define (stat:mode f) (vector-ref f 2))
612 (define (stat:nlink f) (vector-ref f 3))
613 (define (stat:uid f) (vector-ref f 4))
614 (define (stat:gid f) (vector-ref f 5))
615 (define (stat:rdev f) (vector-ref f 6))
616 (define (stat:size f) (vector-ref f 7))
617 (define (stat:atime f) (vector-ref f 8))
618 (define (stat:mtime f) (vector-ref f 9))
619 (define (stat:ctime f) (vector-ref f 10))
620 (define (stat:blksize f) (vector-ref f 11))
621 (define (stat:blocks f) (vector-ref f 12))
623 ;; derived from stat mode.
624 (define (stat:type f) (vector-ref f 13))
625 (define (stat:perms f) (vector-ref f 14))
628 (if (feature? 'posix)
632 (let ((port (catch 'system-error (lambda () (open-file str OPEN_READ))
634 (if port (begin (close-port port) #t)
637 (define file-is-directory?
638 (if (feature? 'i/o-extensions)
640 (eq? (stat:type (stat str)) 'directory))
644 (let ((port (catch 'system-error
645 (lambda () (open-file (string-append str "/.")
648 (if port (begin (close-port port) #t)
651 (define (has-suffix? str suffix)
652 (let ((sufl (string-length suffix))
653 (sl (string-length str)))
655 (string=? (substring str (- sl sufl) sl) suffix))))
661 (define (error . args)
664 (scm-error 'misc-error #f "?" #f #f)
665 (let loop ((msg "%s")
667 (if (not (null? rest))
668 (loop (string-append msg " %S")
670 (scm-error 'misc-error #f msg args #f)))))
672 ;; bad-throw is the hook that is called upon a throw to a an unhandled
673 ;; key (unless the throw has four arguments, in which case
674 ;; it's usually interpreted as an error throw.)
675 ;; If the key has a default handler (a throw-handler-default property),
676 ;; it is applied to the throw.
678 (define (bad-throw key . args)
679 (let ((default (symbol-property key 'throw-handler-default)))
680 (or (and default (apply default key args))
681 (apply error "unhandled-exception:" key args))))
684 ;;; {Non-polymorphic versions of POSIX functions}
686 (define (getgrnam name) (getgr name))
687 (define (getgrgid id) (getgr id))
688 (define (gethostbyaddr addr) (gethost addr))
689 (define (gethostbyname name) (gethost name))
690 (define (getnetbyaddr addr) (getnet addr))
691 (define (getnetbyname name) (getnet name))
692 (define (getprotobyname name) (getproto name))
693 (define (getprotobynumber addr) (getproto addr))
694 (define (getpwnam name) (getpw name))
695 (define (getpwuid uid) (getpw uid))
696 (define (getservbyname name proto) (getserv name proto))
697 (define (getservbyport port proto) (getserv port proto))
698 (define (endgrent) (setgr))
699 (define (endhostent) (sethost))
700 (define (endnetent) (setnet))
701 (define (endprotoent) (setproto))
702 (define (endpwent) (setpw))
703 (define (endservent) (setserv))
704 (define (getgrent) (getgr))
705 (define (gethostent) (gethost))
706 (define (getnetent) (getnet))
707 (define (getprotoent) (getproto))
708 (define (getpwent) (getpw))
709 (define (getservent) (getserv))
710 (define (reopen-file . args) (apply freopen args))
711 (define (setgrent) (setgr #f))
712 (define (sethostent) (sethost #t))
713 (define (setnetent) (setnet #t))
714 (define (setprotoent) (setproto #t))
715 (define (setpwent) (setpw #t))
716 (define (setservent) (setserv #t))
718 (define (passwd:name obj) (vector-ref obj 0))
719 (define (passwd:passwd obj) (vector-ref obj 1))
720 (define (passwd:uid obj) (vector-ref obj 2))
721 (define (passwd:gid obj) (vector-ref obj 3))
722 (define (passwd:gecos obj) (vector-ref obj 4))
723 (define (passwd:dir obj) (vector-ref obj 5))
724 (define (passwd:shell obj) (vector-ref obj 6))
726 (define (group:name obj) (vector-ref obj 0))
727 (define (group:passwd obj) (vector-ref obj 1))
728 (define (group:gid obj) (vector-ref obj 2))
729 (define (group:mem obj) (vector-ref obj 3))
731 (define (hostent:name obj) (vector-ref obj 0))
732 (define (hostent:aliases obj) (vector-ref obj 1))
733 (define (hostent:addrtype obj) (vector-ref obj 2))
734 (define (hostent:length obj) (vector-ref obj 3))
735 (define (hostent:addr-list obj) (vector-ref obj 4))
737 (define (netent:name obj) (vector-ref obj 0))
738 (define (netent:aliases obj) (vector-ref obj 1))
739 (define (netent:addrtype obj) (vector-ref obj 2))
740 (define (netent:net obj) (vector-ref obj 3))
742 (define (protoent:name obj) (vector-ref obj 0))
743 (define (protoent:aliases obj) (vector-ref obj 1))
744 (define (protoent:proto obj) (vector-ref obj 2))
746 (define (servent:name obj) (vector-ref obj 0))
747 (define (servent:aliases obj) (vector-ref obj 1))
748 (define (servent:port obj) (vector-ref obj 2))
749 (define (servent:proto obj) (vector-ref obj 3))
751 (define (sockaddr:fam obj) (vector-ref obj 0))
752 (define (sockaddr:path obj) (vector-ref obj 1))
753 (define (sockaddr:addr obj) (vector-ref obj 1))
754 (define (sockaddr:port obj) (vector-ref obj 2))
756 (define (utsname:sysname obj) (vector-ref obj 0))
757 (define (utsname:nodename obj) (vector-ref obj 1))
758 (define (utsname:release obj) (vector-ref obj 2))
759 (define (utsname:version obj) (vector-ref obj 3))
760 (define (utsname:machine obj) (vector-ref obj 4))
762 (define (tm:sec obj) (vector-ref obj 0))
763 (define (tm:min obj) (vector-ref obj 1))
764 (define (tm:hour obj) (vector-ref obj 2))
765 (define (tm:mday obj) (vector-ref obj 3))
766 (define (tm:mon obj) (vector-ref obj 4))
767 (define (tm:year obj) (vector-ref obj 5))
768 (define (tm:wday obj) (vector-ref obj 6))
769 (define (tm:yday obj) (vector-ref obj 7))
770 (define (tm:isdst obj) (vector-ref obj 8))
771 (define (tm:gmtoff obj) (vector-ref obj 9))
772 (define (tm:zone obj) (vector-ref obj 10))
774 (define (set-tm:sec obj val) (vector-set! obj 0 val))
775 (define (set-tm:min obj val) (vector-set! obj 1 val))
776 (define (set-tm:hour obj val) (vector-set! obj 2 val))
777 (define (set-tm:mday obj val) (vector-set! obj 3 val))
778 (define (set-tm:mon obj val) (vector-set! obj 4 val))
779 (define (set-tm:year obj val) (vector-set! obj 5 val))
780 (define (set-tm:wday obj val) (vector-set! obj 6 val))
781 (define (set-tm:yday obj val) (vector-set! obj 7 val))
782 (define (set-tm:isdst obj val) (vector-set! obj 8 val))
783 (define (set-tm:gmtoff obj val) (vector-set! obj 9 val))
784 (define (set-tm:zone obj val) (vector-set! obj 10 val))
786 (define (tms:clock obj) (vector-ref obj 0))
787 (define (tms:utime obj) (vector-ref obj 1))
788 (define (tms:stime obj) (vector-ref obj 2))
789 (define (tms:cutime obj) (vector-ref obj 3))
790 (define (tms:cstime obj) (vector-ref obj 4))
792 (define (file-position . args) (apply ftell args))
793 (define (file-set-position . args) (apply fseek args))
795 (define (open-input-pipe command) (open-pipe command OPEN_READ))
796 (define (open-output-pipe command) (open-pipe command OPEN_WRITE))
798 (define (move->fdes fd/port fd)
799 (cond ((integer? fd/port)
800 (dup->fdes fd/port fd)
804 (primitive-move->fdes fd/port fd)
805 (set-port-revealed! fd/port 1)
808 (define (release-port-handle port)
809 (let ((revealed (port-revealed port)))
811 (set-port-revealed! port (- revealed 1)))))
813 (define (dup->port port/fd mode . maybe-fd)
814 (let ((port (fdopen (apply dup->fdes port/fd maybe-fd)
817 (set-port-revealed! port 1))
820 (define (dup->inport port/fd . maybe-fd)
821 (apply dup->port port/fd "r" maybe-fd))
823 (define (dup->outport port/fd . maybe-fd)
824 (apply dup->port port/fd "w" maybe-fd))
826 (define (dup port/fd . maybe-fd)
827 (if (integer? port/fd)
828 (apply dup->fdes port/fd maybe-fd)
829 (apply dup->port port/fd (port-mode port/fd) maybe-fd)))
831 (define (duplicate-port port modes)
832 (dup->port port modes))
834 (define (fdes->inport fdes)
835 (let loop ((rest-ports (fdes->ports fdes)))
836 (cond ((null? rest-ports)
837 (let ((result (fdopen fdes "r")))
838 (set-port-revealed! result 1)
840 ((input-port? (car rest-ports))
841 (set-port-revealed! (car rest-ports)
842 (+ (port-revealed (car rest-ports)) 1))
845 (loop (cdr rest-ports))))))
847 (define (fdes->outport fdes)
848 (let loop ((rest-ports (fdes->ports fdes)))
849 (cond ((null? rest-ports)
850 (let ((result (fdopen fdes "w")))
851 (set-port-revealed! result 1)
853 ((output-port? (car rest-ports))
854 (set-port-revealed! (car rest-ports)
855 (+ (port-revealed (car rest-ports)) 1))
858 (loop (cdr rest-ports))))))
860 (define (port->fdes port)
861 (set-port-revealed! port (+ (port-revealed port) 1))
864 (define (setenv name value)
866 (putenv (string-append name "=" value))
873 ;;; Here for backward compatability
875 (define scheme-file-suffix (lambda () ".scm"))
877 (define (in-vicinity vicinity file)
878 (let ((tail (let ((len (string-length vicinity)))
881 (string-ref vicinity (- len 1))))))
882 (string-append vicinity
890 ;;; {Help for scm_shell}
891 ;;; The argument-processing code used by Guile-based shells generates
892 ;;; Scheme code based on the argument list. This page contains help
893 ;;; functions for the code it generates.
895 (define (command-line) (program-arguments))
897 ;; This is mostly for the internal use of the code generated by
898 ;; scm_compile_shell_switches.
899 (define (load-user-init)
900 (define (has-init? dir)
901 (let ((path (in-vicinity dir ".guile")))
904 (let ((stats (stat path)))
905 (if (not (eq? (stat:type stats) 'directory))
908 (let ((path (or (has-init? (or (getenv "HOME") "/"))
909 (has-init? (passwd:dir (getpw (getuid)))))))
910 (if path (primitive-load path))))
913 ;;; {Loading by paths}
915 ;;; Load a Scheme source file named NAME, searching for it in the
916 ;;; directories listed in %load-path, and applying each of the file
917 ;;; name extensions listed in %load-extensions.
918 (define (load-from-path name)
919 (start-stack 'load-stack
920 (primitive-load-path name)))
924 ;;; {Transcendental Functions}
926 ;;; Derived from "Transcen.scm", Complex trancendental functions for SCM.
927 ;;; Written by Jerry D. Hedden, (C) FSF.
928 ;;; See the file `COPYING' for terms applying to this program.
932 (if (real? z) ($exp z)
933 (make-polar ($exp (real-part z)) (imag-part z))))
936 (if (and (real? z) (>= z 0))
938 (make-rectangular ($log (magnitude z)) (angle z))))
942 (if (negative? z) (make-rectangular 0 ($sqrt (- z)))
944 (make-polar ($sqrt (magnitude z)) (/ (angle z) 2))))
947 (let ((integer-expt integer-expt))
950 (integer-expt z1 z2))
951 ((and (real? z2) (real? z1) (>= z1 0))
954 (exp (* z2 (log z1))))))))
957 (if (real? z) ($sinh z)
958 (let ((x (real-part z)) (y (imag-part z)))
959 (make-rectangular (* ($sinh x) ($cos y))
960 (* ($cosh x) ($sin y))))))
962 (if (real? z) ($cosh z)
963 (let ((x (real-part z)) (y (imag-part z)))
964 (make-rectangular (* ($cosh x) ($cos y))
965 (* ($sinh x) ($sin y))))))
967 (if (real? z) ($tanh z)
968 (let* ((x (* 2 (real-part z)))
969 (y (* 2 (imag-part z)))
970 (w (+ ($cosh x) ($cos y))))
971 (make-rectangular (/ ($sinh x) w) (/ ($sin y) w)))))
974 (if (real? z) ($asinh z)
975 (log (+ z (sqrt (+ (* z z) 1))))))
978 (if (and (real? z) (>= z 1))
980 (log (+ z (sqrt (- (* z z) 1))))))
983 (if (and (real? z) (> z -1) (< z 1))
985 (/ (log (/ (+ 1 z) (- 1 z))) 2)))
988 (if (real? z) ($sin z)
989 (let ((x (real-part z)) (y (imag-part z)))
990 (make-rectangular (* ($sin x) ($cosh y))
991 (* ($cos x) ($sinh y))))))
993 (if (real? z) ($cos z)
994 (let ((x (real-part z)) (y (imag-part z)))
995 (make-rectangular (* ($cos x) ($cosh y))
996 (- (* ($sin x) ($sinh y)))))))
998 (if (real? z) ($tan z)
999 (let* ((x (* 2 (real-part z)))
1000 (y (* 2 (imag-part z)))
1001 (w (+ ($cos x) ($cosh y))))
1002 (make-rectangular (/ ($sin x) w) (/ ($sinh y) w)))))
1005 (if (and (real? z) (>= z -1) (<= z 1))
1007 (* -i (asinh (* +i z)))))
1010 (if (and (real? z) (>= z -1) (<= z 1))
1012 (+ (/ (angle -1) 2) (* +i (asinh (* +i z))))))
1014 (define (atan z . y)
1016 (if (real? z) ($atan z)
1017 (/ (log (/ (- +i z) (+ +i z))) +2i))
1018 ($atan2 z (car y))))
1020 (set! abs magnitude)
1023 (/ (log arg) (log 10)))
1027 ;;; {Reader Extensions}
1030 ;;; Reader code for various "#c" forms.
1033 ;;; Parse the portion of a #/ list that comes after the first slash.
1034 (define (read-path-list-notation slash port)
1037 ;; Is C a delimiter?
1038 ((delimiter? (lambda (c) (or (eof-object? c)
1039 (char-whitespace? c)
1040 (string-index "()\";" c))))
1042 ;; Read and return one component of a path list.
1045 (let loop ((reversed-chars '()))
1046 (let ((c (peek-char port)))
1047 (if (or (delimiter? c)
1049 (string->symbol (list->string (reverse reversed-chars)))
1050 (loop (cons (read-char port) reversed-chars))))))))
1052 ;; Read and return a path list.
1053 (let loop ((reversed-path (list (read-component))))
1054 (let ((c (peek-char port)))
1055 (if (and (char? c) (char=? c #\/))
1058 (loop (cons (read-component) reversed-path)))
1059 (reverse reversed-path))))))
1061 (define (read-path-list-notation-warning slash port)
1062 (if (not (getenv "GUILE_HUSH"))
1064 (display "warning: obsolete `#/' list notation read from "
1065 (current-error-port))
1066 (display (port-filename port) (current-error-port))
1067 (display "; see guile-core/NEWS." (current-error-port))
1068 (newline (current-error-port))
1069 (display " Set the GUILE_HUSH environment variable to disable this warning."
1070 (current-error-port))
1071 (newline (current-error-port))))
1072 (read-hash-extend #\/ read-path-list-notation)
1073 (read-path-list-notation slash port))
1076 (read-hash-extend #\' (lambda (c port)
1078 (read-hash-extend #\. (lambda (c port)
1079 (eval (read port))))
1081 (if (feature? 'array)
1083 (let ((make-array-proc (lambda (template)
1085 (read:uniform-vector template port)))))
1086 (for-each (lambda (char template)
1087 (read-hash-extend char
1088 (make-array-proc template)))
1089 '(#\b #\a #\u #\e #\s #\i #\c #\y #\h)
1090 '(#t #\a 1 -1 1.0 1/3 0+i #\nul s)))
1091 (let ((array-proc (lambda (c port)
1092 (read:array c port))))
1093 (for-each (lambda (char) (read-hash-extend char array-proc))
1094 '(#\0 #\1 #\2 #\3 #\4 #\5 #\6 #\7 #\8 #\9)))))
1096 ;; pushed to the beginning of the alist since it's used more than the
1097 ;; others at present.
1098 (read-hash-extend #\/ read-path-list-notation-warning)
1100 (define (read:array digit port)
1101 (define chr0 (char->integer #\0))
1102 (let ((rank (let readnum ((val (- (char->integer digit) chr0)))
1103 (if (char-numeric? (peek-char port))
1104 (readnum (+ (* 10 val)
1105 (- (char->integer (read-char port)) chr0)))
1107 (prot (if (eq? #\( (peek-char port))
1109 (let ((c (read-char port)))
1117 (else (error "read:array unknown option " c)))))))
1118 (if (eq? (peek-char port) #\()
1119 (list->uniform-array rank prot (read port))
1120 (error "read:array list not found"))))
1122 (define (read:uniform-vector proto port)
1123 (if (eq? #\( (peek-char port))
1124 (list->uniform-array 1 proto (read port))
1125 (error "read:uniform-vector list not found")))
1128 ;;; {Command Line Options}
1131 (define (get-option argv kw-opts kw-args return)
1134 (return #f #f argv))
1136 ((or (not (eq? #\- (string-ref (car argv) 0)))
1137 (eq? (string-length (car argv)) 1))
1138 (return 'normal-arg (car argv) (cdr argv)))
1140 ((eq? #\- (string-ref (car argv) 1))
1141 (let* ((kw-arg-pos (or (string-index (car argv) #\=)
1142 (string-length (car argv))))
1143 (kw (symbol->keyword (substring (car argv) 2 kw-arg-pos)))
1144 (kw-opt? (member kw kw-opts))
1145 (kw-arg? (member kw kw-args))
1146 (arg (or (and (not (eq? kw-arg-pos (string-length (car argv))))
1147 (substring (car argv)
1149 (string-length (car argv))))
1151 (begin (set! argv (cdr argv)) (car argv))))))
1152 (if (or kw-opt? kw-arg?)
1153 (return kw arg (cdr argv))
1154 (return 'usage-error kw (cdr argv)))))
1157 (let* ((char (substring (car argv) 1 2))
1158 (kw (symbol->keyword char)))
1161 ((member kw kw-opts)
1162 (let* ((rest-car (substring (car argv) 2 (string-length (car argv))))
1163 (new-argv (if (= 0 (string-length rest-car))
1165 (cons (string-append "-" rest-car) (cdr argv)))))
1166 (return kw #f new-argv)))
1168 ((member kw kw-args)
1169 (let* ((rest-car (substring (car argv) 2 (string-length (car argv))))
1170 (arg (if (= 0 (string-length rest-car))
1173 (new-argv (if (= 0 (string-length rest-car))
1176 (return kw arg new-argv)))
1178 (else (return 'usage-error kw argv)))))))
1180 (define (for-next-option proc argv kw-opts kw-args)
1181 (let loop ((argv argv))
1182 (get-option argv kw-opts kw-args
1183 (lambda (opt opt-arg argv)
1184 (and opt (proc opt opt-arg argv loop))))))
1186 (define (display-usage-report kw-desc)
1189 (or (eq? (car kw) #t)
1190 (eq? (car kw) 'else)
1191 (let* ((opt-desc kw)
1192 (help (cadr opt-desc))
1193 (opts (car opt-desc))
1194 (opts-proper (if (string? (car opts)) (cdr opts) opts))
1195 (arg-name (if (string? (car opts))
1196 (string-append "<" (car opts) ">")
1198 (left-part (string-append
1199 (with-output-to-string
1201 (map (lambda (x) (display (keyword-symbol x)) (display " "))
1204 (middle-part (if (and (< (string-length left-part) 30)
1205 (< (string-length help) 40))
1206 (make-string (- 30 (string-length left-part)) #\ )
1209 (display middle-part)
1216 (define (transform-usage-lambda cases)
1217 (let* ((raw-usage (delq! 'else (map car cases)))
1218 (usage-sans-specials (map (lambda (x)
1219 (or (and (not (list? x)) x)
1220 (and (symbol? (car x)) #t)
1221 (and (boolean? (car x)) #t)
1224 (usage-desc (delq! #t usage-sans-specials))
1225 (kw-desc (map car usage-desc))
1226 (kw-opts (apply append (map (lambda (x) (and (not (string? (car x))) x)) kw-desc)))
1227 (kw-args (apply append (map (lambda (x) (and (string? (car x)) (cdr x))) kw-desc)))
1228 (transmogrified-cases (map (lambda (case)
1229 (cons (let ((opts (car case)))
1230 (if (or (boolean? opts) (eq? 'else opts))
1233 ((symbol? (car opts)) opts)
1234 ((boolean? (car opts)) opts)
1235 ((string? (caar opts)) (cdar opts))
1236 (else (car opts)))))
1239 `(let ((%display-usage (lambda () (display-usage-report ',usage-desc))))
1241 (let %next-arg ((%argv %argv))
1245 (lambda (%opt %arg %new-argv)
1247 ,@ transmogrified-cases))))))))
1252 ;;; {Low Level Modules}
1254 ;;; These are the low level data structures for modules.
1256 ;;; !!! warning: The interface to lazy binder procedures is going
1257 ;;; to be changed in an incompatible way to permit all the basic
1258 ;;; module ops to be virtualized.
1260 ;;; (make-module size use-list lazy-binding-proc) => module
1261 ;;; module-{obarray,uses,binder}[|-set!]
1262 ;;; (module? obj) => [#t|#f]
1263 ;;; (module-locally-bound? module symbol) => [#t|#f]
1264 ;;; (module-bound? module symbol) => [#t|#f]
1265 ;;; (module-symbol-locally-interned? module symbol) => [#t|#f]
1266 ;;; (module-symbol-interned? module symbol) => [#t|#f]
1267 ;;; (module-local-variable module symbol) => [#<variable ...> | #f]
1268 ;;; (module-variable module symbol) => [#<variable ...> | #f]
1269 ;;; (module-symbol-binding module symbol opt-value)
1270 ;;; => [ <obj> | opt-value | an error occurs ]
1271 ;;; (module-make-local-var! module symbol) => #<variable...>
1272 ;;; (module-add! module symbol var) => unspecified
1273 ;;; (module-remove! module symbol) => unspecified
1274 ;;; (module-for-each proc module) => unspecified
1275 ;;; (make-scm-module) => module ; a lazy copy of the symhash module
1276 ;;; (set-current-module module) => unspecified
1277 ;;; (current-module) => #<module...>
1282 ;;; {Printing Modules}
1283 ;; This is how modules are printed. You can re-define it.
1284 ;; (Redefining is actually more complicated than simply redefining
1285 ;; %print-module because that would only change the binding and not
1286 ;; the value stored in the vtable that determines how record are
1289 (define (%print-module mod port) ; unused args: depth length style table)
1291 (display (or (module-kind mod) "module") port)
1292 (let ((name (module-name mod)))
1296 (display name port))))
1298 (display (number->string (object-address mod) 16) port)
1303 ;; A module is characterized by an obarray in which local symbols
1304 ;; are interned, a list of modules, "uses", from which non-local
1305 ;; bindings can be inherited, and an optional lazy-binder which
1306 ;; is a (CLOSURE module symbol) which, as a last resort, can provide
1307 ;; bindings that would otherwise not be found locally in the module.
1310 (make-record-type 'module
1311 '(obarray uses binder eval-closure transformer name kind)
1314 ;; make-module &opt size uses binder
1316 ;; Create a new module, perhaps with a particular size of obarray,
1317 ;; initial uses list, or binding procedure.
1322 (define (parse-arg index default)
1323 (if (> (length args) index)
1324 (list-ref args index)
1327 (if (> (length args) 3)
1328 (error "Too many args to make-module." args))
1330 (let ((size (parse-arg 0 1021))
1331 (uses (parse-arg 1 '()))
1332 (binder (parse-arg 2 #f)))
1334 (if (not (integer? size))
1335 (error "Illegal size to make-module." size))
1336 (if (not (and (list? uses)
1337 (and-map module? uses)))
1338 (error "Incorrect use list." uses))
1339 (if (and binder (not (procedure? binder)))
1341 "Lazy-binder expected to be a procedure or #f." binder))
1343 (let ((module (module-constructor (make-vector size '())
1344 uses binder #f #f #f #f)))
1346 ;; We can't pass this as an argument to module-constructor,
1347 ;; because we need it to close over a pointer to the module
1349 (set-module-eval-closure! module
1350 (lambda (symbol define?)
1352 (module-make-local-var! module symbol)
1353 (module-variable module symbol))))
1357 (define module-constructor (record-constructor module-type))
1358 (define module-obarray (record-accessor module-type 'obarray))
1359 (define set-module-obarray! (record-modifier module-type 'obarray))
1360 (define module-uses (record-accessor module-type 'uses))
1361 (define set-module-uses! (record-modifier module-type 'uses))
1362 (define module-binder (record-accessor module-type 'binder))
1363 (define set-module-binder! (record-modifier module-type 'binder))
1365 ;; NOTE: This binding is used in libguile/modules.c.
1366 (define module-eval-closure (record-accessor module-type 'eval-closure))
1368 (define set-module-eval-closure! (record-modifier module-type 'eval-closure))
1369 (define module-transformer (record-accessor module-type 'transformer))
1370 (define set-module-transformer! (record-modifier module-type 'transformer))
1371 (define module-name (record-accessor module-type 'name))
1372 (define set-module-name! (record-modifier module-type 'name))
1373 (define module-kind (record-accessor module-type 'kind))
1374 (define set-module-kind! (record-modifier module-type 'kind))
1375 (define module? (record-predicate module-type))
1378 (define (eval-in-module exp module)
1379 (eval2 exp (module-eval-closure module)))
1382 ;;; {Module Searching in General}
1384 ;;; We sometimes want to look for properties of a symbol
1385 ;;; just within the obarray of one module. If the property
1386 ;;; holds, then it is said to hold ``locally'' as in, ``The symbol
1387 ;;; DISPLAY is locally rebound in the module `safe-guile'.''
1390 ;;; Other times, we want to test for a symbol property in the obarray
1391 ;;; of M and, if it is not found there, try each of the modules in the
1392 ;;; uses list of M. This is the normal way of testing for some
1393 ;;; property, so we state these properties without qualification as
1394 ;;; in: ``The symbol 'fnord is interned in module M because it is
1395 ;;; interned locally in module M2 which is a member of the uses list
1399 ;; module-search fn m
1401 ;; return the first non-#f result of FN applied to M and then to
1402 ;; the modules in the uses of m, and so on recursively. If all applications
1403 ;; return #f, then so does this function.
1405 (define (module-search fn m v)
1408 (or (module-search fn (car pos) v)
1411 (loop (module-uses m))))
1414 ;;; {Is a symbol bound in a module?}
1416 ;;; Symbol S in Module M is bound if S is interned in M and if the binding
1417 ;;; of S in M has been set to some well-defined value.
1420 ;; module-locally-bound? module symbol
1422 ;; Is a symbol bound (interned and defined) locally in a given module?
1424 (define (module-locally-bound? m v)
1425 (let ((var (module-local-variable m v)))
1427 (variable-bound? var))))
1429 ;; module-bound? module symbol
1431 ;; Is a symbol bound (interned and defined) anywhere in a given module
1434 (define (module-bound? m v)
1435 (module-search module-locally-bound? m v))
1437 ;;; {Is a symbol interned in a module?}
1439 ;;; Symbol S in Module M is interned if S occurs in
1440 ;;; of S in M has been set to some well-defined value.
1442 ;;; It is possible to intern a symbol in a module without providing
1443 ;;; an initial binding for the corresponding variable. This is done
1445 ;;; (module-add! module symbol (make-undefined-variable))
1447 ;;; In that case, the symbol is interned in the module, but not
1448 ;;; bound there. The unbound symbol shadows any binding for that
1449 ;;; symbol that might otherwise be inherited from a member of the uses list.
1452 (define (module-obarray-get-handle ob key)
1453 ((if (symbol? key) hashq-get-handle hash-get-handle) ob key))
1455 (define (module-obarray-ref ob key)
1456 ((if (symbol? key) hashq-ref hash-ref) ob key))
1458 (define (module-obarray-set! ob key val)
1459 ((if (symbol? key) hashq-set! hash-set!) ob key val))
1461 (define (module-obarray-remove! ob key)
1462 ((if (symbol? key) hashq-remove! hash-remove!) ob key))
1464 ;; module-symbol-locally-interned? module symbol
1466 ;; is a symbol interned (not neccessarily defined) locally in a given module
1467 ;; or its uses? Interned symbols shadow inherited bindings even if
1468 ;; they are not themselves bound to a defined value.
1470 (define (module-symbol-locally-interned? m v)
1471 (not (not (module-obarray-get-handle (module-obarray m) v))))
1473 ;; module-symbol-interned? module symbol
1475 ;; is a symbol interned (not neccessarily defined) anywhere in a given module
1476 ;; or its uses? Interned symbols shadow inherited bindings even if
1477 ;; they are not themselves bound to a defined value.
1479 (define (module-symbol-interned? m v)
1480 (module-search module-symbol-locally-interned? m v))
1483 ;;; {Mapping modules x symbols --> variables}
1486 ;; module-local-variable module symbol
1487 ;; return the local variable associated with a MODULE and SYMBOL.
1489 ;;; This function is very important. It is the only function that can
1490 ;;; return a variable from a module other than the mutators that store
1491 ;;; new variables in modules. Therefore, this function is the location
1492 ;;; of the "lazy binder" hack.
1494 ;;; If symbol is defined in MODULE, and if the definition binds symbol
1495 ;;; to a variable, return that variable object.
1497 ;;; If the symbols is not found at first, but the module has a lazy binder,
1498 ;;; then try the binder.
1500 ;;; If the symbol is not found at all, return #f.
1502 (define (module-local-variable m v)
1505 (let ((b (module-obarray-ref (module-obarray m) v)))
1506 (or (and (variable? b) b)
1507 (and (module-binder m)
1508 ((module-binder m) m v #f)))))
1511 ;; module-variable module symbol
1513 ;; like module-local-variable, except search the uses in the
1514 ;; case V is not found in M.
1516 (define (module-variable m v)
1517 (module-search module-local-variable m v))
1520 ;;; {Mapping modules x symbols --> bindings}
1522 ;;; These are similar to the mapping to variables, except that the
1523 ;;; variable is dereferenced.
1526 ;; module-symbol-binding module symbol opt-value
1528 ;; return the binding of a variable specified by name within
1529 ;; a given module, signalling an error if the variable is unbound.
1530 ;; If the OPT-VALUE is passed, then instead of signalling an error,
1531 ;; return OPT-VALUE.
1533 (define (module-symbol-local-binding m v . opt-val)
1534 (let ((var (module-local-variable m v)))
1537 (if (not (null? opt-val))
1539 (error "Locally unbound variable." v)))))
1541 ;; module-symbol-binding module symbol opt-value
1543 ;; return the binding of a variable specified by name within
1544 ;; a given module, signalling an error if the variable is unbound.
1545 ;; If the OPT-VALUE is passed, then instead of signalling an error,
1546 ;; return OPT-VALUE.
1548 (define (module-symbol-binding m v . opt-val)
1549 (let ((var (module-variable m v)))
1552 (if (not (null? opt-val))
1554 (error "Unbound variable." v)))))
1558 ;;; {Adding Variables to Modules}
1563 ;; module-make-local-var! module symbol
1565 ;; ensure a variable for V in the local namespace of M.
1566 ;; If no variable was already there, then create a new and uninitialzied
1569 (define (module-make-local-var! m v)
1570 (or (let ((b (module-obarray-ref (module-obarray m) v)))
1571 (and (variable? b) b))
1572 (and (module-binder m)
1573 ((module-binder m) m v #t))
1575 (let ((answer (make-undefined-variable v)))
1576 (module-obarray-set! (module-obarray m) v answer)
1579 ;; module-add! module symbol var
1581 ;; ensure a particular variable for V in the local namespace of M.
1583 (define (module-add! m v var)
1584 (if (not (variable? var))
1585 (error "Bad variable to module-add!" var))
1586 (module-obarray-set! (module-obarray m) v var))
1590 ;; make sure that a symbol is undefined in the local namespace of M.
1592 (define (module-remove! m v)
1593 (module-obarray-remove! (module-obarray m) v))
1595 (define (module-clear! m)
1596 (vector-fill! (module-obarray m) '()))
1598 ;; MODULE-FOR-EACH -- exported
1600 ;; Call PROC on each symbol in MODULE, with arguments of (SYMBOL VARIABLE).
1602 (define (module-for-each proc module)
1603 (let ((obarray (module-obarray module)))
1604 (do ((index 0 (+ index 1))
1605 (end (vector-length obarray)))
1609 (proc (car bucket) (cdr bucket)))
1610 (vector-ref obarray index)))))
1613 (define (module-map proc module)
1614 (let* ((obarray (module-obarray module))
1615 (end (vector-length obarray)))
1623 (map (lambda (bucket)
1624 (proc (car bucket) (cdr bucket)))
1625 (vector-ref obarray i))
1629 ;;; {Low Level Bootstrapping}
1634 ;; A root module uses the symhash table (the system's privileged
1635 ;; obarray). Being inside a root module is like using SCM without
1636 ;; any module system.
1640 (define (root-module-closure m s define?)
1641 (let ((bi (and (symbol-interned? #f s)
1642 (builtin-variable s))))
1644 (or define? (variable-bound? bi))
1646 (module-add! m s bi)
1649 (define (make-root-module)
1650 (make-module 1019 '() root-module-closure))
1655 ;; An scm module is a module into which the lazy binder copies
1656 ;; variable bindings from the system symhash table. The mapping is
1657 ;; one way only; newly introduced bindings in an scm module are not
1658 ;; copied back into the system symhash table (and can be used to override
1659 ;; bindings from the symhash table).
1662 (define (make-scm-module)
1663 (make-module 1019 '()
1664 (lambda (m s define?)
1665 (let ((bi (and (symbol-interned? #f s)
1666 (builtin-variable s))))
1668 (variable-bound? bi)
1670 (module-add! m s bi)
1678 ;; NOTE: This binding is used in libguile/modules.c.
1680 (define the-module #f)
1682 ;; scm:eval-transformer
1684 (define scm:eval-transformer #f)
1686 ;; set-current-module module
1688 ;; set the current module as viewed by the normalizer.
1690 ;; NOTE: This binding is used in libguile/modules.c.
1692 (define (set-current-module m)
1696 (set! *top-level-lookup-closure* (module-eval-closure the-module))
1697 (set! scm:eval-transformer (module-transformer the-module)))
1698 (set! *top-level-lookup-closure* #f)))
1703 ;; return the current module as viewed by the normalizer.
1705 (define (current-module) the-module)
1707 ;;; {Module-based Loading}
1710 (define (save-module-excursion thunk)
1711 (let ((inner-module (current-module))
1713 (dynamic-wind (lambda ()
1714 (set! outer-module (current-module))
1715 (set-current-module inner-module)
1716 (set! inner-module #f))
1719 (set! inner-module (current-module))
1720 (set-current-module outer-module)
1721 (set! outer-module #f)))))
1723 (define basic-load load)
1725 (define (load-module filename)
1726 (save-module-excursion
1728 (let ((oldname (and (current-load-port)
1729 (port-filename (current-load-port)))))
1730 (basic-load (if (and oldname
1731 (> (string-length filename) 0)
1732 (not (char=? (string-ref filename 0) #\/))
1733 (not (string=? (dirname oldname) ".")))
1734 (string-append (dirname oldname) "/" filename)
1739 ;;; {MODULE-REF -- exported}
1741 ;; Returns the value of a variable called NAME in MODULE or any of its
1742 ;; used modules. If there is no such variable, then if the optional third
1743 ;; argument DEFAULT is present, it is returned; otherwise an error is signaled.
1745 (define (module-ref module name . rest)
1746 (let ((variable (module-variable module name)))
1747 (if (and variable (variable-bound? variable))
1748 (variable-ref variable)
1750 (error "No variable named" name 'in module)
1751 (car rest) ; default value
1754 ;; MODULE-SET! -- exported
1756 ;; Sets the variable called NAME in MODULE (or in a module that MODULE uses)
1757 ;; to VALUE; if there is no such variable, an error is signaled.
1759 (define (module-set! module name value)
1760 (let ((variable (module-variable module name)))
1762 (variable-set! variable value)
1763 (error "No variable named" name 'in module))))
1765 ;; MODULE-DEFINE! -- exported
1767 ;; Sets the variable called NAME in MODULE to VALUE; if there is no such
1768 ;; variable, it is added first.
1770 (define (module-define! module name value)
1771 (let ((variable (module-local-variable module name)))
1773 (variable-set! variable value)
1774 (module-add! module name (make-variable value name)))))
1776 ;; MODULE-DEFINED? -- exported
1778 ;; Return #t iff NAME is defined in MODULE (or in a module that MODULE
1781 (define (module-defined? module name)
1782 (let ((variable (module-variable module name)))
1783 (and variable (variable-bound? variable))))
1785 ;; MODULE-USE! module interface
1787 ;; Add INTERFACE to the list of interfaces used by MODULE.
1789 (define (module-use! module interface)
1790 (set-module-uses! module
1791 (cons interface (delq! interface (module-uses module)))))
1794 ;;; {Recursive Namespaces}
1797 ;;; A hierarchical namespace emerges if we consider some module to be
1798 ;;; root, and variables bound to modules as nested namespaces.
1800 ;;; The routines in this file manage variable names in hierarchical namespace.
1801 ;;; Each variable name is a list of elements, looked up in successively nested
1804 ;;; (nested-ref some-root-module '(foo bar baz))
1805 ;;; => <value of a variable named baz in the module bound to bar in
1806 ;;; the module bound to foo in some-root-module>
1811 ;;; ;; a-root is a module
1812 ;;; ;; name is a list of symbols
1814 ;;; nested-ref a-root name
1815 ;;; nested-set! a-root name val
1816 ;;; nested-define! a-root name val
1817 ;;; nested-remove! a-root name
1820 ;;; (current-module) is a natural choice for a-root so for convenience there are
1823 ;;; local-ref name == nested-ref (current-module) name
1824 ;;; local-set! name val == nested-set! (current-module) name val
1825 ;;; local-define! name val == nested-define! (current-module) name val
1826 ;;; local-remove! name == nested-remove! (current-module) name
1830 (define (nested-ref root names)
1831 (let loop ((cur root)
1835 ((not (module? cur)) #f)
1836 (else (loop (module-ref cur (car elts) #f) (cdr elts))))))
1838 (define (nested-set! root names val)
1839 (let loop ((cur root)
1841 (if (null? (cdr elts))
1842 (module-set! cur (car elts) val)
1843 (loop (module-ref cur (car elts)) (cdr elts)))))
1845 (define (nested-define! root names val)
1846 (let loop ((cur root)
1848 (if (null? (cdr elts))
1849 (module-define! cur (car elts) val)
1850 (loop (module-ref cur (car elts)) (cdr elts)))))
1852 (define (nested-remove! root names)
1853 (let loop ((cur root)
1855 (if (null? (cdr elts))
1856 (module-remove! cur (car elts))
1857 (loop (module-ref cur (car elts)) (cdr elts)))))
1859 (define (local-ref names) (nested-ref (current-module) names))
1860 (define (local-set! names val) (nested-set! (current-module) names val))
1861 (define (local-define names val) (nested-define! (current-module) names val))
1862 (define (local-remove names) (nested-remove! (current-module) names))
1866 ;;; {The (app) module}
1868 ;;; The root of conventionally named objects not directly in the top level.
1871 ;;; (app modules guile)
1873 ;;; The directory of all modules and the standard root module.
1876 (define (module-public-interface m) (module-ref m '%module-public-interface #f))
1877 (define (set-module-public-interface! m i) (module-define! m '%module-public-interface i))
1878 (define the-root-module (make-root-module))
1879 (define the-scm-module (make-scm-module))
1880 (set-module-public-interface! the-root-module the-scm-module)
1881 (set-module-name! the-root-module 'the-root-module)
1882 (set-module-name! the-scm-module 'the-scm-module)
1884 (set-current-module the-root-module)
1886 (define app (make-module 31))
1887 (local-define '(app modules) (make-module 31))
1888 (local-define '(app modules guile) the-root-module)
1890 ;; (define-special-value '(app modules new-ws) (lambda () (make-scm-module)))
1892 (define (resolve-module name . maybe-autoload)
1893 (let ((full-name (append '(app modules) name)))
1894 (let ((already (local-ref full-name)))
1897 (if (or (null? maybe-autoload) (car maybe-autoload))
1898 (or (try-module-linked name)
1899 (try-module-autoload name)
1900 (try-module-dynamic-link name)))
1901 (make-modules-in (current-module) full-name))))))
1903 (define (beautify-user-module! module)
1904 (let ((interface (module-public-interface module)))
1905 (if (or (not interface)
1906 (eq? interface module))
1907 (let ((interface (make-module 31)))
1908 (set-module-name! interface (module-name module))
1909 (set-module-kind! interface 'interface)
1910 (set-module-public-interface! module interface))))
1911 (if (and (not (memq the-scm-module (module-uses module)))
1912 (not (eq? module the-root-module)))
1913 (set-module-uses! module (append (module-uses module) (list the-scm-module)))))
1915 ;; NOTE: This binding is used in libguile/modules.c.
1917 (define (make-modules-in module name)
1921 ((module-ref module (car name) #f)
1922 => (lambda (m) (make-modules-in m (cdr name))))
1923 (else (let ((m (make-module 31)))
1924 (set-module-kind! m 'directory)
1925 (set-module-name! m (car name))
1926 (module-define! module (car name) m)
1927 (make-modules-in m (cdr name)))))))
1929 (define (resolve-interface name)
1930 (let ((module (resolve-module name)))
1931 (and module (module-public-interface module))))
1934 (define %autoloader-developer-mode #t)
1936 (define (internal-use-syntax transformer)
1937 (set-module-transformer! (current-module) transformer)
1938 (set! scm:eval-transformer transformer))
1940 (define (process-define-module args)
1941 (let* ((module-id (car args))
1942 (module (resolve-module module-id #f))
1944 (beautify-user-module! module)
1945 (let loop ((kws kws)
1946 (reversed-interfaces '()))
1948 (for-each (lambda (interface)
1949 (module-use! module interface))
1950 reversed-interfaces)
1951 (let ((keyword (cond ((keyword? (car kws))
1952 (keyword->symbol (car kws)))
1953 ((and (symbol? (car kws))
1954 (eq? (string-ref (car kws) 0) #\:))
1955 (string->symbol (substring (car kws) 1)))
1958 ((use-module use-syntax)
1959 (if (not (pair? (cdr kws)))
1960 (error "unrecognized defmodule argument" kws))
1961 (let* ((used-name (cadr kws))
1962 (used-module (resolve-module used-name)))
1963 (if (eq? used-module module)
1965 (or (try-module-linked used-name)
1966 (try-module-dynamic-link used-name))
1967 (loop (cddr kws) reversed-interfaces))
1969 (if (not (module-ref used-module
1970 '%module-public-interface
1973 ((if %autoloader-developer-mode warn error)
1974 "no code for module" (module-name used-module))
1975 (beautify-user-module! used-module)))
1976 (let ((interface (module-public-interface used-module)))
1978 (error "missing interface for use-module"
1980 (if (eq? keyword 'use-syntax)
1981 (internal-use-syntax
1982 (module-ref interface (car (last-pair used-name))
1985 (cons interface reversed-interfaces)))))))
1987 (error "unrecognized defmodule argument" kws))))))
1990 ;;; {Autoloading modules}
1992 (define autoloads-in-progress '())
1994 (define (try-module-autoload module-name)
1996 (define (sfx name) (string-append name (scheme-file-suffix)))
1997 (let* ((reverse-name (reverse module-name))
1998 (name (car reverse-name))
1999 (dir-hint-module-name (reverse (cdr reverse-name)))
2000 (dir-hint (apply symbol-append (map (lambda (elt) (symbol-append elt "/")) dir-hint-module-name))))
2001 (resolve-module dir-hint-module-name #f)
2002 (and (not (autoload-done-or-in-progress? dir-hint name))
2005 (lambda () (autoload-in-progress! dir-hint name))
2007 (let loop ((dirs %load-path))
2008 (and (not (null? dirs))
2010 (let ((d (car dirs))
2014 (in-vicinity dir-hint name)
2015 (in-vicinity dir-hint (sfx name)))))
2016 (and (or-map (lambda (f)
2017 (let ((full (in-vicinity d f)))
2019 (and (file-exists? full)
2020 (not (file-is-directory? full))
2022 (save-module-excursion
2024 (load (string-append
2031 (loop (cdr dirs))))))
2032 (lambda () (set-autoloaded! dir-hint name didit)))
2035 ;;; Dynamic linking of modules
2037 ;; Initializing a module that is written in C is a two step process.
2038 ;; First the module's `module init' function is called. This function
2039 ;; is expected to call `scm_register_module_xxx' to register the `real
2040 ;; init' function. Later, when the module is referenced for the first
2041 ;; time, this real init function is called in the right context. See
2042 ;; gtcltk-lib/gtcltk-module.c for an example.
2044 ;; The code for the module can be in a regular shared library (so that
2045 ;; the `module init' function will be called when libguile is
2046 ;; initialized). Or it can be dynamically linked.
2048 ;; You can safely call `scm_register_module_xxx' before libguile
2049 ;; itself is initialized. You could call it from an C++ constructor
2050 ;; of a static object, for example.
2052 ;; To make your Guile extension into a dynamic linkable module, follow
2053 ;; these easy steps:
2055 ;; - Find a name for your module, like (ice-9 gtcltk)
2056 ;; - Write a function with a name like
2058 ;; scm_init_ice_9_gtcltk_module
2060 ;; This is your `module init' function. It should call
2062 ;; scm_register_module_xxx ("ice-9 gtcltk", scm_init_gtcltk);
2064 ;; "ice-9 gtcltk" is the C version of the module name. Slashes are
2065 ;; replaced by spaces, the rest is untouched. `scm_init_gtcltk' is
2066 ;; the real init function that executes the usual initializations
2067 ;; like making new smobs, etc.
2069 ;; - Make a shared library with your code and a name like
2071 ;; ice-9/libgtcltk.so
2073 ;; and put it somewhere in %load-path.
2075 ;; - Then you can simply write `:use-module (ice-9 gtcltk)' and it
2076 ;; will be linked automatically.
2078 ;; This is all very experimental.
2080 (define (split-c-module-name str)
2081 (let loop ((rev '())
2084 (end (string-length str)))
2087 (reverse (cons (string->symbol (substring str start pos)) rev)))
2088 ((eq? (string-ref str pos) #\space)
2089 (loop (cons (string->symbol (substring str start pos)) rev)
2094 (loop rev start (+ pos 1) end)))))
2096 (define (convert-c-registered-modules dynobj)
2097 (let ((res (map (lambda (c)
2098 (list (split-c-module-name (car c)) (cdr c) dynobj))
2099 (c-registered-modules))))
2100 (c-clear-registered-modules)
2103 (define registered-modules '())
2105 (define (register-modules dynobj)
2106 (set! registered-modules
2107 (append! (convert-c-registered-modules dynobj)
2108 registered-modules)))
2110 (define (init-dynamic-module modname)
2111 ;; Register any linked modules which has been registered on the C level
2112 (register-modules #f)
2113 (or-map (lambda (modinfo)
2114 (if (equal? (car modinfo) modname)
2116 (set! registered-modules (delq! modinfo registered-modules))
2117 (let ((mod (resolve-module modname #f)))
2118 (save-module-excursion
2120 (set-current-module mod)
2121 (set-module-public-interface! mod mod)
2122 (dynamic-call (cadr modinfo) (caddr modinfo))
2126 registered-modules))
2128 (define (dynamic-maybe-call name dynobj)
2129 (catch #t ; could use false-if-exception here
2131 (dynamic-call name dynobj))
2135 (define (dynamic-maybe-link filename)
2136 (catch #t ; could use false-if-exception here
2138 (dynamic-link filename))
2142 (define (find-and-link-dynamic-module module-name)
2143 (define (make-init-name mod-name)
2144 (string-append 'scm_init
2145 (list->string (map (lambda (c)
2146 (if (or (char-alphabetic? c)
2150 (string->list mod-name)))
2153 ;; Put the subdirectory for this module in the car of SUBDIR-AND-LIBNAME,
2154 ;; and the `libname' (the name of the module prepended by `lib') in the cdr
2155 ;; field. For example, if MODULE-NAME is the list (inet tcp-ip udp), then
2156 ;; SUBDIR-AND-LIBNAME will be the pair ("inet/tcp-ip" . "libudp").
2157 (let ((subdir-and-libname
2158 (let loop ((dirs "")
2160 (if (null? (cdr syms))
2161 (cons dirs (string-append "lib" (car syms)))
2162 (loop (string-append dirs (car syms) "/") (cdr syms)))))
2163 (init (make-init-name (apply string-append
2165 (string-append "_" s))
2167 (let ((subdir (car subdir-and-libname))
2168 (libname (cdr subdir-and-libname)))
2170 ;; Now look in each dir in %LOAD-PATH for `subdir/libfoo.la'. If that
2171 ;; file exists, fetch the dlname from that file and attempt to link
2172 ;; against it. If `subdir/libfoo.la' does not exist, or does not seem
2173 ;; to name any shared library, look for `subdir/libfoo.so' instead and
2174 ;; link against that.
2175 (let check-dirs ((dir-list %load-path))
2176 (if (null? dir-list)
2178 (let* ((dir (in-vicinity (car dir-list) subdir))
2180 (or (try-using-libtool-name dir libname)
2181 (try-using-sharlib-name dir libname))))
2182 (if (and sharlib-full (file-exists? sharlib-full))
2183 (link-dynamic-module sharlib-full init)
2184 (check-dirs (cdr dir-list)))))))))
2186 (define (try-using-libtool-name libdir libname)
2187 (let ((libtool-filename (in-vicinity libdir
2188 (string-append libname ".la"))))
2189 (and (file-exists? libtool-filename)
2190 (with-input-from-file libtool-filename
2192 (let loop ((ln (read-line)))
2193 (cond ((eof-object? ln) #f)
2194 ((and (>= (string-length ln) 8)
2195 (string=? "dlname='" (substring ln 0 8))
2196 (string-index ln #\' 8))
2199 (in-vicinity libdir (substring ln 8 end))))
2200 (else (loop (read-line))))))))))
2202 (define (try-using-sharlib-name libdir libname)
2203 (in-vicinity libdir (string-append libname ".so")))
2205 (define (link-dynamic-module filename initname)
2206 ;; Register any linked modules which has been registered on the C level
2207 (register-modules #f)
2208 (let ((dynobj (dynamic-link filename)))
2209 (dynamic-call initname dynobj)
2210 (register-modules dynobj)))
2212 (define (try-module-linked module-name)
2213 (init-dynamic-module module-name))
2215 (define (try-module-dynamic-link module-name)
2216 (and (find-and-link-dynamic-module module-name)
2217 (init-dynamic-module module-name)))
2221 (define autoloads-done '((guile . guile)))
2223 (define (autoload-done-or-in-progress? p m)
2224 (let ((n (cons p m)))
2225 (->bool (or (member n autoloads-done)
2226 (member n autoloads-in-progress)))))
2228 (define (autoload-done! p m)
2229 (let ((n (cons p m)))
2230 (set! autoloads-in-progress
2231 (delete! n autoloads-in-progress))
2232 (or (member n autoloads-done)
2233 (set! autoloads-done (cons n autoloads-done)))))
2235 (define (autoload-in-progress! p m)
2236 (let ((n (cons p m)))
2237 (set! autoloads-done
2238 (delete! n autoloads-done))
2239 (set! autoloads-in-progress (cons n autoloads-in-progress))))
2241 (define (set-autoloaded! p m done?)
2243 (autoload-done! p m)
2244 (let ((n (cons p m)))
2245 (set! autoloads-done (delete! n autoloads-done))
2246 (set! autoloads-in-progress (delete! n autoloads-in-progress)))))
2255 (define (primitive-macro? m)
2257 (not (macro-transformer m))))
2261 (define macro-table (make-weak-key-hash-table 523))
2262 (define xformer-table (make-weak-key-hash-table 523))
2264 (define (defmacro? m) (hashq-ref macro-table m))
2265 (define (assert-defmacro?! m) (hashq-set! macro-table m #t))
2266 (define (defmacro-transformer m) (hashq-ref xformer-table m))
2267 (define (set-defmacro-transformer! m t) (hashq-set! xformer-table m t))
2269 (define defmacro:transformer
2271 (let* ((xform (lambda (exp env)
2272 (copy-tree (apply f (cdr exp)))))
2273 (a (procedure->memoizing-macro xform)))
2274 (assert-defmacro?! a)
2275 (set-defmacro-transformer! a f)
2280 (let ((defmacro-transformer
2281 (lambda (name parms . body)
2282 (let ((transformer `(lambda ,parms ,@body)))
2284 (,(lambda (transformer)
2285 (defmacro:transformer transformer))
2287 (defmacro:transformer defmacro-transformer)))
2289 (define defmacro:syntax-transformer
2293 (copy-tree (apply f (cdr exp)))))))
2296 ;; XXX - should the definition of the car really be looked up in the
2299 (define (macroexpand-1 e)
2301 ((pair? e) (let* ((a (car e))
2302 (val (and (symbol? a) (local-ref (list a)))))
2304 (apply (defmacro-transformer val) (cdr e))
2308 (define (macroexpand e)
2310 ((pair? e) (let* ((a (car e))
2311 (val (and (symbol? a) (local-ref (list a)))))
2313 (macroexpand (apply (defmacro-transformer val) (cdr e)))
2324 ;;; {Run-time options}
2326 ((let* ((names '((eval-options-interface
2327 (eval-options eval-enable eval-disable)
2330 (debug-options-interface
2331 (debug-options debug-enable debug-disable)
2334 (evaluator-traps-interface
2335 (traps trap-enable trap-disable)
2338 (read-options-interface
2339 (read-options read-enable read-disable)
2342 (print-options-interface
2343 (print-options print-enable print-disable)
2346 (readline-options-interface
2347 (readline-options readline-enable readline-disable)
2352 (option-documentation caddr)
2354 (print-option (lambda (option)
2355 (display (option-name option))
2356 (if (< (string-length
2357 (symbol->string (option-name option)))
2361 (display (option-value option))
2363 (display (option-documentation option))
2366 ;; Below follows the macros defining the run-time option interfaces.
2368 (make-options (lambda (interface)
2370 (cond ((null? args) (,interface))
2372 (,interface (car args)) (,interface))
2373 (else (for-each ,print-option
2374 (,interface #t)))))))
2376 (make-enable (lambda (interface)
2378 (,interface (append flags (,interface)))
2381 (make-disable (lambda (interface)
2383 (let ((options (,interface)))
2384 (for-each (lambda (flag)
2385 (set! options (delq! flag options)))
2387 (,interface options)
2390 (make-set! (lambda (interface)
2393 (begin (,interface (append (,interface)
2394 (list '(,'unquote name)
2402 (map (lambda (group)
2403 (let ((interface (car group)))
2404 (append (map (lambda (name constructor)
2406 ,(constructor interface)))
2411 (map (lambda (name constructor)
2413 ,@(constructor interface)))
2415 (list make-set!)))))
2423 (define (repl read evaler print)
2424 (let loop ((source (read (current-input-port))))
2425 (print (evaler source))
2426 (loop (read (current-input-port)))))
2428 ;; A provisional repl that acts like the SCM repl:
2430 (define scm-repl-silent #f)
2431 (define (assert-repl-silence v) (set! scm-repl-silent v))
2433 (define *unspecified* (if #f #f))
2434 (define (unspecified? v) (eq? v *unspecified*))
2436 (define scm-repl-print-unspecified #f)
2437 (define (assert-repl-print-unspecified v) (set! scm-repl-print-unspecified v))
2439 (define scm-repl-verbose #f)
2440 (define (assert-repl-verbosity v) (set! scm-repl-verbose v))
2442 (define scm-repl-prompt "guile> ")
2444 (define (set-repl-prompt! v) (set! scm-repl-prompt v))
2446 (define (default-lazy-handler key . args)
2447 (save-stack lazy-handler-dispatch)
2448 (apply throw key args))
2450 (define enter-frame-handler default-lazy-handler)
2451 (define apply-frame-handler default-lazy-handler)
2452 (define exit-frame-handler default-lazy-handler)
2454 (define (lazy-handler-dispatch key . args)
2457 (apply apply-frame-handler key args))
2459 (apply exit-frame-handler key args))
2461 (apply enter-frame-handler key args))
2463 (apply default-lazy-handler key args))))
2465 (define abort-hook (make-hook))
2467 ;; these definitions are used if running a script.
2468 ;; otherwise redefined in error-catching-loop.
2469 (define (set-batch-mode?! arg) #t)
2470 (define (batch-mode?) #t)
2472 (define (error-catching-loop thunk)
2475 (set! set-batch-mode?! (lambda (arg)
2477 (set! interactive #f)
2480 (error "sorry, not implemented")))))
2481 (set! batch-mode? (lambda () (not interactive)))
2482 (define (loop first)
2490 (lambda () (unmask-signals))
2496 ;; This line is needed because mark
2497 ;; doesn't do closures quite right.
2498 ;; Unreferenced locals should be
2502 (let loop ((v (thunk)))
2505 (lambda () (mask-signals))))
2507 lazy-handler-dispatch))
2509 (lambda (key . args)
2517 (apply throw 'switch-repl args))
2520 ;; This is one of the closures that require
2521 ;; (set! first #f) above
2524 (run-hook abort-hook)
2526 (display "ABORT: " (current-error-port))
2527 (write args (current-error-port))
2528 (newline (current-error-port))
2530 (if (and (not has-shown-debugger-hint?)
2531 (not (memq 'backtrace
2532 (debug-options-interface)))
2533 (stack? (fluid-ref the-last-stack)))
2535 (newline (current-error-port))
2537 "Type \"(backtrace)\" to get more information.\n"
2538 (current-error-port))
2539 (set! has-shown-debugger-hint? #t)))
2541 (set! stack-saved? #f)))
2544 ;; This is the other cons-leak closure...
2546 (cond ((= (length args) 4)
2547 (apply handle-system-error key args))
2549 (apply bad-throw key args))))))))))
2550 (if next (loop next) status)))
2551 (loop (lambda () #t))))
2553 ;;(define the-last-stack (make-fluid)) Defined by scm_init_backtrace ()
2554 (define stack-saved? #f)
2556 (define (save-stack . narrowing)
2557 (cond (stack-saved?)
2558 ((not (memq 'debug (debug-options-interface)))
2559 (fluid-set! the-last-stack #f)
2560 (set! stack-saved? #t))
2566 (apply make-stack #t save-stack eval narrowing))
2568 (apply make-stack #t save-stack 0 narrowing))
2570 (apply make-stack #t save-stack tk-stack-mark narrowing))
2572 (apply make-stack #t save-stack 0 1 narrowing))
2573 (else (let ((id (stack-id #t)))
2574 (and (procedure? id)
2575 (apply make-stack #t save-stack id narrowing))))))
2576 (set! stack-saved? #t))))
2578 (define before-error-hook (make-hook))
2579 (define after-error-hook (make-hook))
2580 (define before-backtrace-hook (make-hook))
2581 (define after-backtrace-hook (make-hook))
2583 (define has-shown-debugger-hint? #f)
2585 (define (handle-system-error key . args)
2586 (let ((cep (current-error-port)))
2587 (cond ((not (stack? (fluid-ref the-last-stack))))
2588 ((memq 'backtrace (debug-options-interface))
2589 (run-hook before-backtrace-hook)
2591 (display-backtrace (fluid-ref the-last-stack) cep)
2593 (run-hook after-backtrace-hook)))
2594 (run-hook before-error-hook)
2595 (apply display-error (fluid-ref the-last-stack) cep args)
2596 (run-hook after-error-hook)
2598 (throw 'abort key)))
2600 (define (quit . args)
2601 (apply throw 'quit args))
2605 ;;(define has-shown-backtrace-hint? #f) Defined by scm_init_backtrace ()
2607 ;; Replaced by C code:
2608 ;;(define (backtrace)
2609 ;; (if (fluid-ref the-last-stack)
2612 ;; (display-backtrace (fluid-ref the-last-stack) (current-output-port))
2614 ;; (if (and (not has-shown-backtrace-hint?)
2615 ;; (not (memq 'backtrace (debug-options-interface))))
2618 ;;"Type \"(debug-enable 'backtrace)\" if you would like a backtrace
2619 ;;automatically if an error occurs in the future.\n")
2620 ;; (set! has-shown-backtrace-hint? #t))))
2621 ;; (display "No backtrace available.\n")))
2623 (define (error-catching-repl r e p)
2624 (error-catching-loop (lambda () (p (e (r))))))
2626 (define (gc-run-time)
2627 (cdr (assq 'gc-time-taken (gc-stats))))
2629 (define before-read-hook (make-hook))
2630 (define after-read-hook (make-hook))
2632 ;;; The default repl-reader function. We may override this if we've
2633 ;;; the readline library.
2638 (run-hook before-read-hook)
2639 (read (current-input-port))))
2641 (define (scm-style-repl)
2645 (repl-report-start-timing (lambda ()
2646 (set! start-gc-rt (gc-run-time))
2647 (set! start-rt (get-internal-run-time))))
2648 (repl-report (lambda ()
2650 (display (inexact->exact
2651 (* 1000 (/ (- (get-internal-run-time) start-rt)
2652 internal-time-units-per-second))))
2654 (display (inexact->exact
2655 (* 1000 (/ (- (gc-run-time) start-gc-rt)
2656 internal-time-units-per-second))))
2657 (display " msec in gc)\n")))
2659 (consume-trailing-whitespace
2661 (let ((ch (peek-char)))
2664 ((or (char=? ch #\space) (char=? ch #\tab))
2666 (consume-trailing-whitespace))
2667 ((char=? ch #\newline)
2671 (let ((prompt (cond ((string? scm-repl-prompt)
2673 ((thunk? scm-repl-prompt)
2675 (scm-repl-prompt "> ")
2677 (repl-reader prompt))))
2679 ;; As described in R4RS, the READ procedure updates the
2680 ;; port to point to the first characetr past the end of
2681 ;; the external representation of the object. This
2682 ;; means that it doesn't consume the newline typically
2683 ;; found after an expression. This means that, when
2684 ;; debugging Guile with GDB, GDB gets the newline, which
2685 ;; it often interprets as a "continue" command, making
2686 ;; breakpoints kind of useless. So, consume any
2687 ;; trailing newline here, as well as any whitespace
2689 (consume-trailing-whitespace)
2690 (run-hook after-read-hook)
2691 (if (eof-object? val)
2693 (repl-report-start-timing)
2694 (if scm-repl-verbose
2697 (display ";;; EOF -- quitting")
2702 (-eval (lambda (sourc)
2703 (repl-report-start-timing)
2704 (start-stack 'repl-stack (eval sourc))))
2706 (-print (lambda (result)
2707 (if (not scm-repl-silent)
2709 (if (or scm-repl-print-unspecified
2710 (not (unspecified? result)))
2714 (if scm-repl-verbose
2718 (-quit (lambda (args)
2719 (if scm-repl-verbose
2721 (display ";;; QUIT executed, repl exitting")
2727 (if scm-repl-verbose
2729 (display ";;; ABORT executed.")
2732 (repl -read -eval -print))))
2734 (let ((status (error-catching-repl -read
2741 ;;; {IOTA functions: generating lists of numbers}
2743 (define (reverse-iota n) (if (> n 0) (cons (1- n) (reverse-iota (1- n))) '()))
2744 (define (iota n) (reverse! (reverse-iota n)))
2749 ;;; with `continue' and `break'.
2752 (defmacro while (cond . body)
2753 `(letrec ((continue (lambda () (or (not ,cond) (begin (begin ,@ body) (continue)))))
2754 (break (lambda val (apply throw 'break val))))
2756 (lambda () (continue))
2757 (lambda v (cadr v)))))
2761 ;;; Similar to `begin' but returns a list of the results of all constituent
2762 ;;; forms instead of the result of the last form.
2763 ;;; (The definition relies on the current left-to-right
2764 ;;; order of evaluation of operands in applications.)
2766 (defmacro collect forms
2771 ;; with-fluids is a convenience wrapper for the builtin procedure
2772 ;; `with-fluids*'. The syntax is just like `let':
2774 ;; (with-fluids ((fluid val)
2778 (defmacro with-fluids (bindings . body)
2779 `(with-fluids* (list ,@(map car bindings)) (list ,@(map cadr bindings))
2780 (lambda () ,@body)))
2784 (define the-environment
2794 ;; actually....hobbit might be able to hack these with a little
2798 (defmacro define-macro (first . rest)
2799 (let ((name (if (symbol? first) first (car first)))
2803 `(lambda ,(cdr first) ,@rest))))
2804 `(define ,name (defmacro:transformer ,transformer))))
2807 (defmacro define-syntax-macro (first . rest)
2808 (let ((name (if (symbol? first) first (car first)))
2812 `(lambda ,(cdr first) ,@rest))))
2813 `(define ,name (defmacro:syntax-transformer ,transformer))))
2815 ;;; {Module System Macros}
2818 (defmacro define-module args
2819 `(let* ((process-define-module process-define-module)
2820 (set-current-module set-current-module)
2821 (module (process-define-module ',args)))
2822 (set-current-module module)
2825 ;; the guts of the use-modules macro. add the interfaces of the named
2826 ;; modules to the use-list of the current module, in order
2827 (define (process-use-modules module-names)
2828 (for-each (lambda (module-name)
2829 (let ((mod-iface (resolve-interface module-name)))
2831 (error "no such module" module-name))
2832 (module-use! (current-module) mod-iface)))
2833 (reverse module-names)))
2835 (defmacro use-modules modules
2836 `(process-use-modules ',modules))
2838 (defmacro use-syntax (spec)
2841 (process-use-modules ',(list spec))
2842 (internal-use-syntax ,(car (last-pair spec))))
2843 `(internal-use-syntax ,spec)))
2845 (define define-private define)
2847 (defmacro define-public args
2849 (error "bad syntax" (list 'define-public args)))
2850 (define (defined-name n)
2853 ((pair? n) (defined-name (car n)))
2856 ((null? args) (syntax))
2858 (#t (let ((name (defined-name (car args))))
2860 (let ((public-i (module-public-interface (current-module))))
2861 ;; Make sure there is a local variable:
2863 (module-define! (current-module)
2865 (module-ref (current-module) ',name #f))
2867 ;; Make sure that local is exported:
2869 (module-add! public-i ',name
2870 (module-variable (current-module) ',name)))
2872 ;; Now (re)define the var normally. Bernard URBAN
2873 ;; suggests we use eval here to accomodate Hobbit; it lets
2874 ;; the interpreter handle the define-private form, which
2875 ;; Hobbit can't digest.
2876 (eval '(define-private ,@ args)))))))
2880 (defmacro defmacro-public args
2882 (error "bad syntax" (list 'defmacro-public args)))
2883 (define (defined-name n)
2888 ((null? args) (syntax))
2890 (#t (let ((name (defined-name (car args))))
2892 (let ((public-i (module-public-interface (current-module))))
2893 ;; Make sure there is a local variable:
2895 (module-define! (current-module)
2897 (module-ref (current-module) ',name #f))
2899 ;; Make sure that local is exported:
2901 (module-add! public-i ',name (module-variable (current-module) ',name)))
2903 ;; Now (re)define the var normally.
2905 (defmacro ,@ args))))))
2908 (defmacro export names
2909 `(let* ((m (current-module))
2910 (public-i (module-public-interface m)))
2911 (for-each (lambda (name)
2912 ;; Make sure there is a local variable:
2913 (module-define! m name (module-ref m name #f))
2914 ;; Make sure that local is exported:
2915 (module-add! public-i name (module-variable m name)))
2918 (define export-syntax export)
2923 (define load load-module)
2927 ;;; {Load emacs interface support if emacs option is given.}
2929 (define (load-emacs-interface)
2930 (if (memq 'debug-extensions *features*)
2931 (debug-enable 'backtrace))
2932 (define-module (guile-user) :use-module (ice-9 emacs)))
2935 ;;; {I/O functions for Tcl channels (disabled)}
2937 ;; (define in-ch (get-standard-channel TCL_STDIN))
2938 ;; (define out-ch (get-standard-channel TCL_STDOUT))
2939 ;; (define err-ch (get-standard-channel TCL_STDERR))
2941 ;; (define inp (%make-channel-port in-ch "r"))
2942 ;; (define outp (%make-channel-port out-ch "w"))
2943 ;; (define errp (%make-channel-port err-ch "w"))
2945 ;; (define %system-char-ready? char-ready?)
2947 ;; (define (char-ready? p)
2948 ;; (if (not (channel-port? p))
2949 ;; (%system-char-ready? p)
2950 ;; (let* ((channel (%channel-port-channel p))
2951 ;; (old-blocking (channel-option-ref channel :blocking)))
2953 ;; (lambda () (set-channel-option the-root-tcl-interpreter channel :blocking "0"))
2954 ;; (lambda () (not (eof-object? (peek-char p))))
2955 ;; (lambda () (set-channel-option the-root-tcl-interpreter channel :blocking old-blocking))))))
2957 ;; (define (top-repl)
2958 ;; (with-input-from-port inp
2960 ;; (with-output-to-port outp
2962 ;; (with-error-to-port errp
2964 ;; (scm-style-repl))))))))
2966 ;; (set-current-input-port inp)
2967 ;; (set-current-output-port outp)
2968 ;; (set-current-error-port errp)
2970 ;; this is just (scm-style-repl) with a wrapper to install and remove
2974 ;; Load emacs interface support if emacs option is given.
2975 (if (and (module-defined? the-root-module 'use-emacs-interface)
2976 use-emacs-interface)
2977 (load-emacs-interface))
2979 ;; Place the user in the guile-user module.
2980 (define-module (guile-user))
2982 (let ((old-handlers #f)
2983 (signals `((,SIGINT . "User interrupt")
2984 (,SIGFPE . "Arithmetic error")
2985 (,SIGBUS . "Bad memory access (bus error)")
2986 (,SIGSEGV . "Bad memory access (Segmentation violation)"))))
2992 (let ((make-handler (lambda (msg)
2994 (save-stack %deliver-signals)
3001 (map (lambda (sig-msg)
3002 (sigaction (car sig-msg)
3003 (make-handler (cdr sig-msg))))
3006 ;; the protected thunk.
3009 ;; If we've got readline, use it to prompt the user. This is a
3010 ;; kludge, but we'll fix it soon. At least we only get
3011 ;; readline involved when we're actually running the repl.
3012 (if (and (memq 'readline *features*)
3013 (isatty? (current-input-port))
3014 (not (and (module-defined? the-root-module
3015 'use-emacs-interface)
3016 use-emacs-interface)))
3017 (let ((read-hook (lambda () (run-hook before-read-hook))))
3018 (set-current-input-port (readline-port))
3023 (set-readline-prompt! prompt)
3024 (set-readline-read-hook! read-hook))
3027 (set-readline-prompt! "")
3028 (set-readline-read-hook! #f)))))))
3029 (let ((status (scm-style-repl)))
3030 (run-hook exit-hook)
3035 (map (lambda (sig-msg old-handler)
3036 (if (not (car old-handler))
3037 ;; restore original C handler.
3038 (sigaction (car sig-msg) #f)
3039 ;; restore Scheme handler, SIG_IGN or SIG_DFL.
3040 (sigaction (car sig-msg)
3042 (cdr old-handler))))
3043 signals old-handlers)))))
3045 (defmacro false-if-exception (expr)
3046 `(catch #t (lambda () ,expr)
3049 ;;; This hook is run at the very end of an interactive session.
3051 (define exit-hook (make-hook))
3053 ;;; Load readline code into root module if readline primitives are available.
3055 ;;; Ideally, we wouldn't do this until we were sure we were actually
3056 ;;; going to enter the repl, but autoloading individual functions is
3057 ;;; clumsy at the moment.
3058 (if (and (memq 'readline *features*)
3059 (isatty? (current-input-port)))
3061 (define-module (guile) :use-module (ice-9 readline))
3062 (define-module (guile-user) :use-module (ice-9 readline))))
3065 ;;; {Load debug extension code into user module if debug extensions present.}
3067 ;;; *fixme* This is a temporary solution.
3070 (if (memq 'debug-extensions *features*)
3071 (define-module (guile-user) :use-module (ice-9 debug)))
3074 ;;; {Load session support into user module if present.}
3076 ;;; *fixme* This is a temporary solution.
3079 (if (%search-load-path "ice-9/session.scm")
3080 (define-module (guile-user) :use-module (ice-9 session)))
3082 ;;; {Load thread code into user module if threads are present.}
3084 ;;; *fixme* This is a temporary solution.
3087 (if (memq 'threads *features*)
3088 (define-module (guile-user) :use-module (ice-9 threads)))
3091 ;;; {Load regexp code if regexp primitives are available.}
3093 (if (memq 'regex *features*)
3094 (define-module (guile-user) :use-module (ice-9 regex)))
3097 (define-module (guile))
3099 ;;; {Check that the interpreter and scheme code match up.}
3103 (with-output-to-port (current-error-port)
3105 (display (car (command-line)))
3107 (for-each (lambda (string) (display string))
3111 (load-from-path "ice-9/version.scm")
3114 (libguile-config-stamp) ; from the interprpreter
3115 (ice-9-config-stamp))) ; from the Scheme code
3117 (show-line "warning: different versions of libguile and ice-9:")
3118 (show-line "libguile: configured on " (libguile-config-stamp))
3119 (show-line "ice-9: configured on " (ice-9-config-stamp)))))
3121 (append! %load-path (cons "." ()))