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))
46 (primitive-load-path "ice-9/r4rs.scm")
49 ;;; {Simple Debugging Tools}
53 ;; peek takes any number of arguments, writes them to the
54 ;; current ouput port, and returns the last argument.
55 ;; It is handy to wrap around an expression to look at
56 ;; a value each time is evaluated, e.g.:
58 ;; (+ 10 (troublesome-fn))
59 ;; => (+ 10 (pk 'troublesome-fn-returned (troublesome-fn)))
62 (define (peek . stuff)
67 (car (last-pair stuff)))
71 (define (warn . stuff)
72 (with-output-to-port (current-error-port)
75 (display ";;; WARNING ")
78 (car (last-pair stuff)))))
81 ;;; {Trivial Functions}
85 (define (1+ n) (+ n 1))
86 (define (-1+ n) (+ n -1))
88 (define return-it noop)
89 (define (and=> value procedure) (and value (procedure value)))
90 (define (make-hash-table k) (make-vector k '()))
92 ;;; apply-to-args is functionally redunant with apply and, worse,
93 ;;; is less general than apply since it only takes two arguments.
95 ;;; On the other hand, apply-to-args is a syntacticly convenient way to
96 ;;; perform binding in many circumstances when the "let" family of
97 ;;; of forms don't cut it. E.g.:
99 ;;; (apply-to-args (return-3d-mouse-coords)
104 (define (apply-to-args args fn) (apply fn args))
110 (define (ipow-by-squaring x k acc proc)
111 (cond ((zero? k) acc)
112 ((= 1 k) (proc acc x))
113 (else (ipow-by-squaring (proc x x)
115 (if (even? k) acc (proc acc x))
118 (define string-character-length string-length)
122 ;; A convenience function for combining flag bits. Like logior, but
123 ;; handles the cases of 0 and 1 arguments.
125 (define (flags . args)
128 ((null? (cdr args)) (car args))
129 (else (apply logior args))))
132 ;;; {Symbol Properties}
135 (define (symbol-property sym prop)
136 (let ((pair (assoc prop (symbol-pref sym))))
137 (and pair (cdr pair))))
139 (define (set-symbol-property! sym prop val)
140 (let ((pair (assoc prop (symbol-pref sym))))
143 (symbol-pset! sym (acons prop val (symbol-pref sym))))))
145 (define (symbol-property-remove! sym prop)
146 (let ((pair (assoc prop (symbol-pref sym))))
148 (symbol-pset! sym (delq! pair (symbol-pref sym))))))
152 ;;; {Line and Delimited I/O}
154 ;;; corresponds to SCM_LINE_INCREMENTORS in libguile.
155 (define scm-line-incrementors "\n")
157 (define (read-line! string . maybe-port)
158 (let* ((port (if (pair? maybe-port)
160 (current-input-port))))
161 (let* ((rv (%read-delimited! scm-line-incrementors
165 (terminator (car rv))
167 (cond ((and (= nchars 0)
168 (eof-object? terminator))
170 ((not terminator) #f)
173 (define (read-delimited! delims buf . args)
174 (let* ((num-args (length args))
175 (port (if (> num-args 0)
177 (current-input-port)))
178 (handle-delim (if (> num-args 1)
181 (start (if (> num-args 2)
184 (end (if (> num-args 3)
186 (string-length buf))))
187 (let* ((rv (%read-delimited! delims
189 (not (eq? handle-delim 'peek))
193 (terminator (car rv))
195 (cond ((or (not terminator) ; buffer filled
196 (eof-object? terminator))
198 (if (eq? handle-delim 'split)
199 (cons terminator terminator)
201 (if (eq? handle-delim 'split)
202 (cons nchars terminator)
207 ((concat) (string-set! buf (+ nchars start) terminator)
209 ((split) (cons nchars terminator))
210 (else (error "unexpected handle-delim value: "
213 (define (read-delimited delims . args)
214 (let* ((port (if (pair? args)
215 (let ((pt (car args)))
216 (set! args (cdr args))
218 (current-input-port)))
219 (handle-delim (if (pair? args)
222 (let loop ((substrings ())
224 (buf-size 100)) ; doubled each time through.
225 (let* ((buf (make-string buf-size))
226 (rv (%read-delimited! delims
228 (not (eq? handle-delim 'peek))
230 (terminator (car rv))
236 (cons (if (and (eq? handle-delim 'concat)
237 (not (eof-object? terminator)))
240 (cons (make-shared-substring buf 0 nchars)
242 (new-total (+ total-chars nchars)))
243 (cond ((not terminator)
245 (loop (cons (substring buf 0 nchars) substrings)
248 ((eof-object? terminator)
249 (if (zero? new-total)
250 (if (eq? handle-delim 'split)
251 (cons terminator terminator)
253 (if (eq? handle-delim 'split)
254 (cons (join-substrings) terminator)
258 ((trim peek concat) (join-substrings))
259 ((split) (cons (join-substrings) terminator))
262 (else (error "unexpected handle-delim value: "
263 handle-delim)))))))))
265 ;;; read-line [PORT [HANDLE-DELIM]] reads a newline-terminated string
266 ;;; from PORT. The return value depends on the value of HANDLE-DELIM,
267 ;;; which may be one of the symbols `trim', `concat', `peek' and
268 ;;; `split'. If it is `trim' (the default), the trailing newline is
269 ;;; removed and the string is returned. If `concat', the string is
270 ;;; returned with the trailing newline intact. If `peek', the newline
271 ;;; is left in the input port buffer and the string is returned. If
272 ;;; `split', the newline is split from the string and read-line
273 ;;; returns a pair consisting of the truncated string and the newline.
275 (define (read-line . args)
276 (let* ((port (if (null? args)
279 (handle-delim (if (> (length args) 1)
282 (line/delim (%read-line port))
283 (line (car line/delim))
284 (delim (cdr line/delim)))
288 ((concat) (if (and (string? line) (char? delim))
289 (string-append line (string delim))
291 ((peek) (if (char? delim)
292 (unread-char delim port))
295 (error "unexpected handle-delim value: " handle-delim)))))
302 (define uniform-vector? array?)
303 (define make-uniform-vector dimensions->uniform-array)
304 ; (define uniform-vector-ref array-ref)
305 (define (uniform-vector-set! u i o)
306 (uniform-array-set1! u o i))
307 (define uniform-vector-fill! array-fill!)
308 (define uniform-vector-read! uniform-array-read!)
309 (define uniform-vector-write uniform-array-write)
311 (define (make-array fill . args)
312 (dimensions->uniform-array args () fill))
313 (define (make-uniform-array prot . args)
314 (dimensions->uniform-array args prot))
315 (define (list->array ndim lst)
316 (list->uniform-array ndim '() lst))
317 (define (list->uniform-vector prot lst)
318 (list->uniform-array 1 prot lst))
319 (define (array-shape a)
320 (map (lambda (ind) (if (number? ind) (list 0 (+ -1 ind)) ind))
321 (array-dimensions a))))
327 (define (symbol->keyword symbol)
328 (make-keyword-from-dash-symbol (symbol-append '- symbol)))
330 (define (keyword->symbol kw)
331 (let ((sym (keyword-dash-symbol kw)))
332 (string->symbol (substring sym 1 (string-length sym)))))
334 (define (kw-arg-ref args kw)
335 (let ((rem (member kw args)))
336 (and rem (pair? (cdr rem)) (cadr rem))))
342 (define (struct-layout s)
343 (struct-ref (struct-vtable s) vtable-index-layout))
349 ;; Printing records: by default, records are printed as
351 ;; #<type-name field1: val1 field2: val2 ...>
353 ;; You can change that by giving a custom printing function to
354 ;; MAKE-RECORD-TYPE (after the list of field symbols). This function
355 ;; will be called like
357 ;; (<printer> object port)
359 ;; It should print OBJECT to PORT.
361 (define (inherit-print-state old-port new-port)
363 (cons (if (pair? new-port) (car new-port) new-port)
367 ;; 0: type-name, 1: fields
368 (define record-type-vtable
369 (make-vtable-vtable "prpr" 0
371 (cond ((eq? s record-type-vtable)
372 (display "#<record-type-vtable>" p))
374 (display "#<record-type " p)
375 (display (record-type-name s) p)
378 (define (record-type? obj)
379 (and (struct? obj) (eq? record-type-vtable (struct-vtable obj))))
381 (define (make-record-type type-name fields . opt)
382 (let ((printer-fn (and (pair? opt) (car opt))))
383 (let ((struct (make-struct record-type-vtable 0
386 (map (lambda (f) "pw") fields)))
390 (display type-name p)
391 (let loop ((fields fields)
394 ((not (null? fields))
396 (display (car fields) p)
398 (display (struct-ref s off) p)
399 (loop (cdr fields) (+ 1 off)))))
402 (copy-tree fields))))
403 ;; Temporary solution: Associate a name to the record type descriptor
404 ;; so that the object system can create a wrapper class for it.
405 (set-struct-vtable-name! struct (if (symbol? type-name)
407 (string->symbol type-name)))
410 (define (record-type-name obj)
411 (if (record-type? obj)
412 (struct-ref obj vtable-offset-user)
413 (error 'not-a-record-type obj)))
415 (define (record-type-fields obj)
416 (if (record-type? obj)
417 (struct-ref obj (+ 1 vtable-offset-user))
418 (error 'not-a-record-type obj)))
420 (define (record-constructor rtd . opt)
421 (let ((field-names (if (pair? opt) (car opt) (record-type-fields rtd))))
422 (eval `(lambda ,field-names
423 (make-struct ',rtd 0 ,@(map (lambda (f)
424 (if (memq f field-names)
427 (record-type-fields rtd)))))))
429 (define (record-predicate rtd)
430 (lambda (obj) (and (struct? obj) (eq? rtd (struct-vtable obj)))))
432 (define (record-accessor rtd field-name)
433 (let* ((pos (list-index (record-type-fields rtd) field-name)))
435 (error 'no-such-field field-name))
437 (and (eq? ',rtd (record-type-descriptor obj))
438 (struct-ref obj ,pos))))))
440 (define (record-modifier rtd field-name)
441 (let* ((pos (list-index (record-type-fields rtd) field-name)))
443 (error 'no-such-field field-name))
444 (eval `(lambda (obj val)
445 (and (eq? ',rtd (record-type-descriptor obj))
446 (struct-set! obj ,pos val))))))
449 (define (record? obj)
450 (and (struct? obj) (record-type? (struct-vtable obj))))
452 (define (record-type-descriptor obj)
455 (error 'not-a-record obj)))
463 (define (->bool x) (not (not x)))
469 (define (symbol-append . args)
470 (string->symbol (apply string-append args)))
472 (define (list->symbol . args)
473 (string->symbol (apply list->string args)))
475 (define (symbol . args)
476 (string->symbol (apply string args)))
478 (define (obarray-symbol-append ob . args)
479 (string->obarray-symbol (apply string-append ob args)))
481 (define (obarray-gensym obarray . opt)
483 (gensym "%%gensym" obarray)
484 (gensym (car opt) obarray)))
490 (define (list-index l k)
496 (loop (+ n 1) (cdr l))))))
498 (define (make-list n . init)
499 (if (pair? init) (set! init (car init)))
500 (let loop ((answer '())
504 (loop (cons init answer) (- n 1)))))
508 ;;; {Multiple return values}
511 (make-record-type "values"
515 (let ((make-values (record-constructor *values-rtd*)))
517 (if (and (not (null? x))
522 (define call-with-values
523 (let ((access-values (record-accessor *values-rtd* 'values))
524 (values-predicate? (record-predicate *values-rtd*)))
525 (lambda (producer consumer)
526 (let ((result (producer)))
527 (if (values-predicate? result)
528 (apply consumer (access-values result))
529 (consumer result))))))
534 ;;; {and-map and or-map}
536 ;;; (and-map fn lst) is like (and (fn (car lst)) (fn (cadr lst)) (fn...) ...)
537 ;;; (or-map fn lst) is like (or (fn (car lst)) (fn (cadr lst)) (fn...) ...)
538 ;;; (map-in-order fn lst) is like (map fn lst) but definately in order of lst.
543 ;; Apply f to successive elements of l until exhaustion or f returns #f.
544 ;; If returning early, return #f. Otherwise, return the last value returned
545 ;; by f. If f has never been called because l is empty, return #t.
547 (define (and-map f lst)
548 (let loop ((result #t)
553 (loop (f (car l)) (cdr l))))))
557 ;; Apply f to successive elements of l until exhaustion or while f returns #f.
558 ;; If returning early, return the return value of f.
560 (define (or-map f lst)
561 (let loop ((result #f)
565 (loop (f (car l)) (cdr l))))))
570 ;;; Warning: Hooks are now first class objects and add-hook! and remove-hook!
571 ;;; procedures. This interface is only provided for backward compatibility
572 ;;; and will be removed.
574 (if (not (defined? 'new-add-hook!))
576 (define new-add-hook! add-hook!)
577 (define new-remove-hook! remove-hook!)))
579 (define (run-hooks hook)
580 (if (and (pair? hook) (eq? (car hook) 'hook))
582 (for-each (lambda (thunk) (thunk)) hook)))
584 (define *suppress-old-style-hook-warning* #f)
587 (procedure->memoizing-macro
589 (let ((hook (local-eval (cadr exp) env)))
590 (if (and (pair? hook) (eq? (car hook) 'hook))
591 `(new-add-hook! ,@(cdr exp))
593 (or *suppress-old-style-hook-warning*
594 (display "Warning: Old style hooks\n" (current-error-port)))
595 `(let ((thunk ,(caddr exp)))
596 (if (not (memq thunk ,(cadr exp)))
598 (cons thunk ,(cadr exp)))))))))))
601 (procedure->memoizing-macro
603 (let ((hook (local-eval (cadr exp) env)))
604 (if (and (pair? hook) (eq? (car hook) 'hook))
605 `(new-remove-hook! ,@(cdr exp))
607 (or *suppress-old-style-hook-warning*
608 (display "Warning: Old style hooks\n" (current-error-port)))
609 `(let ((thunk ,(caddr exp)))
611 (delq! thunk ,(cadr exp))))))))))
616 ;;; If no one can explain this comment to me by 31 Jan 1998, I will
617 ;;; assume it is meaningless and remove it. -twp
618 ;;; !!!! these should be implemented using Tcl commands, not fports.
620 (define (feature? feature)
621 (and (memq feature *features*) #t))
623 ;; Using the vector returned by stat directly is probably not a good
624 ;; idea (it could just as well be a record). Hence some accessors.
625 (define (stat:dev f) (vector-ref f 0))
626 (define (stat:ino f) (vector-ref f 1))
627 (define (stat:mode f) (vector-ref f 2))
628 (define (stat:nlink f) (vector-ref f 3))
629 (define (stat:uid f) (vector-ref f 4))
630 (define (stat:gid f) (vector-ref f 5))
631 (define (stat:rdev f) (vector-ref f 6))
632 (define (stat:size f) (vector-ref f 7))
633 (define (stat:atime f) (vector-ref f 8))
634 (define (stat:mtime f) (vector-ref f 9))
635 (define (stat:ctime f) (vector-ref f 10))
636 (define (stat:blksize f) (vector-ref f 11))
637 (define (stat:blocks f) (vector-ref f 12))
639 ;; derived from stat mode.
640 (define (stat:type f) (vector-ref f 13))
641 (define (stat:perms f) (vector-ref f 14))
644 (if (feature? 'posix)
648 (let ((port (catch 'system-error (lambda () (open-file str OPEN_READ))
650 (if port (begin (close-port port) #t)
653 (define file-is-directory?
654 (if (feature? 'i/o-extensions)
656 (eq? (stat:type (stat str)) 'directory))
660 (let ((port (catch 'system-error
661 (lambda () (open-file (string-append str "/.")
664 (if port (begin (close-port port) #t)
667 (define (has-suffix? str suffix)
668 (let ((sufl (string-length suffix))
669 (sl (string-length str)))
671 (string=? (substring str (- sl sufl) sl) suffix))))
677 (define (error . args)
680 (scm-error 'misc-error #f "?" #f #f)
681 (let loop ((msg "%s")
683 (if (not (null? rest))
684 (loop (string-append msg " %S")
686 (scm-error 'misc-error #f msg args #f)))))
688 ;; bad-throw is the hook that is called upon a throw to a an unhandled
689 ;; key (unless the throw has four arguments, in which case
690 ;; it's usually interpreted as an error throw.)
691 ;; If the key has a default handler (a throw-handler-default property),
692 ;; it is applied to the throw.
694 (define (bad-throw key . args)
695 (let ((default (symbol-property key 'throw-handler-default)))
696 (or (and default (apply default key args))
697 (apply error "unhandled-exception:" key args))))
700 ;;; {Non-polymorphic versions of POSIX functions}
702 (define (getgrnam name) (getgr name))
703 (define (getgrgid id) (getgr id))
704 (define (gethostbyaddr addr) (gethost addr))
705 (define (gethostbyname name) (gethost name))
706 (define (getnetbyaddr addr) (getnet addr))
707 (define (getnetbyname name) (getnet name))
708 (define (getprotobyname name) (getproto name))
709 (define (getprotobynumber addr) (getproto addr))
710 (define (getpwnam name) (getpw name))
711 (define (getpwuid uid) (getpw uid))
712 (define (getservbyname name proto) (getserv name proto))
713 (define (getservbyport port proto) (getserv port proto))
714 (define (endgrent) (setgr))
715 (define (endhostent) (sethost))
716 (define (endnetent) (setnet))
717 (define (endprotoent) (setproto))
718 (define (endpwent) (setpw))
719 (define (endservent) (setserv))
720 (define (getgrent) (getgr))
721 (define (gethostent) (gethost))
722 (define (getnetent) (getnet))
723 (define (getprotoent) (getproto))
724 (define (getpwent) (getpw))
725 (define (getservent) (getserv))
726 (define (setgrent) (setgr #f))
727 (define (sethostent) (sethost #t))
728 (define (setnetent) (setnet #t))
729 (define (setprotoent) (setproto #t))
730 (define (setpwent) (setpw #t))
731 (define (setservent) (setserv #t))
733 (define (passwd:name obj) (vector-ref obj 0))
734 (define (passwd:passwd obj) (vector-ref obj 1))
735 (define (passwd:uid obj) (vector-ref obj 2))
736 (define (passwd:gid obj) (vector-ref obj 3))
737 (define (passwd:gecos obj) (vector-ref obj 4))
738 (define (passwd:dir obj) (vector-ref obj 5))
739 (define (passwd:shell obj) (vector-ref obj 6))
741 (define (group:name obj) (vector-ref obj 0))
742 (define (group:passwd obj) (vector-ref obj 1))
743 (define (group:gid obj) (vector-ref obj 2))
744 (define (group:mem obj) (vector-ref obj 3))
746 (define (hostent:name obj) (vector-ref obj 0))
747 (define (hostent:aliases obj) (vector-ref obj 1))
748 (define (hostent:addrtype obj) (vector-ref obj 2))
749 (define (hostent:length obj) (vector-ref obj 3))
750 (define (hostent:addr-list obj) (vector-ref obj 4))
752 (define (netent:name obj) (vector-ref obj 0))
753 (define (netent:aliases obj) (vector-ref obj 1))
754 (define (netent:addrtype obj) (vector-ref obj 2))
755 (define (netent:net obj) (vector-ref obj 3))
757 (define (protoent:name obj) (vector-ref obj 0))
758 (define (protoent:aliases obj) (vector-ref obj 1))
759 (define (protoent:proto obj) (vector-ref obj 2))
761 (define (servent:name obj) (vector-ref obj 0))
762 (define (servent:aliases obj) (vector-ref obj 1))
763 (define (servent:port obj) (vector-ref obj 2))
764 (define (servent:proto obj) (vector-ref obj 3))
766 (define (sockaddr:fam obj) (vector-ref obj 0))
767 (define (sockaddr:path obj) (vector-ref obj 1))
768 (define (sockaddr:addr obj) (vector-ref obj 1))
769 (define (sockaddr:port obj) (vector-ref obj 2))
771 (define (utsname:sysname obj) (vector-ref obj 0))
772 (define (utsname:nodename obj) (vector-ref obj 1))
773 (define (utsname:release obj) (vector-ref obj 2))
774 (define (utsname:version obj) (vector-ref obj 3))
775 (define (utsname:machine obj) (vector-ref obj 4))
777 (define (tm:sec obj) (vector-ref obj 0))
778 (define (tm:min obj) (vector-ref obj 1))
779 (define (tm:hour obj) (vector-ref obj 2))
780 (define (tm:mday obj) (vector-ref obj 3))
781 (define (tm:mon obj) (vector-ref obj 4))
782 (define (tm:year obj) (vector-ref obj 5))
783 (define (tm:wday obj) (vector-ref obj 6))
784 (define (tm:yday obj) (vector-ref obj 7))
785 (define (tm:isdst obj) (vector-ref obj 8))
786 (define (tm:gmtoff obj) (vector-ref obj 9))
787 (define (tm:zone obj) (vector-ref obj 10))
789 (define (set-tm:sec obj val) (vector-set! obj 0 val))
790 (define (set-tm:min obj val) (vector-set! obj 1 val))
791 (define (set-tm:hour obj val) (vector-set! obj 2 val))
792 (define (set-tm:mday obj val) (vector-set! obj 3 val))
793 (define (set-tm:mon obj val) (vector-set! obj 4 val))
794 (define (set-tm:year obj val) (vector-set! obj 5 val))
795 (define (set-tm:wday obj val) (vector-set! obj 6 val))
796 (define (set-tm:yday obj val) (vector-set! obj 7 val))
797 (define (set-tm:isdst obj val) (vector-set! obj 8 val))
798 (define (set-tm:gmtoff obj val) (vector-set! obj 9 val))
799 (define (set-tm:zone obj val) (vector-set! obj 10 val))
801 (define (tms:clock obj) (vector-ref obj 0))
802 (define (tms:utime obj) (vector-ref obj 1))
803 (define (tms:stime obj) (vector-ref obj 2))
804 (define (tms:cutime obj) (vector-ref obj 3))
805 (define (tms:cstime obj) (vector-ref obj 4))
807 (define (file-position . args) (apply ftell args))
808 (define (file-set-position . args) (apply fseek args))
810 (define (move->fdes fd/port fd)
811 (cond ((integer? fd/port)
812 (dup->fdes fd/port fd)
816 (primitive-move->fdes fd/port fd)
817 (set-port-revealed! fd/port 1)
820 (define (release-port-handle port)
821 (let ((revealed (port-revealed port)))
823 (set-port-revealed! port (- revealed 1)))))
825 (define (dup->port port/fd mode . maybe-fd)
826 (let ((port (fdopen (apply dup->fdes port/fd maybe-fd)
829 (set-port-revealed! port 1))
832 (define (dup->inport port/fd . maybe-fd)
833 (apply dup->port port/fd "r" maybe-fd))
835 (define (dup->outport port/fd . maybe-fd)
836 (apply dup->port port/fd "w" maybe-fd))
838 (define (dup port/fd . maybe-fd)
839 (if (integer? port/fd)
840 (apply dup->fdes port/fd maybe-fd)
841 (apply dup->port port/fd (port-mode port/fd) maybe-fd)))
843 (define (duplicate-port port modes)
844 (dup->port port modes))
846 (define (fdes->inport fdes)
847 (let loop ((rest-ports (fdes->ports fdes)))
848 (cond ((null? rest-ports)
849 (let ((result (fdopen fdes "r")))
850 (set-port-revealed! result 1)
852 ((input-port? (car rest-ports))
853 (set-port-revealed! (car rest-ports)
854 (+ (port-revealed (car rest-ports)) 1))
857 (loop (cdr rest-ports))))))
859 (define (fdes->outport fdes)
860 (let loop ((rest-ports (fdes->ports fdes)))
861 (cond ((null? rest-ports)
862 (let ((result (fdopen fdes "w")))
863 (set-port-revealed! result 1)
865 ((output-port? (car rest-ports))
866 (set-port-revealed! (car rest-ports)
867 (+ (port-revealed (car rest-ports)) 1))
870 (loop (cdr rest-ports))))))
872 (define (port->fdes port)
873 (set-port-revealed! port (+ (port-revealed port) 1))
876 (define (setenv name value)
878 (putenv (string-append name "=" value))
885 ;;; Here for backward compatability
887 (define scheme-file-suffix (lambda () ".scm"))
889 (define (in-vicinity vicinity file)
890 (let ((tail (let ((len (string-length vicinity)))
893 (string-ref vicinity (- len 1))))))
894 (string-append vicinity
902 ;;; {Help for scm_shell}
903 ;;; The argument-processing code used by Guile-based shells generates
904 ;;; Scheme code based on the argument list. This page contains help
905 ;;; functions for the code it generates.
907 (define (command-line) (program-arguments))
909 ;; This is mostly for the internal use of the code generated by
910 ;; scm_compile_shell_switches.
911 (define (load-user-init)
912 (define (has-init? dir)
913 (let ((path (in-vicinity dir ".guile")))
916 (let ((stats (stat path)))
917 (if (not (eq? (stat:type stats) 'directory))
920 (let ((path (or (has-init? (or (getenv "HOME") "/"))
921 (has-init? (passwd:dir (getpw (getuid)))))))
922 (if path (primitive-load path))))
925 ;;; {Loading by paths}
927 ;;; Load a Scheme source file named NAME, searching for it in the
928 ;;; directories listed in %load-path, and applying each of the file
929 ;;; name extensions listed in %load-extensions.
930 (define (load-from-path name)
931 (start-stack 'load-stack
932 (primitive-load-path name)))
936 ;;; {Transcendental Functions}
938 ;;; Derived from "Transcen.scm", Complex trancendental functions for SCM.
939 ;;; Written by Jerry D. Hedden, (C) FSF.
940 ;;; See the file `COPYING' for terms applying to this program.
944 (if (real? z) ($exp z)
945 (make-polar ($exp (real-part z)) (imag-part z))))
948 (if (and (real? z) (>= z 0))
950 (make-rectangular ($log (magnitude z)) (angle z))))
954 (if (negative? z) (make-rectangular 0 ($sqrt (- z)))
956 (make-polar ($sqrt (magnitude z)) (/ (angle z) 2))))
959 (let ((integer-expt integer-expt))
962 (integer-expt z1 z2))
963 ((and (real? z2) (real? z1) (>= z1 0))
966 (exp (* z2 (log z1))))))))
969 (if (real? z) ($sinh z)
970 (let ((x (real-part z)) (y (imag-part z)))
971 (make-rectangular (* ($sinh x) ($cos y))
972 (* ($cosh x) ($sin y))))))
974 (if (real? z) ($cosh z)
975 (let ((x (real-part z)) (y (imag-part z)))
976 (make-rectangular (* ($cosh x) ($cos y))
977 (* ($sinh x) ($sin y))))))
979 (if (real? z) ($tanh z)
980 (let* ((x (* 2 (real-part z)))
981 (y (* 2 (imag-part z)))
982 (w (+ ($cosh x) ($cos y))))
983 (make-rectangular (/ ($sinh x) w) (/ ($sin y) w)))))
986 (if (real? z) ($asinh z)
987 (log (+ z (sqrt (+ (* z z) 1))))))
990 (if (and (real? z) (>= z 1))
992 (log (+ z (sqrt (- (* z z) 1))))))
995 (if (and (real? z) (> z -1) (< z 1))
997 (/ (log (/ (+ 1 z) (- 1 z))) 2)))
1000 (if (real? z) ($sin z)
1001 (let ((x (real-part z)) (y (imag-part z)))
1002 (make-rectangular (* ($sin x) ($cosh y))
1003 (* ($cos x) ($sinh y))))))
1005 (if (real? z) ($cos z)
1006 (let ((x (real-part z)) (y (imag-part z)))
1007 (make-rectangular (* ($cos x) ($cosh y))
1008 (- (* ($sin x) ($sinh y)))))))
1010 (if (real? z) ($tan z)
1011 (let* ((x (* 2 (real-part z)))
1012 (y (* 2 (imag-part z)))
1013 (w (+ ($cos x) ($cosh y))))
1014 (make-rectangular (/ ($sin x) w) (/ ($sinh y) w)))))
1017 (if (and (real? z) (>= z -1) (<= z 1))
1019 (* -i (asinh (* +i z)))))
1022 (if (and (real? z) (>= z -1) (<= z 1))
1024 (+ (/ (angle -1) 2) (* +i (asinh (* +i z))))))
1026 (define (atan z . y)
1028 (if (real? z) ($atan z)
1029 (/ (log (/ (- +i z) (+ +i z))) +2i))
1030 ($atan2 z (car y))))
1032 (set! abs magnitude)
1035 (/ (log arg) (log 10)))
1039 ;;; {Reader Extensions}
1042 ;;; Reader code for various "#c" forms.
1045 ;;; Parse the portion of a #/ list that comes after the first slash.
1046 (define (read-path-list-notation slash port)
1049 ;; Is C a delimiter?
1050 ((delimiter? (lambda (c) (or (eof-object? c)
1051 (char-whitespace? c)
1052 (string-index "()\";" c))))
1054 ;; Read and return one component of a path list.
1057 (let loop ((reversed-chars '()))
1058 (let ((c (peek-char port)))
1059 (if (or (delimiter? c)
1061 (string->symbol (list->string (reverse reversed-chars)))
1062 (loop (cons (read-char port) reversed-chars))))))))
1064 ;; Read and return a path list.
1065 (let loop ((reversed-path (list (read-component))))
1066 (let ((c (peek-char port)))
1067 (if (and (char? c) (char=? c #\/))
1070 (loop (cons (read-component) reversed-path)))
1071 (reverse reversed-path))))))
1073 (define (read-path-list-notation-warning slash port)
1074 (if (not (getenv "GUILE_HUSH"))
1076 (display "warning: obsolete `#/' list notation read from "
1077 (current-error-port))
1078 (display (port-filename port) (current-error-port))
1079 (display "; see guile-core/NEWS." (current-error-port))
1080 (newline (current-error-port))
1081 (display " Set the GUILE_HUSH environment variable to disable this warning."
1082 (current-error-port))
1083 (newline (current-error-port))))
1084 (read-hash-extend #\/ read-path-list-notation)
1085 (read-path-list-notation slash port))
1088 (read-hash-extend #\' (lambda (c port)
1090 (read-hash-extend #\. (lambda (c port)
1091 (eval (read port))))
1093 (if (feature? 'array)
1095 (let ((make-array-proc (lambda (template)
1097 (read:uniform-vector template port)))))
1098 (for-each (lambda (char template)
1099 (read-hash-extend char
1100 (make-array-proc template)))
1101 '(#\b #\a #\u #\e #\s #\i #\c #\y #\h)
1102 '(#t #\a 1 -1 1.0 1/3 0+i #\nul s)))
1103 (let ((array-proc (lambda (c port)
1104 (read:array c port))))
1105 (for-each (lambda (char) (read-hash-extend char array-proc))
1106 '(#\0 #\1 #\2 #\3 #\4 #\5 #\6 #\7 #\8 #\9)))))
1108 ;; pushed to the beginning of the alist since it's used more than the
1109 ;; others at present.
1110 (read-hash-extend #\/ read-path-list-notation-warning)
1112 (define (read:array digit port)
1113 (define chr0 (char->integer #\0))
1114 (let ((rank (let readnum ((val (- (char->integer digit) chr0)))
1115 (if (char-numeric? (peek-char port))
1116 (readnum (+ (* 10 val)
1117 (- (char->integer (read-char port)) chr0)))
1119 (prot (if (eq? #\( (peek-char port))
1121 (let ((c (read-char port)))
1129 (else (error "read:array unknown option " c)))))))
1130 (if (eq? (peek-char port) #\()
1131 (list->uniform-array rank prot (read port))
1132 (error "read:array list not found"))))
1134 (define (read:uniform-vector proto port)
1135 (if (eq? #\( (peek-char port))
1136 (list->uniform-array 1 proto (read port))
1137 (error "read:uniform-vector list not found")))
1140 ;;; {Command Line Options}
1143 (define (get-option argv kw-opts kw-args return)
1146 (return #f #f argv))
1148 ((or (not (eq? #\- (string-ref (car argv) 0)))
1149 (eq? (string-length (car argv)) 1))
1150 (return 'normal-arg (car argv) (cdr argv)))
1152 ((eq? #\- (string-ref (car argv) 1))
1153 (let* ((kw-arg-pos (or (string-index (car argv) #\=)
1154 (string-length (car argv))))
1155 (kw (symbol->keyword (substring (car argv) 2 kw-arg-pos)))
1156 (kw-opt? (member kw kw-opts))
1157 (kw-arg? (member kw kw-args))
1158 (arg (or (and (not (eq? kw-arg-pos (string-length (car argv))))
1159 (substring (car argv)
1161 (string-length (car argv))))
1163 (begin (set! argv (cdr argv)) (car argv))))))
1164 (if (or kw-opt? kw-arg?)
1165 (return kw arg (cdr argv))
1166 (return 'usage-error kw (cdr argv)))))
1169 (let* ((char (substring (car argv) 1 2))
1170 (kw (symbol->keyword char)))
1173 ((member kw kw-opts)
1174 (let* ((rest-car (substring (car argv) 2 (string-length (car argv))))
1175 (new-argv (if (= 0 (string-length rest-car))
1177 (cons (string-append "-" rest-car) (cdr argv)))))
1178 (return kw #f new-argv)))
1180 ((member kw kw-args)
1181 (let* ((rest-car (substring (car argv) 2 (string-length (car argv))))
1182 (arg (if (= 0 (string-length rest-car))
1185 (new-argv (if (= 0 (string-length rest-car))
1188 (return kw arg new-argv)))
1190 (else (return 'usage-error kw argv)))))))
1192 (define (for-next-option proc argv kw-opts kw-args)
1193 (let loop ((argv argv))
1194 (get-option argv kw-opts kw-args
1195 (lambda (opt opt-arg argv)
1196 (and opt (proc opt opt-arg argv loop))))))
1198 (define (display-usage-report kw-desc)
1201 (or (eq? (car kw) #t)
1202 (eq? (car kw) 'else)
1203 (let* ((opt-desc kw)
1204 (help (cadr opt-desc))
1205 (opts (car opt-desc))
1206 (opts-proper (if (string? (car opts)) (cdr opts) opts))
1207 (arg-name (if (string? (car opts))
1208 (string-append "<" (car opts) ">")
1210 (left-part (string-append
1211 (with-output-to-string
1213 (map (lambda (x) (display (keyword-symbol x)) (display " "))
1216 (middle-part (if (and (< (string-length left-part) 30)
1217 (< (string-length help) 40))
1218 (make-string (- 30 (string-length left-part)) #\ )
1221 (display middle-part)
1228 (define (transform-usage-lambda cases)
1229 (let* ((raw-usage (delq! 'else (map car cases)))
1230 (usage-sans-specials (map (lambda (x)
1231 (or (and (not (list? x)) x)
1232 (and (symbol? (car x)) #t)
1233 (and (boolean? (car x)) #t)
1236 (usage-desc (delq! #t usage-sans-specials))
1237 (kw-desc (map car usage-desc))
1238 (kw-opts (apply append (map (lambda (x) (and (not (string? (car x))) x)) kw-desc)))
1239 (kw-args (apply append (map (lambda (x) (and (string? (car x)) (cdr x))) kw-desc)))
1240 (transmogrified-cases (map (lambda (case)
1241 (cons (let ((opts (car case)))
1242 (if (or (boolean? opts) (eq? 'else opts))
1245 ((symbol? (car opts)) opts)
1246 ((boolean? (car opts)) opts)
1247 ((string? (caar opts)) (cdar opts))
1248 (else (car opts)))))
1251 `(let ((%display-usage (lambda () (display-usage-report ',usage-desc))))
1253 (let %next-arg ((%argv %argv))
1257 (lambda (%opt %arg %new-argv)
1259 ,@ transmogrified-cases))))))))
1264 ;;; {Low Level Modules}
1266 ;;; These are the low level data structures for modules.
1268 ;;; !!! warning: The interface to lazy binder procedures is going
1269 ;;; to be changed in an incompatible way to permit all the basic
1270 ;;; module ops to be virtualized.
1272 ;;; (make-module size use-list lazy-binding-proc) => module
1273 ;;; module-{obarray,uses,binder}[|-set!]
1274 ;;; (module? obj) => [#t|#f]
1275 ;;; (module-locally-bound? module symbol) => [#t|#f]
1276 ;;; (module-bound? module symbol) => [#t|#f]
1277 ;;; (module-symbol-locally-interned? module symbol) => [#t|#f]
1278 ;;; (module-symbol-interned? module symbol) => [#t|#f]
1279 ;;; (module-local-variable module symbol) => [#<variable ...> | #f]
1280 ;;; (module-variable module symbol) => [#<variable ...> | #f]
1281 ;;; (module-symbol-binding module symbol opt-value)
1282 ;;; => [ <obj> | opt-value | an error occurs ]
1283 ;;; (module-make-local-var! module symbol) => #<variable...>
1284 ;;; (module-add! module symbol var) => unspecified
1285 ;;; (module-remove! module symbol) => unspecified
1286 ;;; (module-for-each proc module) => unspecified
1287 ;;; (make-scm-module) => module ; a lazy copy of the symhash module
1288 ;;; (set-current-module module) => unspecified
1289 ;;; (current-module) => #<module...>
1294 ;;; {Printing Modules}
1295 ;; This is how modules are printed. You can re-define it.
1296 ;; (Redefining is actually more complicated than simply redefining
1297 ;; %print-module because that would only change the binding and not
1298 ;; the value stored in the vtable that determines how record are
1301 (define (%print-module mod port) ; unused args: depth length style table)
1303 (display (or (module-kind mod) "module") port)
1304 (let ((name (module-name mod)))
1308 (display name port))))
1310 (display (number->string (object-address mod) 16) port)
1315 ;; A module is characterized by an obarray in which local symbols
1316 ;; are interned, a list of modules, "uses", from which non-local
1317 ;; bindings can be inherited, and an optional lazy-binder which
1318 ;; is a (CLOSURE module symbol) which, as a last resort, can provide
1319 ;; bindings that would otherwise not be found locally in the module.
1322 (make-record-type 'module
1323 '(obarray uses binder eval-closure transformer name kind)
1326 ;; make-module &opt size uses binder
1328 ;; Create a new module, perhaps with a particular size of obarray,
1329 ;; initial uses list, or binding procedure.
1334 (define (parse-arg index default)
1335 (if (> (length args) index)
1336 (list-ref args index)
1339 (if (> (length args) 3)
1340 (error "Too many args to make-module." args))
1342 (let ((size (parse-arg 0 1021))
1343 (uses (parse-arg 1 '()))
1344 (binder (parse-arg 2 #f)))
1346 (if (not (integer? size))
1347 (error "Illegal size to make-module." size))
1348 (if (not (and (list? uses)
1349 (and-map module? uses)))
1350 (error "Incorrect use list." uses))
1351 (if (and binder (not (procedure? binder)))
1353 "Lazy-binder expected to be a procedure or #f." binder))
1355 (let ((module (module-constructor (make-vector size '())
1356 uses binder #f #f #f #f)))
1358 ;; We can't pass this as an argument to module-constructor,
1359 ;; because we need it to close over a pointer to the module
1361 (set-module-eval-closure! module
1362 (lambda (symbol define?)
1364 (module-make-local-var! module symbol)
1365 (module-variable module symbol))))
1369 (define module-constructor (record-constructor module-type))
1370 (define module-obarray (record-accessor module-type 'obarray))
1371 (define set-module-obarray! (record-modifier module-type 'obarray))
1372 (define module-uses (record-accessor module-type 'uses))
1373 (define set-module-uses! (record-modifier module-type 'uses))
1374 (define module-binder (record-accessor module-type 'binder))
1375 (define set-module-binder! (record-modifier module-type 'binder))
1377 ;; NOTE: This binding is used in libguile/modules.c.
1378 (define module-eval-closure (record-accessor module-type 'eval-closure))
1380 (define module-transformer (record-accessor module-type 'transformer))
1381 (define set-module-transformer! (record-modifier module-type 'transformer))
1382 (define module-name (record-accessor module-type 'name))
1383 (define set-module-name! (record-modifier module-type 'name))
1384 (define module-kind (record-accessor module-type 'kind))
1385 (define set-module-kind! (record-modifier module-type 'kind))
1386 (define module? (record-predicate module-type))
1388 (define set-module-eval-closure!
1389 (let ((setter (record-modifier module-type 'eval-closure)))
1390 (lambda (module closure)
1391 (setter module closure)
1392 ;; Make it possible to lookup the module from the environment.
1393 ;; This implementation is correct since an eval closure can belong
1394 ;; to maximally one module.
1395 (set-procedure-property! closure 'module module))))
1397 (define (eval-in-module exp module)
1398 (eval2 exp (module-eval-closure module)))
1401 ;;; {Module Searching in General}
1403 ;;; We sometimes want to look for properties of a symbol
1404 ;;; just within the obarray of one module. If the property
1405 ;;; holds, then it is said to hold ``locally'' as in, ``The symbol
1406 ;;; DISPLAY is locally rebound in the module `safe-guile'.''
1409 ;;; Other times, we want to test for a symbol property in the obarray
1410 ;;; of M and, if it is not found there, try each of the modules in the
1411 ;;; uses list of M. This is the normal way of testing for some
1412 ;;; property, so we state these properties without qualification as
1413 ;;; in: ``The symbol 'fnord is interned in module M because it is
1414 ;;; interned locally in module M2 which is a member of the uses list
1418 ;; module-search fn m
1420 ;; return the first non-#f result of FN applied to M and then to
1421 ;; the modules in the uses of m, and so on recursively. If all applications
1422 ;; return #f, then so does this function.
1424 (define (module-search fn m v)
1427 (or (module-search fn (car pos) v)
1430 (loop (module-uses m))))
1433 ;;; {Is a symbol bound in a module?}
1435 ;;; Symbol S in Module M is bound if S is interned in M and if the binding
1436 ;;; of S in M has been set to some well-defined value.
1439 ;; module-locally-bound? module symbol
1441 ;; Is a symbol bound (interned and defined) locally in a given module?
1443 (define (module-locally-bound? m v)
1444 (let ((var (module-local-variable m v)))
1446 (variable-bound? var))))
1448 ;; module-bound? module symbol
1450 ;; Is a symbol bound (interned and defined) anywhere in a given module
1453 (define (module-bound? m v)
1454 (module-search module-locally-bound? m v))
1456 ;;; {Is a symbol interned in a module?}
1458 ;;; Symbol S in Module M is interned if S occurs in
1459 ;;; of S in M has been set to some well-defined value.
1461 ;;; It is possible to intern a symbol in a module without providing
1462 ;;; an initial binding for the corresponding variable. This is done
1464 ;;; (module-add! module symbol (make-undefined-variable))
1466 ;;; In that case, the symbol is interned in the module, but not
1467 ;;; bound there. The unbound symbol shadows any binding for that
1468 ;;; symbol that might otherwise be inherited from a member of the uses list.
1471 (define (module-obarray-get-handle ob key)
1472 ((if (symbol? key) hashq-get-handle hash-get-handle) ob key))
1474 (define (module-obarray-ref ob key)
1475 ((if (symbol? key) hashq-ref hash-ref) ob key))
1477 (define (module-obarray-set! ob key val)
1478 ((if (symbol? key) hashq-set! hash-set!) ob key val))
1480 (define (module-obarray-remove! ob key)
1481 ((if (symbol? key) hashq-remove! hash-remove!) ob key))
1483 ;; module-symbol-locally-interned? module symbol
1485 ;; is a symbol interned (not neccessarily defined) locally in a given module
1486 ;; or its uses? Interned symbols shadow inherited bindings even if
1487 ;; they are not themselves bound to a defined value.
1489 (define (module-symbol-locally-interned? m v)
1490 (not (not (module-obarray-get-handle (module-obarray m) v))))
1492 ;; module-symbol-interned? module symbol
1494 ;; is a symbol interned (not neccessarily defined) anywhere in a given module
1495 ;; or its uses? Interned symbols shadow inherited bindings even if
1496 ;; they are not themselves bound to a defined value.
1498 (define (module-symbol-interned? m v)
1499 (module-search module-symbol-locally-interned? m v))
1502 ;;; {Mapping modules x symbols --> variables}
1505 ;; module-local-variable module symbol
1506 ;; return the local variable associated with a MODULE and SYMBOL.
1508 ;;; This function is very important. It is the only function that can
1509 ;;; return a variable from a module other than the mutators that store
1510 ;;; new variables in modules. Therefore, this function is the location
1511 ;;; of the "lazy binder" hack.
1513 ;;; If symbol is defined in MODULE, and if the definition binds symbol
1514 ;;; to a variable, return that variable object.
1516 ;;; If the symbols is not found at first, but the module has a lazy binder,
1517 ;;; then try the binder.
1519 ;;; If the symbol is not found at all, return #f.
1521 (define (module-local-variable m v)
1524 (let ((b (module-obarray-ref (module-obarray m) v)))
1525 (or (and (variable? b) b)
1526 (and (module-binder m)
1527 ((module-binder m) m v #f)))))
1530 ;; module-variable module symbol
1532 ;; like module-local-variable, except search the uses in the
1533 ;; case V is not found in M.
1535 (define (module-variable m v)
1536 (module-search module-local-variable m v))
1539 ;;; {Mapping modules x symbols --> bindings}
1541 ;;; These are similar to the mapping to variables, except that the
1542 ;;; variable is dereferenced.
1545 ;; module-symbol-binding module symbol opt-value
1547 ;; return the binding of a variable specified by name within
1548 ;; a given module, signalling an error if the variable is unbound.
1549 ;; If the OPT-VALUE is passed, then instead of signalling an error,
1550 ;; return OPT-VALUE.
1552 (define (module-symbol-local-binding m v . opt-val)
1553 (let ((var (module-local-variable m v)))
1556 (if (not (null? opt-val))
1558 (error "Locally unbound variable." v)))))
1560 ;; module-symbol-binding module symbol opt-value
1562 ;; return the binding of a variable specified by name within
1563 ;; a given module, signalling an error if the variable is unbound.
1564 ;; If the OPT-VALUE is passed, then instead of signalling an error,
1565 ;; return OPT-VALUE.
1567 (define (module-symbol-binding m v . opt-val)
1568 (let ((var (module-variable m v)))
1571 (if (not (null? opt-val))
1573 (error "Unbound variable." v)))))
1577 ;;; {Adding Variables to Modules}
1582 ;; module-make-local-var! module symbol
1584 ;; ensure a variable for V in the local namespace of M.
1585 ;; If no variable was already there, then create a new and uninitialzied
1588 (define (module-make-local-var! m v)
1589 (or (let ((b (module-obarray-ref (module-obarray m) v)))
1590 (and (variable? b) b))
1591 (and (module-binder m)
1592 ((module-binder m) m v #t))
1594 (let ((answer (make-undefined-variable v)))
1595 (module-obarray-set! (module-obarray m) v answer)
1598 ;; module-add! module symbol var
1600 ;; ensure a particular variable for V in the local namespace of M.
1602 (define (module-add! m v var)
1603 (if (not (variable? var))
1604 (error "Bad variable to module-add!" var))
1605 (module-obarray-set! (module-obarray m) v var))
1609 ;; make sure that a symbol is undefined in the local namespace of M.
1611 (define (module-remove! m v)
1612 (module-obarray-remove! (module-obarray m) v))
1614 (define (module-clear! m)
1615 (vector-fill! (module-obarray m) '()))
1617 ;; MODULE-FOR-EACH -- exported
1619 ;; Call PROC on each symbol in MODULE, with arguments of (SYMBOL VARIABLE).
1621 (define (module-for-each proc module)
1622 (let ((obarray (module-obarray module)))
1623 (do ((index 0 (+ index 1))
1624 (end (vector-length obarray)))
1628 (proc (car bucket) (cdr bucket)))
1629 (vector-ref obarray index)))))
1632 (define (module-map proc module)
1633 (let* ((obarray (module-obarray module))
1634 (end (vector-length obarray)))
1642 (map (lambda (bucket)
1643 (proc (car bucket) (cdr bucket)))
1644 (vector-ref obarray i))
1648 ;;; {Low Level Bootstrapping}
1653 ;; A root module uses the symhash table (the system's privileged
1654 ;; obarray). Being inside a root module is like using SCM without
1655 ;; any module system.
1659 (define (root-module-closure m s define?)
1660 (let ((bi (and (symbol-interned? #f s)
1661 (builtin-variable s))))
1663 (or define? (variable-bound? bi))
1665 (module-add! m s bi)
1668 (define (make-root-module)
1669 (make-module 1019 '() root-module-closure))
1674 ;; An scm module is a module into which the lazy binder copies
1675 ;; variable bindings from the system symhash table. The mapping is
1676 ;; one way only; newly introduced bindings in an scm module are not
1677 ;; copied back into the system symhash table (and can be used to override
1678 ;; bindings from the symhash table).
1681 (define (make-scm-module)
1682 (make-module 1019 '()
1683 (lambda (m s define?)
1684 (let ((bi (and (symbol-interned? #f s)
1685 (builtin-variable s))))
1687 (variable-bound? bi)
1689 (module-add! m s bi)
1697 ;; NOTE: This binding is used in libguile/modules.c.
1699 (define the-module #f)
1701 ;; scm:eval-transformer
1703 (define scm:eval-transformer #f)
1705 ;; set-current-module module
1707 ;; set the current module as viewed by the normalizer.
1709 ;; NOTE: This binding is used in libguile/modules.c.
1711 (define (set-current-module m)
1715 (set! *top-level-lookup-closure* (module-eval-closure the-module))
1716 (set! scm:eval-transformer (module-transformer the-module)))
1717 (set! *top-level-lookup-closure* #f)))
1722 ;; return the current module as viewed by the normalizer.
1724 (define (current-module) the-module)
1726 ;;; {Module-based Loading}
1729 (define (save-module-excursion thunk)
1730 (let ((inner-module (current-module))
1732 (dynamic-wind (lambda ()
1733 (set! outer-module (current-module))
1734 (set-current-module inner-module)
1735 (set! inner-module #f))
1738 (set! inner-module (current-module))
1739 (set-current-module outer-module)
1740 (set! outer-module #f)))))
1742 (define basic-load load)
1744 (define (load-module filename)
1745 (save-module-excursion
1747 (let ((oldname (and (current-load-port)
1748 (port-filename (current-load-port)))))
1749 (basic-load (if (and oldname
1750 (> (string-length filename) 0)
1751 (not (char=? (string-ref filename 0) #\/))
1752 (not (string=? (dirname oldname) ".")))
1753 (string-append (dirname oldname) "/" filename)
1758 ;;; {MODULE-REF -- exported}
1760 ;; Returns the value of a variable called NAME in MODULE or any of its
1761 ;; used modules. If there is no such variable, then if the optional third
1762 ;; argument DEFAULT is present, it is returned; otherwise an error is signaled.
1764 (define (module-ref module name . rest)
1765 (let ((variable (module-variable module name)))
1766 (if (and variable (variable-bound? variable))
1767 (variable-ref variable)
1769 (error "No variable named" name 'in module)
1770 (car rest) ; default value
1773 ;; MODULE-SET! -- exported
1775 ;; Sets the variable called NAME in MODULE (or in a module that MODULE uses)
1776 ;; to VALUE; if there is no such variable, an error is signaled.
1778 (define (module-set! module name value)
1779 (let ((variable (module-variable module name)))
1781 (variable-set! variable value)
1782 (error "No variable named" name 'in module))))
1784 ;; MODULE-DEFINE! -- exported
1786 ;; Sets the variable called NAME in MODULE to VALUE; if there is no such
1787 ;; variable, it is added first.
1789 (define (module-define! module name value)
1790 (let ((variable (module-local-variable module name)))
1792 (variable-set! variable value)
1793 (module-add! module name (make-variable value name)))))
1795 ;; MODULE-DEFINED? -- exported
1797 ;; Return #t iff NAME is defined in MODULE (or in a module that MODULE
1800 (define (module-defined? module name)
1801 (let ((variable (module-variable module name)))
1802 (and variable (variable-bound? variable))))
1804 ;; MODULE-USE! module interface
1806 ;; Add INTERFACE to the list of interfaces used by MODULE.
1808 (define (module-use! module interface)
1809 (set-module-uses! module
1810 (cons interface (delq! interface (module-uses module)))))
1813 ;;; {Recursive Namespaces}
1816 ;;; A hierarchical namespace emerges if we consider some module to be
1817 ;;; root, and variables bound to modules as nested namespaces.
1819 ;;; The routines in this file manage variable names in hierarchical namespace.
1820 ;;; Each variable name is a list of elements, looked up in successively nested
1823 ;;; (nested-ref some-root-module '(foo bar baz))
1824 ;;; => <value of a variable named baz in the module bound to bar in
1825 ;;; the module bound to foo in some-root-module>
1830 ;;; ;; a-root is a module
1831 ;;; ;; name is a list of symbols
1833 ;;; nested-ref a-root name
1834 ;;; nested-set! a-root name val
1835 ;;; nested-define! a-root name val
1836 ;;; nested-remove! a-root name
1839 ;;; (current-module) is a natural choice for a-root so for convenience there are
1842 ;;; local-ref name == nested-ref (current-module) name
1843 ;;; local-set! name val == nested-set! (current-module) name val
1844 ;;; local-define! name val == nested-define! (current-module) name val
1845 ;;; local-remove! name == nested-remove! (current-module) name
1849 (define (nested-ref root names)
1850 (let loop ((cur root)
1854 ((not (module? cur)) #f)
1855 (else (loop (module-ref cur (car elts) #f) (cdr elts))))))
1857 (define (nested-set! root names val)
1858 (let loop ((cur root)
1860 (if (null? (cdr elts))
1861 (module-set! cur (car elts) val)
1862 (loop (module-ref cur (car elts)) (cdr elts)))))
1864 (define (nested-define! root names val)
1865 (let loop ((cur root)
1867 (if (null? (cdr elts))
1868 (module-define! cur (car elts) val)
1869 (loop (module-ref cur (car elts)) (cdr elts)))))
1871 (define (nested-remove! root names)
1872 (let loop ((cur root)
1874 (if (null? (cdr elts))
1875 (module-remove! cur (car elts))
1876 (loop (module-ref cur (car elts)) (cdr elts)))))
1878 (define (local-ref names) (nested-ref (current-module) names))
1879 (define (local-set! names val) (nested-set! (current-module) names val))
1880 (define (local-define names val) (nested-define! (current-module) names val))
1881 (define (local-remove names) (nested-remove! (current-module) names))
1885 ;;; {The (app) module}
1887 ;;; The root of conventionally named objects not directly in the top level.
1890 ;;; (app modules guile)
1892 ;;; The directory of all modules and the standard root module.
1895 (define (module-public-interface m)
1896 (module-ref m '%module-public-interface #f))
1897 (define (set-module-public-interface! m i)
1898 (module-define! m '%module-public-interface i))
1899 (define (set-system-module! m s)
1900 (set-procedure-property! (module-eval-closure m) 'system-module s))
1901 (define the-root-module (make-root-module))
1902 (define the-scm-module (make-scm-module))
1903 (set-module-public-interface! the-root-module the-scm-module)
1904 (set-module-name! the-root-module 'the-root-module)
1905 (set-module-name! the-scm-module 'the-scm-module)
1906 (for-each set-system-module! (list the-root-module the-scm-module) '(#t #t))
1908 (set-current-module the-root-module)
1910 (define app (make-module 31))
1911 (local-define '(app modules) (make-module 31))
1912 (local-define '(app modules guile) the-root-module)
1914 ;; (define-special-value '(app modules new-ws) (lambda () (make-scm-module)))
1916 (define (try-load-module name)
1917 (or (try-module-linked name)
1918 (try-module-autoload name)
1919 (try-module-dynamic-link name)))
1921 ;; NOTE: This binding is used in libguile/modules.c.
1923 (define (resolve-module name . maybe-autoload)
1924 (let ((full-name (append '(app modules) name)))
1925 (let ((already (local-ref full-name)))
1927 ;; The module already exists...
1928 (if (and (or (null? maybe-autoload) (car maybe-autoload))
1929 (not (module-ref already '%module-public-interface #f)))
1930 ;; ...but we are told to load and it doesn't contain source, so
1932 (try-load-module name)
1934 ;; simply return it.
1937 ;; Try to autoload it if we are told so
1938 (if (or (null? maybe-autoload) (car maybe-autoload))
1939 (try-load-module name))
1941 (make-modules-in (current-module) full-name))))))
1943 (define (beautify-user-module! module)
1944 (let ((interface (module-public-interface module)))
1945 (if (or (not interface)
1946 (eq? interface module))
1947 (let ((interface (make-module 31)))
1948 (set-module-name! interface (module-name module))
1949 (set-module-kind! interface 'interface)
1950 (set-module-public-interface! module interface))))
1951 (if (and (not (memq the-scm-module (module-uses module)))
1952 (not (eq? module the-root-module)))
1953 (set-module-uses! module (append (module-uses module) (list the-scm-module)))))
1955 ;; NOTE: This binding is used in libguile/modules.c.
1957 (define (make-modules-in module name)
1961 ((module-ref module (car name) #f)
1962 => (lambda (m) (make-modules-in m (cdr name))))
1963 (else (let ((m (make-module 31)))
1964 (set-module-kind! m 'directory)
1965 (set-module-name! m (car name))
1966 (module-define! module (car name) m)
1967 (make-modules-in m (cdr name)))))))
1969 (define (resolve-interface name)
1970 (let ((module (resolve-module name)))
1971 (and module (module-public-interface module))))
1974 (define %autoloader-developer-mode #t)
1976 (define (process-define-module args)
1977 (let* ((module-id (car args))
1978 (module (resolve-module module-id #f))
1980 (beautify-user-module! module)
1981 (let loop ((kws kws)
1982 (reversed-interfaces '()))
1984 (for-each (lambda (interface)
1985 (module-use! module interface))
1986 reversed-interfaces)
1987 (let ((keyword (cond ((keyword? (car kws))
1988 (keyword->symbol (car kws)))
1989 ((and (symbol? (car kws))
1990 (eq? (string-ref (car kws) 0) #\:))
1991 (string->symbol (substring (car kws) 1)))
1994 ((use-module use-syntax)
1995 (if (not (pair? (cdr kws)))
1996 (error "unrecognized defmodule argument" kws))
1997 (let* ((used-name (cadr kws))
1998 (used-module (resolve-module used-name)))
1999 (if (not (module-ref used-module
2000 '%module-public-interface
2003 ((if %autoloader-developer-mode warn error)
2004 "no code for module" (module-name used-module))
2005 (beautify-user-module! used-module)))
2006 (let ((interface (module-public-interface used-module)))
2008 (error "missing interface for use-module"
2010 (if (eq? keyword 'use-syntax)
2011 (set-module-transformer!
2013 (module-ref interface (car (last-pair used-name))
2016 (cons interface reversed-interfaces)))))
2018 (if (not (and (pair? (cdr kws)) (pair? (cddr kws))))
2019 (error "unrecognized defmodule argument" kws))
2021 (cons (make-autoload-interface module
2024 reversed-interfaces)))
2026 (set-system-module! module #t)
2027 (loop (cdr kws) reversed-interfaces))
2029 (error "unrecognized defmodule argument" kws))))))
2034 (define (make-autoload-interface module name bindings)
2035 (let ((b (lambda (a sym definep)
2036 (and (memq sym bindings)
2037 (let ((i (module-public-interface (resolve-module name))))
2039 (error "missing interface for module" name))
2040 ;; Replace autoload-interface with interface
2041 (set-car! (memq a (module-uses module)) i)
2042 (module-local-variable i sym))))))
2043 (module-constructor #() #f b #f #f name 'autoload)))
2046 ;;; {Autoloading modules}
2048 (define autoloads-in-progress '())
2050 (define (try-module-autoload module-name)
2052 (define (sfx name) (string-append name (scheme-file-suffix)))
2053 (let* ((reverse-name (reverse module-name))
2054 (name (car reverse-name))
2055 (dir-hint-module-name (reverse (cdr reverse-name)))
2056 (dir-hint (apply symbol-append (map (lambda (elt) (symbol-append elt "/")) dir-hint-module-name))))
2057 (resolve-module dir-hint-module-name #f)
2058 (and (not (autoload-done-or-in-progress? dir-hint name))
2061 (lambda () (autoload-in-progress! dir-hint name))
2063 (let loop ((dirs %load-path))
2064 (and (not (null? dirs))
2066 (let ((d (car dirs))
2070 (in-vicinity dir-hint name)
2071 (in-vicinity dir-hint (sfx name)))))
2072 (and (or-map (lambda (f)
2073 (let ((full (in-vicinity d f)))
2075 (and (file-exists? full)
2076 (not (file-is-directory? full))
2078 (save-module-excursion
2080 (load (string-append
2087 (loop (cdr dirs))))))
2088 (lambda () (set-autoloaded! dir-hint name didit)))
2092 ;;; Dynamic linking of modules
2094 ;; Initializing a module that is written in C is a two step process.
2095 ;; First the module's `module init' function is called. This function
2096 ;; is expected to call `scm_register_module_xxx' to register the `real
2097 ;; init' function. Later, when the module is referenced for the first
2098 ;; time, this real init function is called in the right context. See
2099 ;; gtcltk-lib/gtcltk-module.c for an example.
2101 ;; The code for the module can be in a regular shared library (so that
2102 ;; the `module init' function will be called when libguile is
2103 ;; initialized). Or it can be dynamically linked.
2105 ;; You can safely call `scm_register_module_xxx' before libguile
2106 ;; itself is initialized. You could call it from an C++ constructor
2107 ;; of a static object, for example.
2109 ;; To make your Guile extension into a dynamic linkable module, follow
2110 ;; these easy steps:
2112 ;; - Find a name for your module, like (ice-9 gtcltk)
2113 ;; - Write a function with a name like
2115 ;; scm_init_ice_9_gtcltk_module
2117 ;; This is your `module init' function. It should call
2119 ;; scm_register_module_xxx ("ice-9 gtcltk", scm_init_gtcltk);
2121 ;; "ice-9 gtcltk" is the C version of the module name. Slashes are
2122 ;; replaced by spaces, the rest is untouched. `scm_init_gtcltk' is
2123 ;; the real init function that executes the usual initializations
2124 ;; like making new smobs, etc.
2126 ;; - Make a shared library with your code and a name like
2128 ;; ice-9/libgtcltk.so
2130 ;; and put it somewhere in %load-path.
2132 ;; - Then you can simply write `:use-module (ice-9 gtcltk)' and it
2133 ;; will be linked automatically.
2135 ;; This is all very experimental.
2137 (define (split-c-module-name str)
2138 (let loop ((rev '())
2141 (end (string-length str)))
2144 (reverse (cons (string->symbol (substring str start pos)) rev)))
2145 ((eq? (string-ref str pos) #\space)
2146 (loop (cons (string->symbol (substring str start pos)) rev)
2151 (loop rev start (+ pos 1) end)))))
2153 (define (convert-c-registered-modules dynobj)
2154 (let ((res (map (lambda (c)
2155 (list (split-c-module-name (car c)) (cdr c) dynobj))
2156 (c-registered-modules))))
2157 (c-clear-registered-modules)
2160 (define registered-modules '())
2162 (define (register-modules dynobj)
2163 (set! registered-modules
2164 (append! (convert-c-registered-modules dynobj)
2165 registered-modules)))
2167 (define (init-dynamic-module modname)
2168 ;; Register any linked modules which has been registered on the C level
2169 (register-modules #f)
2170 (or-map (lambda (modinfo)
2171 (if (equal? (car modinfo) modname)
2173 (set! registered-modules (delq! modinfo registered-modules))
2174 (let ((mod (resolve-module modname #f)))
2175 (save-module-excursion
2177 (set-current-module mod)
2178 (set-module-public-interface! mod mod)
2179 (dynamic-call (cadr modinfo) (caddr modinfo))
2183 registered-modules))
2185 (define (dynamic-maybe-call name dynobj)
2186 (catch #t ; could use false-if-exception here
2188 (dynamic-call name dynobj))
2192 (define (dynamic-maybe-link filename)
2193 (catch #t ; could use false-if-exception here
2195 (dynamic-link filename))
2199 (define (find-and-link-dynamic-module module-name)
2200 (define (make-init-name mod-name)
2201 (string-append 'scm_init
2202 (list->string (map (lambda (c)
2203 (if (or (char-alphabetic? c)
2207 (string->list mod-name)))
2210 ;; Put the subdirectory for this module in the car of SUBDIR-AND-LIBNAME,
2211 ;; and the `libname' (the name of the module prepended by `lib') in the cdr
2212 ;; field. For example, if MODULE-NAME is the list (inet tcp-ip udp), then
2213 ;; SUBDIR-AND-LIBNAME will be the pair ("inet/tcp-ip" . "libudp").
2214 (let ((subdir-and-libname
2215 (let loop ((dirs "")
2217 (if (null? (cdr syms))
2218 (cons dirs (string-append "lib" (car syms)))
2219 (loop (string-append dirs (car syms) "/") (cdr syms)))))
2220 (init (make-init-name (apply string-append
2222 (string-append "_" s))
2224 (let ((subdir (car subdir-and-libname))
2225 (libname (cdr subdir-and-libname)))
2227 ;; Now look in each dir in %LOAD-PATH for `subdir/libfoo.la'. If that
2228 ;; file exists, fetch the dlname from that file and attempt to link
2229 ;; against it. If `subdir/libfoo.la' does not exist, or does not seem
2230 ;; to name any shared library, look for `subdir/libfoo.so' instead and
2231 ;; link against that.
2232 (let check-dirs ((dir-list %load-path))
2233 (if (null? dir-list)
2235 (let* ((dir (in-vicinity (car dir-list) subdir))
2237 (or (try-using-libtool-name dir libname)
2238 (try-using-sharlib-name dir libname))))
2239 (if (and sharlib-full (file-exists? sharlib-full))
2240 (link-dynamic-module sharlib-full init)
2241 (check-dirs (cdr dir-list)))))))))
2243 (define (try-using-libtool-name libdir libname)
2244 (let ((libtool-filename (in-vicinity libdir
2245 (string-append libname ".la"))))
2246 (and (file-exists? libtool-filename)
2247 (with-input-from-file libtool-filename
2249 (let loop ((ln (read-line)))
2250 (cond ((eof-object? ln) #f)
2251 ((and (> (string-length ln) 9)
2252 (string=? "dlname='" (substring ln 0 8))
2253 (string-index ln #\' 8))
2256 (in-vicinity libdir (substring ln 8 end))))
2257 (else (loop (read-line))))))))))
2259 (define (try-using-sharlib-name libdir libname)
2260 (in-vicinity libdir (string-append libname ".so")))
2262 (define (link-dynamic-module filename initname)
2263 ;; Register any linked modules which has been registered on the C level
2264 (register-modules #f)
2265 (let ((dynobj (dynamic-link filename)))
2266 (dynamic-call initname dynobj)
2267 (register-modules dynobj)))
2269 (define (try-module-linked module-name)
2270 (init-dynamic-module module-name))
2272 (define (try-module-dynamic-link module-name)
2273 (and (find-and-link-dynamic-module module-name)
2274 (init-dynamic-module module-name)))
2278 (define autoloads-done '((guile . guile)))
2280 (define (autoload-done-or-in-progress? p m)
2281 (let ((n (cons p m)))
2282 (->bool (or (member n autoloads-done)
2283 (member n autoloads-in-progress)))))
2285 (define (autoload-done! p m)
2286 (let ((n (cons p m)))
2287 (set! autoloads-in-progress
2288 (delete! n autoloads-in-progress))
2289 (or (member n autoloads-done)
2290 (set! autoloads-done (cons n autoloads-done)))))
2292 (define (autoload-in-progress! p m)
2293 (let ((n (cons p m)))
2294 (set! autoloads-done
2295 (delete! n autoloads-done))
2296 (set! autoloads-in-progress (cons n autoloads-in-progress))))
2298 (define (set-autoloaded! p m done?)
2300 (autoload-done! p m)
2301 (let ((n (cons p m)))
2302 (set! autoloads-done (delete! n autoloads-done))
2303 (set! autoloads-in-progress (delete! n autoloads-in-progress)))))
2312 (define (primitive-macro? m)
2314 (not (macro-transformer m))))
2318 (define macro-table (make-weak-key-hash-table 523))
2319 (define xformer-table (make-weak-key-hash-table 523))
2321 (define (defmacro? m) (hashq-ref macro-table m))
2322 (define (assert-defmacro?! m) (hashq-set! macro-table m #t))
2323 (define (defmacro-transformer m) (hashq-ref xformer-table m))
2324 (define (set-defmacro-transformer! m t) (hashq-set! xformer-table m t))
2326 (define defmacro:transformer
2328 (let* ((xform (lambda (exp env)
2329 (copy-tree (apply f (cdr exp)))))
2330 (a (procedure->memoizing-macro xform)))
2331 (assert-defmacro?! a)
2332 (set-defmacro-transformer! a f)
2337 (let ((defmacro-transformer
2338 (lambda (name parms . body)
2339 (let ((transformer `(lambda ,parms ,@body)))
2341 (,(lambda (transformer)
2342 (defmacro:transformer transformer))
2344 (defmacro:transformer defmacro-transformer)))
2346 (define defmacro:syntax-transformer
2350 (copy-tree (apply f (cdr exp)))))))
2353 ;; XXX - should the definition of the car really be looked up in the
2356 (define (macroexpand-1 e)
2358 ((pair? e) (let* ((a (car e))
2359 (val (and (symbol? a) (local-ref (list a)))))
2361 (apply (defmacro-transformer val) (cdr e))
2365 (define (macroexpand e)
2367 ((pair? e) (let* ((a (car e))
2368 (val (and (symbol? a) (local-ref (list a)))))
2370 (macroexpand (apply (defmacro-transformer val) (cdr e)))
2381 ;;; {Run-time options}
2383 ((let* ((names '((eval-options-interface
2384 (eval-options eval-enable eval-disable)
2387 (debug-options-interface
2388 (debug-options debug-enable debug-disable)
2391 (evaluator-traps-interface
2392 (traps trap-enable trap-disable)
2395 (read-options-interface
2396 (read-options read-enable read-disable)
2399 (print-options-interface
2400 (print-options print-enable print-disable)
2403 (readline-options-interface
2404 (readline-options readline-enable readline-disable)
2409 (option-documentation caddr)
2411 (print-option (lambda (option)
2412 (display (option-name option))
2413 (if (< (string-length
2414 (symbol->string (option-name option)))
2418 (display (option-value option))
2420 (display (option-documentation option))
2423 ;; Below follows the macros defining the run-time option interfaces.
2425 (make-options (lambda (interface)
2427 (cond ((null? args) (,interface))
2429 (,interface (car args)) (,interface))
2430 (else (for-each ,print-option
2431 (,interface #t)))))))
2433 (make-enable (lambda (interface)
2435 (,interface (append flags (,interface)))
2438 (make-disable (lambda (interface)
2440 (let ((options (,interface)))
2441 (for-each (lambda (flag)
2442 (set! options (delq! flag options)))
2444 (,interface options)
2447 (make-set! (lambda (interface)
2450 (begin (,interface (append (,interface)
2451 (list '(,'unquote name)
2459 (map (lambda (group)
2460 (let ((interface (car group)))
2461 (append (map (lambda (name constructor)
2463 ,(constructor interface)))
2468 (map (lambda (name constructor)
2470 ,@(constructor interface)))
2472 (list make-set!)))))
2480 (define (repl read evaler print)
2481 (let loop ((source (read (current-input-port))))
2482 (print (evaler source))
2483 (loop (read (current-input-port)))))
2485 ;; A provisional repl that acts like the SCM repl:
2487 (define scm-repl-silent #f)
2488 (define (assert-repl-silence v) (set! scm-repl-silent v))
2490 (define *unspecified* (if #f #f))
2491 (define (unspecified? v) (eq? v *unspecified*))
2493 (define scm-repl-print-unspecified #f)
2494 (define (assert-repl-print-unspecified v) (set! scm-repl-print-unspecified v))
2496 (define scm-repl-verbose #f)
2497 (define (assert-repl-verbosity v) (set! scm-repl-verbose v))
2499 (define scm-repl-prompt "guile> ")
2501 (define (set-repl-prompt! v) (set! scm-repl-prompt v))
2503 (define (default-lazy-handler key . args)
2504 (save-stack lazy-handler-dispatch)
2505 (apply throw key args))
2507 (define enter-frame-handler default-lazy-handler)
2508 (define apply-frame-handler default-lazy-handler)
2509 (define exit-frame-handler default-lazy-handler)
2511 (define (lazy-handler-dispatch key . args)
2514 (apply apply-frame-handler key args))
2516 (apply exit-frame-handler key args))
2518 (apply enter-frame-handler key args))
2520 (apply default-lazy-handler key args))))
2522 (define abort-hook (make-hook))
2524 ;; these definitions are used if running a script.
2525 ;; otherwise redefined in error-catching-loop.
2526 (define (set-batch-mode?! arg) #t)
2527 (define (batch-mode?) #t)
2529 (define (error-catching-loop thunk)
2532 (define (loop first)
2540 (lambda () (unmask-signals))
2546 ;; This line is needed because mark
2547 ;; doesn't do closures quite right.
2548 ;; Unreferenced locals should be
2552 (let loop ((v (thunk)))
2555 (lambda () (mask-signals))))
2557 lazy-handler-dispatch))
2559 (lambda (key . args)
2566 (apply throw 'switch-repl args))
2569 ;; This is one of the closures that require
2570 ;; (set! first #f) above
2573 (run-hook abort-hook)
2574 (force-output (current-output-port))
2575 (display "ABORT: " (current-error-port))
2576 (write args (current-error-port))
2577 (newline (current-error-port))
2581 (not has-shown-debugger-hint?)
2582 (not (memq 'backtrace
2583 (debug-options-interface)))
2584 (stack? (fluid-ref the-last-stack)))
2586 (newline (current-error-port))
2588 "Type \"(backtrace)\" to get more information.\n"
2589 (current-error-port))
2590 (set! has-shown-debugger-hint? #t)))
2591 (force-output (current-error-port)))
2593 (primitive-exit 1)))
2594 (set! stack-saved? #f)))
2597 ;; This is the other cons-leak closure...
2599 (cond ((= (length args) 4)
2600 (apply handle-system-error key args))
2602 (apply bad-throw key args))))))))))
2603 (if next (loop next) status)))
2604 (set! set-batch-mode?! (lambda (arg)
2606 (set! interactive #f)
2609 (error "sorry, not implemented")))))
2610 (set! batch-mode? (lambda () (not interactive)))
2611 (loop (lambda () #t))))
2613 ;;(define the-last-stack (make-fluid)) Defined by scm_init_backtrace ()
2614 (define stack-saved? #f)
2616 (define (save-stack . narrowing)
2618 (cond ((not (memq 'debug (debug-options-interface)))
2619 (fluid-set! the-last-stack #f)
2620 (set! stack-saved? #t))
2626 (apply make-stack #t save-stack eval #t 0 narrowing))
2628 (apply make-stack #t save-stack 0 #t 0 narrowing))
2630 (apply make-stack #t save-stack tk-stack-mark #t 0 narrowing))
2632 (apply make-stack #t save-stack 0 1 narrowing))
2634 (let ((id (stack-id #t)))
2635 (and (procedure? id)
2636 (apply make-stack #t save-stack id #t 0 narrowing))))))
2637 (set! stack-saved? #t)))))
2639 (define before-error-hook (make-hook))
2640 (define after-error-hook (make-hook))
2641 (define before-backtrace-hook (make-hook))
2642 (define after-backtrace-hook (make-hook))
2644 (define has-shown-debugger-hint? #f)
2646 (define (handle-system-error key . args)
2647 (let ((cep (current-error-port)))
2648 (cond ((not (stack? (fluid-ref the-last-stack))))
2649 ((memq 'backtrace (debug-options-interface))
2650 (run-hook before-backtrace-hook)
2652 (display-backtrace (fluid-ref the-last-stack) cep)
2654 (run-hook after-backtrace-hook)))
2655 (run-hook before-error-hook)
2656 (apply display-error (fluid-ref the-last-stack) cep args)
2657 (run-hook after-error-hook)
2659 (throw 'abort key)))
2661 (define (quit . args)
2662 (apply throw 'quit args))
2666 ;;(define has-shown-backtrace-hint? #f) Defined by scm_init_backtrace ()
2668 ;; Replaced by C code:
2669 ;;(define (backtrace)
2670 ;; (if (fluid-ref the-last-stack)
2673 ;; (display-backtrace (fluid-ref the-last-stack) (current-output-port))
2675 ;; (if (and (not has-shown-backtrace-hint?)
2676 ;; (not (memq 'backtrace (debug-options-interface))))
2679 ;;"Type \"(debug-enable 'backtrace)\" if you would like a backtrace
2680 ;;automatically if an error occurs in the future.\n")
2681 ;; (set! has-shown-backtrace-hint? #t))))
2682 ;; (display "No backtrace available.\n")))
2684 (define (error-catching-repl r e p)
2685 (error-catching-loop (lambda () (p (e (r))))))
2687 (define (gc-run-time)
2688 (cdr (assq 'gc-time-taken (gc-stats))))
2690 (define before-read-hook (make-hook))
2691 (define after-read-hook (make-hook))
2693 ;;; The default repl-reader function. We may override this if we've
2694 ;;; the readline library.
2699 (run-hook before-read-hook)
2700 (read (current-input-port))))
2702 (define (scm-style-repl)
2706 (repl-report-start-timing (lambda ()
2707 (set! start-gc-rt (gc-run-time))
2708 (set! start-rt (get-internal-run-time))))
2709 (repl-report (lambda ()
2711 (display (inexact->exact
2712 (* 1000 (/ (- (get-internal-run-time) start-rt)
2713 internal-time-units-per-second))))
2715 (display (inexact->exact
2716 (* 1000 (/ (- (gc-run-time) start-gc-rt)
2717 internal-time-units-per-second))))
2718 (display " msec in gc)\n")))
2720 (consume-trailing-whitespace
2722 (let ((ch (peek-char)))
2725 ((or (char=? ch #\space) (char=? ch #\tab))
2727 (consume-trailing-whitespace))
2728 ((char=? ch #\newline)
2732 (let ((prompt (cond ((string? scm-repl-prompt)
2734 ((thunk? scm-repl-prompt)
2736 (scm-repl-prompt "> ")
2738 (repl-reader prompt))))
2740 ;; As described in R4RS, the READ procedure updates the
2741 ;; port to point to the first character past the end of
2742 ;; the external representation of the object. This
2743 ;; means that it doesn't consume the newline typically
2744 ;; found after an expression. This means that, when
2745 ;; debugging Guile with GDB, GDB gets the newline, which
2746 ;; it often interprets as a "continue" command, making
2747 ;; breakpoints kind of useless. So, consume any
2748 ;; trailing newline here, as well as any whitespace
2750 ;; But not if EOF, for control-D.
2751 (if (not (eof-object? val))
2752 (consume-trailing-whitespace))
2753 (run-hook after-read-hook)
2754 (if (eof-object? val)
2756 (repl-report-start-timing)
2757 (if scm-repl-verbose
2760 (display ";;; EOF -- quitting")
2765 (-eval (lambda (sourc)
2766 (repl-report-start-timing)
2767 (start-stack 'repl-stack (eval sourc))))
2769 (-print (lambda (result)
2770 (if (not scm-repl-silent)
2772 (if (or scm-repl-print-unspecified
2773 (not (unspecified? result)))
2777 (if scm-repl-verbose
2781 (-quit (lambda (args)
2782 (if scm-repl-verbose
2784 (display ";;; QUIT executed, repl exitting")
2790 (if scm-repl-verbose
2792 (display ";;; ABORT executed.")
2795 (repl -read -eval -print))))
2797 (let ((status (error-catching-repl -read
2804 ;;; {IOTA functions: generating lists of numbers}
2807 (let loop ((count (1- n)) (result '()))
2808 (if (< count 0) result
2809 (loop (1- count) (cons count result)))))
2814 ;;; with `continue' and `break'.
2817 (defmacro while (cond . body)
2818 `(letrec ((continue (lambda () (or (not ,cond) (begin (begin ,@ body) (continue)))))
2819 (break (lambda val (apply throw 'break val))))
2821 (lambda () (continue))
2822 (lambda v (cadr v)))))
2826 ;;; Similar to `begin' but returns a list of the results of all constituent
2827 ;;; forms instead of the result of the last form.
2828 ;;; (The definition relies on the current left-to-right
2829 ;;; order of evaluation of operands in applications.)
2831 (defmacro collect forms
2836 ;; with-fluids is a convenience wrapper for the builtin procedure
2837 ;; `with-fluids*'. The syntax is just like `let':
2839 ;; (with-fluids ((fluid val)
2843 (defmacro with-fluids (bindings . body)
2844 `(with-fluids* (list ,@(map car bindings)) (list ,@(map cadr bindings))
2845 (lambda () ,@body)))
2849 (define the-environment
2854 (define (environment-module env)
2855 (let ((closure (and (pair? env) (car (last-pair env)))))
2856 (and closure (procedure-property closure 'module))))
2863 ;; actually....hobbit might be able to hack these with a little
2867 (defmacro define-macro (first . rest)
2868 (let ((name (if (symbol? first) first (car first)))
2872 `(lambda ,(cdr first) ,@rest))))
2873 `(define ,name (defmacro:transformer ,transformer))))
2876 (defmacro define-syntax-macro (first . rest)
2877 (let ((name (if (symbol? first) first (car first)))
2881 `(lambda ,(cdr first) ,@rest))))
2882 `(define ,name (defmacro:syntax-transformer ,transformer))))
2884 ;;; {Module System Macros}
2887 (defmacro define-module args
2888 `(let* ((process-define-module process-define-module)
2889 (set-current-module set-current-module)
2890 (module (process-define-module ',args)))
2891 (set-current-module module)
2894 ;; the guts of the use-modules macro. add the interfaces of the named
2895 ;; modules to the use-list of the current module, in order
2896 (define (process-use-modules module-names)
2897 (for-each (lambda (module-name)
2898 (let ((mod-iface (resolve-interface module-name)))
2900 (error "no such module" module-name))
2901 (module-use! (current-module) mod-iface)))
2902 (reverse module-names)))
2904 (defmacro use-modules modules
2905 `(process-use-modules ',modules))
2907 (defmacro use-syntax (spec)
2910 `((process-use-modules ',(list spec))
2911 (set-module-transformer! (current-module)
2912 ,(car (last-pair spec))))
2913 `((set-module-transformer! (current-module) ,spec)))
2914 (set! scm:eval-transformer (module-transformer (current-module)))))
2916 (define define-private define)
2918 (defmacro define-public args
2920 (error "bad syntax" (list 'define-public args)))
2921 (define (defined-name n)
2924 ((pair? n) (defined-name (car n)))
2927 ((null? args) (syntax))
2929 (#t (let ((name (defined-name (car args))))
2931 (let ((public-i (module-public-interface (current-module))))
2932 ;; Make sure there is a local variable:
2934 (module-define! (current-module)
2936 (module-ref (current-module) ',name #f))
2938 ;; Make sure that local is exported:
2940 (module-add! public-i ',name
2941 (module-variable (current-module) ',name)))
2943 ;; Now (re)define the var normally. Bernard URBAN
2944 ;; suggests we use eval here to accomodate Hobbit; it lets
2945 ;; the interpreter handle the define-private form, which
2946 ;; Hobbit can't digest.
2947 (eval '(define-private ,@ args)))))))
2951 (defmacro defmacro-public args
2953 (error "bad syntax" (list 'defmacro-public args)))
2954 (define (defined-name n)
2959 ((null? args) (syntax))
2961 (#t (let ((name (defined-name (car args))))
2963 (let ((public-i (module-public-interface (current-module))))
2964 ;; Make sure there is a local variable:
2966 (module-define! (current-module)
2968 (module-ref (current-module) ',name #f))
2970 ;; Make sure that local is exported:
2972 (module-add! public-i ',name (module-variable (current-module) ',name)))
2974 ;; Now (re)define the var normally.
2976 (defmacro ,@ args))))))
2979 (defmacro export names
2980 `(let* ((m (current-module))
2981 (public-i (module-public-interface m)))
2982 (for-each (lambda (name)
2983 ;; Make sure there is a local variable:
2984 (module-define! m name (module-ref m name #f))
2985 ;; Make sure that local is exported:
2986 (module-add! public-i name (module-variable m name)))
2989 (define export-syntax export)
2994 (define load load-module)
2998 ;;; {Load emacs interface support if emacs option is given.}
3000 (define (load-emacs-interface)
3001 (if (memq 'debug-extensions *features*)
3002 (debug-enable 'backtrace))
3003 (define-module (guile-user) :use-module (ice-9 emacs)))
3006 ;;; {I/O functions for Tcl channels (disabled)}
3008 ;; (define in-ch (get-standard-channel TCL_STDIN))
3009 ;; (define out-ch (get-standard-channel TCL_STDOUT))
3010 ;; (define err-ch (get-standard-channel TCL_STDERR))
3012 ;; (define inp (%make-channel-port in-ch "r"))
3013 ;; (define outp (%make-channel-port out-ch "w"))
3014 ;; (define errp (%make-channel-port err-ch "w"))
3016 ;; (define %system-char-ready? char-ready?)
3018 ;; (define (char-ready? p)
3019 ;; (if (not (channel-port? p))
3020 ;; (%system-char-ready? p)
3021 ;; (let* ((channel (%channel-port-channel p))
3022 ;; (old-blocking (channel-option-ref channel :blocking)))
3024 ;; (lambda () (set-channel-option the-root-tcl-interpreter channel :blocking "0"))
3025 ;; (lambda () (not (eof-object? (peek-char p))))
3026 ;; (lambda () (set-channel-option the-root-tcl-interpreter channel :blocking old-blocking))))))
3028 ;; (define (top-repl)
3029 ;; (with-input-from-port inp
3031 ;; (with-output-to-port outp
3033 ;; (with-error-to-port errp
3035 ;; (scm-style-repl))))))))
3037 ;; (set-current-input-port inp)
3038 ;; (set-current-output-port outp)
3039 ;; (set-current-error-port errp)
3041 ;; this is just (scm-style-repl) with a wrapper to install and remove
3045 ;; Load emacs interface support if emacs option is given.
3046 (if (and (module-defined? the-root-module 'use-emacs-interface)
3047 use-emacs-interface)
3048 (load-emacs-interface))
3050 ;; Place the user in the guile-user module.
3051 (define-module (guile-user))
3053 (let ((old-handlers #f)
3054 (signals `((,SIGINT . "User interrupt")
3055 (,SIGFPE . "Arithmetic error")
3056 (,SIGBUS . "Bad memory access (bus error)")
3057 (,SIGSEGV . "Bad memory access (Segmentation violation)"))))
3063 (let ((make-handler (lambda (msg)
3065 (save-stack %deliver-signals)
3072 (map (lambda (sig-msg)
3073 (sigaction (car sig-msg)
3074 (make-handler (cdr sig-msg))))
3077 ;; the protected thunk.
3080 ;; If we've got readline, use it to prompt the user. This is a
3081 ;; kludge, but we'll fix it soon. At least we only get
3082 ;; readline involved when we're actually running the repl.
3083 (if (and (memq 'readline *features*)
3084 (isatty? (current-input-port))
3085 (not (and (module-defined? the-root-module
3086 'use-emacs-interface)
3087 use-emacs-interface)))
3088 (let ((read-hook (lambda () (run-hook before-read-hook))))
3089 (set-current-input-port (readline-port))
3094 (set-readline-prompt! prompt "... ")
3095 (set-readline-read-hook! read-hook))
3098 (set-readline-prompt! "" "")
3099 (set-readline-read-hook! #f)))))))
3100 (let ((status (scm-style-repl)))
3101 (run-hook exit-hook)
3106 (map (lambda (sig-msg old-handler)
3107 (if (not (car old-handler))
3108 ;; restore original C handler.
3109 (sigaction (car sig-msg) #f)
3110 ;; restore Scheme handler, SIG_IGN or SIG_DFL.
3111 (sigaction (car sig-msg)
3113 (cdr old-handler))))
3114 signals old-handlers)))))
3116 (defmacro false-if-exception (expr)
3117 `(catch #t (lambda () ,expr)
3120 ;;; This hook is run at the very end of an interactive session.
3122 (define exit-hook (make-hook))
3124 ;;; Load readline code into root module if readline primitives are available.
3126 ;;; Ideally, we wouldn't do this until we were sure we were actually
3127 ;;; going to enter the repl, but autoloading individual functions is
3128 ;;; clumsy at the moment.
3129 (if (and (memq 'readline *features*)
3130 (isatty? (current-input-port)))
3132 (define-module (guile) :use-module (ice-9 readline))
3133 (define-module (guile-user) :use-module (ice-9 readline))))
3136 ;;; {Load debug extension code into user module if debug extensions present.}
3138 ;;; *fixme* This is a temporary solution.
3141 (if (memq 'debug-extensions *features*)
3142 (define-module (guile-user) :use-module (ice-9 debug)))
3145 ;;; {Load session support into user module if present.}
3147 ;;; *fixme* This is a temporary solution.
3150 (if (%search-load-path "ice-9/session.scm")
3151 (define-module (guile-user) :use-module (ice-9 session)))
3153 ;;; {Load thread code into user module if threads are present.}
3155 ;;; *fixme* This is a temporary solution.
3158 (if (memq 'threads *features*)
3159 (define-module (guile-user) :use-module (ice-9 threads)))
3162 ;;; {Load regexp code if regexp primitives are available.}
3164 (if (memq 'regex *features*)
3165 (define-module (guile-user) :use-module (ice-9 regex)))
3168 (define-module (guile))
3170 ;;; {Check that the interpreter and scheme code match up.}
3174 (with-output-to-port (current-error-port)
3176 (display (car (command-line)))
3178 (for-each (lambda (string) (display string))
3182 (load-from-path "ice-9/version.scm")
3185 (libguile-config-stamp) ; from the interprpreter
3186 (ice-9-config-stamp))) ; from the Scheme code
3188 (show-line "warning: different versions of libguile and ice-9:")
3189 (show-line "libguile: configured on " (libguile-config-stamp))
3190 (show-line "ice-9: configured on " (ice-9-config-stamp)))))
3192 (append! %load-path (cons "." ()))