* Fixed the changelog entry regarding re-introduction of struct member
[bpt/guile.git] / ice-9 / boot-9.scm
... / ...
CommitLineData
1;;; installed-scm-file
2
3;;;; Copyright (C) 1995, 1996, 1997, 1998, 1999, 2000 Free Software Foundation, Inc.
4;;;;
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.
9;;;;
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.
14;;;;
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
19;;;;
20\f
21
22;;; This file is the first thing loaded into Guile. It adds many mundane
23;;; definitions and a few that are interesting.
24;;;
25;;; The module system (hence the hierarchical namespace) are defined in this
26;;; file.
27;;;
28
29\f
30;;; {Features}
31;;
32
33(define (provide sym)
34 (if (not (memq sym *features*))
35 (set! *features* (cons sym *features*))))
36
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))
42
43;;; presumably deprecated.
44(define feature? provided?)
45
46;;; let format alias simple-format until the more complete version is loaded
47(define format simple-format)
48
49\f
50;;; {R4RS compliance}
51
52(primitive-load-path "ice-9/r4rs.scm")
53
54\f
55;;; {Simple Debugging Tools}
56;;
57
58
59;; peek takes any number of arguments, writes them to the
60;; current ouput port, and returns the last argument.
61;; It is handy to wrap around an expression to look at
62;; a value each time is evaluated, e.g.:
63;;
64;; (+ 10 (troublesome-fn))
65;; => (+ 10 (pk 'troublesome-fn-returned (troublesome-fn)))
66;;
67
68(define (peek . stuff)
69 (newline)
70 (display ";;; ")
71 (write stuff)
72 (newline)
73 (car (last-pair stuff)))
74
75(define pk peek)
76
77(define (warn . stuff)
78 (with-output-to-port (current-error-port)
79 (lambda ()
80 (newline)
81 (display ";;; WARNING ")
82 (display stuff)
83 (newline)
84 (car (last-pair stuff)))))
85
86\f
87;;; {Trivial Functions}
88;;;
89
90(define (id x) x)
91(define (1+ n) (+ n 1))
92(define (-1+ n) (+ n -1))
93(define 1- -1+)
94(define return-it noop)
95(define (and=> value procedure) (and value (procedure value)))
96(define (make-hash-table k) (make-vector k '()))
97
98;;; apply-to-args is functionally redunant with apply and, worse,
99;;; is less general than apply since it only takes two arguments.
100;;;
101;;; On the other hand, apply-to-args is a syntacticly convenient way to
102;;; perform binding in many circumstances when the "let" family of
103;;; of forms don't cut it. E.g.:
104;;;
105;;; (apply-to-args (return-3d-mouse-coords)
106;;; (lambda (x y z)
107;;; ...))
108;;;
109
110(define (apply-to-args args fn) (apply fn args))
111
112\f
113;;; {Integer Math}
114;;;
115
116(define (ipow-by-squaring x k acc proc)
117 (cond ((zero? k) acc)
118 ((= 1 k) (proc acc x))
119 (else (ipow-by-squaring (proc x x)
120 (quotient k 2)
121 (if (even? k) acc (proc acc x))
122 proc))))
123
124(define string-character-length string-length)
125
126
127
128;; A convenience function for combining flag bits. Like logior, but
129;; handles the cases of 0 and 1 arguments.
130;;
131(define (flags . args)
132 (cond
133 ((null? args) 0)
134 ((null? (cdr args)) (car args))
135 (else (apply logior args))))
136
137\f
138;;; {Symbol Properties}
139;;;
140
141(define (symbol-property sym prop)
142 (let ((pair (assoc prop (symbol-pref sym))))
143 (and pair (cdr pair))))
144
145(define (set-symbol-property! sym prop val)
146 (let ((pair (assoc prop (symbol-pref sym))))
147 (if pair
148 (set-cdr! pair val)
149 (symbol-pset! sym (acons prop val (symbol-pref sym))))))
150
151(define (symbol-property-remove! sym prop)
152 (let ((pair (assoc prop (symbol-pref sym))))
153 (if pair
154 (symbol-pset! sym (delq! pair (symbol-pref sym))))))
155
156;;; {General Properties}
157
158;; This is a more modern interface to properties. It will replace all
159;; other property-like things eventually.
160
161(define (make-object-property)
162 (let ((prop (primitive-make-property #f)))
163 (make-procedure-with-setter
164 (lambda (obj) (primitive-property-ref prop obj))
165 (lambda (obj val) (primitive-property-set! prop obj val)))))
166
167\f
168
169;;; {Line and Delimited I/O}
170
171;;; corresponds to SCM_LINE_INCREMENTORS in libguile.
172(define scm-line-incrementors "\n")
173
174(define (read-line! string . maybe-port)
175 (let* ((port (if (pair? maybe-port)
176 (car maybe-port)
177 (current-input-port))))
178 (let* ((rv (%read-delimited! scm-line-incrementors
179 string
180 #t
181 port))
182 (terminator (car rv))
183 (nchars (cdr rv)))
184 (cond ((and (= nchars 0)
185 (eof-object? terminator))
186 terminator)
187 ((not terminator) #f)
188 (else nchars)))))
189
190(define (read-delimited! delims buf . args)
191 (let* ((num-args (length args))
192 (port (if (> num-args 0)
193 (car args)
194 (current-input-port)))
195 (handle-delim (if (> num-args 1)
196 (cadr args)
197 'trim))
198 (start (if (> num-args 2)
199 (caddr args)
200 0))
201 (end (if (> num-args 3)
202 (cadddr args)
203 (string-length buf))))
204 (let* ((rv (%read-delimited! delims
205 buf
206 (not (eq? handle-delim 'peek))
207 port
208 start
209 end))
210 (terminator (car rv))
211 (nchars (cdr rv)))
212 (cond ((or (not terminator) ; buffer filled
213 (eof-object? terminator))
214 (if (zero? nchars)
215 (if (eq? handle-delim 'split)
216 (cons terminator terminator)
217 terminator)
218 (if (eq? handle-delim 'split)
219 (cons nchars terminator)
220 nchars)))
221 (else
222 (case handle-delim
223 ((trim peek) nchars)
224 ((concat) (string-set! buf (+ nchars start) terminator)
225 (+ nchars 1))
226 ((split) (cons nchars terminator))
227 (else (error "unexpected handle-delim value: "
228 handle-delim))))))))
229
230(define (read-delimited delims . args)
231 (let* ((port (if (pair? args)
232 (let ((pt (car args)))
233 (set! args (cdr args))
234 pt)
235 (current-input-port)))
236 (handle-delim (if (pair? args)
237 (car args)
238 'trim)))
239 (let loop ((substrings ())
240 (total-chars 0)
241 (buf-size 100)) ; doubled each time through.
242 (let* ((buf (make-string buf-size))
243 (rv (%read-delimited! delims
244 buf
245 (not (eq? handle-delim 'peek))
246 port))
247 (terminator (car rv))
248 (nchars (cdr rv))
249 (join-substrings
250 (lambda ()
251 (apply string-append
252 (reverse
253 (cons (if (and (eq? handle-delim 'concat)
254 (not (eof-object? terminator)))
255 (string terminator)
256 "")
257 (cons (substring buf 0 nchars)
258 substrings))))))
259 (new-total (+ total-chars nchars)))
260 (cond ((not terminator)
261 ;; buffer filled.
262 (loop (cons (substring buf 0 nchars) substrings)
263 new-total
264 (* buf-size 2)))
265 ((eof-object? terminator)
266 (if (zero? new-total)
267 (if (eq? handle-delim 'split)
268 (cons terminator terminator)
269 terminator)
270 (if (eq? handle-delim 'split)
271 (cons (join-substrings) terminator)
272 (join-substrings))))
273 (else
274 (case handle-delim
275 ((trim peek concat) (join-substrings))
276 ((split) (cons (join-substrings) terminator))
277
278
279 (else (error "unexpected handle-delim value: "
280 handle-delim)))))))))
281
282;;; read-line [PORT [HANDLE-DELIM]] reads a newline-terminated string
283;;; from PORT. The return value depends on the value of HANDLE-DELIM,
284;;; which may be one of the symbols `trim', `concat', `peek' and
285;;; `split'. If it is `trim' (the default), the trailing newline is
286;;; removed and the string is returned. If `concat', the string is
287;;; returned with the trailing newline intact. If `peek', the newline
288;;; is left in the input port buffer and the string is returned. If
289;;; `split', the newline is split from the string and read-line
290;;; returns a pair consisting of the truncated string and the newline.
291
292(define (read-line . args)
293 (let* ((port (if (null? args)
294 (current-input-port)
295 (car args)))
296 (handle-delim (if (> (length args) 1)
297 (cadr args)
298 'trim))
299 (line/delim (%read-line port))
300 (line (car line/delim))
301 (delim (cdr line/delim)))
302 (case handle-delim
303 ((trim) line)
304 ((split) line/delim)
305 ((concat) (if (and (string? line) (char? delim))
306 (string-append line (string delim))
307 line))
308 ((peek) (if (char? delim)
309 (unread-char delim port))
310 line)
311 (else
312 (error "unexpected handle-delim value: " handle-delim)))))
313
314\f
315;;; {Arrays}
316;;;
317
318(if (provided? 'array)
319 (primitive-load-path "ice-9/arrays.scm"))
320
321\f
322;;; {Keywords}
323;;;
324
325(define (symbol->keyword symbol)
326 (make-keyword-from-dash-symbol (symbol-append '- symbol)))
327
328(define (keyword->symbol kw)
329 (let ((sym (symbol->string (keyword-dash-symbol kw))))
330 (string->symbol (substring sym 1 (string-length sym)))))
331
332(define (kw-arg-ref args kw)
333 (let ((rem (member kw args)))
334 (and rem (pair? (cdr rem)) (cadr rem))))
335
336\f
337
338;;; {Structs}
339
340(define (struct-layout s)
341 (struct-ref (struct-vtable s) vtable-index-layout))
342
343\f
344
345;;; Environments
346
347(define the-environment
348 (procedure->syntax
349 (lambda (x e)
350 e)))
351
352(define the-root-environment (the-environment))
353
354(define (environment-module env)
355 (let ((closure (and (pair? env) (car (last-pair env)))))
356 (and closure (procedure-property closure 'module))))
357
358\f
359;;; {Records}
360;;;
361
362;; Printing records: by default, records are printed as
363;;
364;; #<type-name field1: val1 field2: val2 ...>
365;;
366;; You can change that by giving a custom printing function to
367;; MAKE-RECORD-TYPE (after the list of field symbols). This function
368;; will be called like
369;;
370;; (<printer> object port)
371;;
372;; It should print OBJECT to PORT.
373
374(define (inherit-print-state old-port new-port)
375 (if (get-print-state old-port)
376 (port-with-print-state new-port (get-print-state old-port))
377 new-port))
378
379;; 0: type-name, 1: fields
380(define record-type-vtable
381 (make-vtable-vtable "prpr" 0
382 (lambda (s p)
383 (cond ((eq? s record-type-vtable)
384 (display "#<record-type-vtable>" p))
385 (else
386 (display "#<record-type " p)
387 (display (record-type-name s) p)
388 (display ">" p))))))
389
390(define (record-type? obj)
391 (and (struct? obj) (eq? record-type-vtable (struct-vtable obj))))
392
393(define (make-record-type type-name fields . opt)
394 (let ((printer-fn (and (pair? opt) (car opt))))
395 (let ((struct (make-struct record-type-vtable 0
396 (make-struct-layout
397 (apply string-append
398 (map (lambda (f) "pw") fields)))
399 (or printer-fn
400 (lambda (s p)
401 (display "#<" p)
402 (display type-name p)
403 (let loop ((fields fields)
404 (off 0))
405 (cond
406 ((not (null? fields))
407 (display " " p)
408 (display (car fields) p)
409 (display ": " p)
410 (display (struct-ref s off) p)
411 (loop (cdr fields) (+ 1 off)))))
412 (display ">" p)))
413 type-name
414 (copy-tree fields))))
415 ;; Temporary solution: Associate a name to the record type descriptor
416 ;; so that the object system can create a wrapper class for it.
417 (set-struct-vtable-name! struct (if (symbol? type-name)
418 type-name
419 (string->symbol type-name)))
420 struct)))
421
422(define (record-type-name obj)
423 (if (record-type? obj)
424 (struct-ref obj vtable-offset-user)
425 (error 'not-a-record-type obj)))
426
427(define (record-type-fields obj)
428 (if (record-type? obj)
429 (struct-ref obj (+ 1 vtable-offset-user))
430 (error 'not-a-record-type obj)))
431
432(define (record-constructor rtd . opt)
433 (let ((field-names (if (pair? opt) (car opt) (record-type-fields rtd))))
434 (local-eval `(lambda ,field-names
435 (make-struct ',rtd 0 ,@(map (lambda (f)
436 (if (memq f field-names)
437 f
438 #f))
439 (record-type-fields rtd))))
440 the-root-environment)))
441
442(define (record-predicate rtd)
443 (lambda (obj) (and (struct? obj) (eq? rtd (struct-vtable obj)))))
444
445(define (record-accessor rtd field-name)
446 (let* ((pos (list-index (record-type-fields rtd) field-name)))
447 (if (not pos)
448 (error 'no-such-field field-name))
449 (local-eval `(lambda (obj)
450 (and (eq? ',rtd (record-type-descriptor obj))
451 (struct-ref obj ,pos)))
452 the-root-environment)))
453
454(define (record-modifier rtd field-name)
455 (let* ((pos (list-index (record-type-fields rtd) field-name)))
456 (if (not pos)
457 (error 'no-such-field field-name))
458 (local-eval `(lambda (obj val)
459 (and (eq? ',rtd (record-type-descriptor obj))
460 (struct-set! obj ,pos val)))
461 the-root-environment)))
462
463
464(define (record? obj)
465 (and (struct? obj) (record-type? (struct-vtable obj))))
466
467(define (record-type-descriptor obj)
468 (if (struct? obj)
469 (struct-vtable obj)
470 (error 'not-a-record obj)))
471
472(provide 'record)
473
474\f
475;;; {Booleans}
476;;;
477
478(define (->bool x) (not (not x)))
479
480\f
481;;; {Symbols}
482;;;
483
484(define (symbol-append . args)
485 (string->symbol (apply string-append (map symbol->string args))))
486
487(define (list->symbol . args)
488 (string->symbol (apply list->string args)))
489
490(define (symbol . args)
491 (string->symbol (apply string args)))
492
493\f
494;;; {Lists}
495;;;
496
497(define (list-index l k)
498 (let loop ((n 0)
499 (l l))
500 (and (not (null? l))
501 (if (eq? (car l) k)
502 n
503 (loop (+ n 1) (cdr l))))))
504
505(define (make-list n . init)
506 (if (pair? init) (set! init (car init)))
507 (let loop ((answer '())
508 (n n))
509 (if (<= n 0)
510 answer
511 (loop (cons init answer) (- n 1)))))
512
513\f
514;;; {and-map and or-map}
515;;;
516;;; (and-map fn lst) is like (and (fn (car lst)) (fn (cadr lst)) (fn...) ...)
517;;; (or-map fn lst) is like (or (fn (car lst)) (fn (cadr lst)) (fn...) ...)
518;;;
519
520;; and-map f l
521;;
522;; Apply f to successive elements of l until exhaustion or f returns #f.
523;; If returning early, return #f. Otherwise, return the last value returned
524;; by f. If f has never been called because l is empty, return #t.
525;;
526(define (and-map f lst)
527 (let loop ((result #t)
528 (l lst))
529 (and result
530 (or (and (null? l)
531 result)
532 (loop (f (car l)) (cdr l))))))
533
534;; or-map f l
535;;
536;; Apply f to successive elements of l until exhaustion or while f returns #f.
537;; If returning early, return the return value of f.
538;;
539(define (or-map f lst)
540 (let loop ((result #f)
541 (l lst))
542 (or result
543 (and (not (null? l))
544 (loop (f (car l)) (cdr l))))))
545
546\f
547
548(if (provided? 'posix)
549 (primitive-load-path "ice-9/posix.scm"))
550
551(if (provided? 'socket)
552 (primitive-load-path "ice-9/networking.scm"))
553
554(define file-exists?
555 (if (provided? 'posix)
556 (lambda (str)
557 (access? str F_OK))
558 (lambda (str)
559 (let ((port (catch 'system-error (lambda () (open-file str OPEN_READ))
560 (lambda args #f))))
561 (if port (begin (close-port port) #t)
562 #f)))))
563
564(define file-is-directory?
565 (if (provided? 'posix)
566 (lambda (str)
567 (eq? (stat:type (stat str)) 'directory))
568 (lambda (str)
569 (let ((port (catch 'system-error
570 (lambda () (open-file (string-append str "/.")
571 OPEN_READ))
572 (lambda args #f))))
573 (if port (begin (close-port port) #t)
574 #f)))))
575
576(define (has-suffix? str suffix)
577 (let ((sufl (string-length suffix))
578 (sl (string-length str)))
579 (and (> sl sufl)
580 (string=? (substring str (- sl sufl) sl) suffix))))
581
582\f
583;;; {Error Handling}
584;;;
585
586(define (error . args)
587 (save-stack)
588 (if (null? args)
589 (scm-error 'misc-error #f "?" #f #f)
590 (let loop ((msg "~A")
591 (rest (cdr args)))
592 (if (not (null? rest))
593 (loop (string-append msg " ~S")
594 (cdr rest))
595 (scm-error 'misc-error #f msg args #f)))))
596
597;; bad-throw is the hook that is called upon a throw to a an unhandled
598;; key (unless the throw has four arguments, in which case
599;; it's usually interpreted as an error throw.)
600;; If the key has a default handler (a throw-handler-default property),
601;; it is applied to the throw.
602;;
603(define (bad-throw key . args)
604 (let ((default (symbol-property key 'throw-handler-default)))
605 (or (and default (apply default key args))
606 (apply error "unhandled-exception:" key args))))
607
608\f
609
610(define (tm:sec obj) (vector-ref obj 0))
611(define (tm:min obj) (vector-ref obj 1))
612(define (tm:hour obj) (vector-ref obj 2))
613(define (tm:mday obj) (vector-ref obj 3))
614(define (tm:mon obj) (vector-ref obj 4))
615(define (tm:year obj) (vector-ref obj 5))
616(define (tm:wday obj) (vector-ref obj 6))
617(define (tm:yday obj) (vector-ref obj 7))
618(define (tm:isdst obj) (vector-ref obj 8))
619(define (tm:gmtoff obj) (vector-ref obj 9))
620(define (tm:zone obj) (vector-ref obj 10))
621
622(define (set-tm:sec obj val) (vector-set! obj 0 val))
623(define (set-tm:min obj val) (vector-set! obj 1 val))
624(define (set-tm:hour obj val) (vector-set! obj 2 val))
625(define (set-tm:mday obj val) (vector-set! obj 3 val))
626(define (set-tm:mon obj val) (vector-set! obj 4 val))
627(define (set-tm:year obj val) (vector-set! obj 5 val))
628(define (set-tm:wday obj val) (vector-set! obj 6 val))
629(define (set-tm:yday obj val) (vector-set! obj 7 val))
630(define (set-tm:isdst obj val) (vector-set! obj 8 val))
631(define (set-tm:gmtoff obj val) (vector-set! obj 9 val))
632(define (set-tm:zone obj val) (vector-set! obj 10 val))
633
634(define (tms:clock obj) (vector-ref obj 0))
635(define (tms:utime obj) (vector-ref obj 1))
636(define (tms:stime obj) (vector-ref obj 2))
637(define (tms:cutime obj) (vector-ref obj 3))
638(define (tms:cstime obj) (vector-ref obj 4))
639
640(define (file-position . args) (apply ftell args))
641(define (file-set-position . args) (apply fseek args))
642
643(define (move->fdes fd/port fd)
644 (cond ((integer? fd/port)
645 (dup->fdes fd/port fd)
646 (close fd/port)
647 fd)
648 (else
649 (primitive-move->fdes fd/port fd)
650 (set-port-revealed! fd/port 1)
651 fd/port)))
652
653(define (release-port-handle port)
654 (let ((revealed (port-revealed port)))
655 (if (> revealed 0)
656 (set-port-revealed! port (- revealed 1)))))
657
658(define (dup->port port/fd mode . maybe-fd)
659 (let ((port (fdopen (apply dup->fdes port/fd maybe-fd)
660 mode)))
661 (if (pair? maybe-fd)
662 (set-port-revealed! port 1))
663 port))
664
665(define (dup->inport port/fd . maybe-fd)
666 (apply dup->port port/fd "r" maybe-fd))
667
668(define (dup->outport port/fd . maybe-fd)
669 (apply dup->port port/fd "w" maybe-fd))
670
671(define (dup port/fd . maybe-fd)
672 (if (integer? port/fd)
673 (apply dup->fdes port/fd maybe-fd)
674 (apply dup->port port/fd (port-mode port/fd) maybe-fd)))
675
676(define (duplicate-port port modes)
677 (dup->port port modes))
678
679(define (fdes->inport fdes)
680 (let loop ((rest-ports (fdes->ports fdes)))
681 (cond ((null? rest-ports)
682 (let ((result (fdopen fdes "r")))
683 (set-port-revealed! result 1)
684 result))
685 ((input-port? (car rest-ports))
686 (set-port-revealed! (car rest-ports)
687 (+ (port-revealed (car rest-ports)) 1))
688 (car rest-ports))
689 (else
690 (loop (cdr rest-ports))))))
691
692(define (fdes->outport fdes)
693 (let loop ((rest-ports (fdes->ports fdes)))
694 (cond ((null? rest-ports)
695 (let ((result (fdopen fdes "w")))
696 (set-port-revealed! result 1)
697 result))
698 ((output-port? (car rest-ports))
699 (set-port-revealed! (car rest-ports)
700 (+ (port-revealed (car rest-ports)) 1))
701 (car rest-ports))
702 (else
703 (loop (cdr rest-ports))))))
704
705(define (port->fdes port)
706 (set-port-revealed! port (+ (port-revealed port) 1))
707 (fileno port))
708
709(define (setenv name value)
710 (if value
711 (putenv (string-append name "=" value))
712 (putenv name)))
713
714\f
715;;; {Load Paths}
716;;;
717
718;;; Here for backward compatability
719;;
720(define scheme-file-suffix (lambda () ".scm"))
721
722(define (in-vicinity vicinity file)
723 (let ((tail (let ((len (string-length vicinity)))
724 (if (zero? len)
725 #f
726 (string-ref vicinity (- len 1))))))
727 (string-append vicinity
728 (if (or (not tail)
729 (eq? tail #\/))
730 ""
731 "/")
732 file)))
733
734\f
735;;; {Help for scm_shell}
736;;; The argument-processing code used by Guile-based shells generates
737;;; Scheme code based on the argument list. This page contains help
738;;; functions for the code it generates.
739
740(define (command-line) (program-arguments))
741
742;; This is mostly for the internal use of the code generated by
743;; scm_compile_shell_switches.
744(define (load-user-init)
745 (let* ((home (or (getenv "HOME")
746 (false-if-exception (passwd:dir (getpwuid (getuid))))
747 "/")) ;; fallback for cygwin etc.
748 (init-file (in-vicinity home ".guile")))
749 (if (file-exists? init-file)
750 (primitive-load init-file))))
751
752\f
753;;; {Loading by paths}
754
755;;; Load a Scheme source file named NAME, searching for it in the
756;;; directories listed in %load-path, and applying each of the file
757;;; name extensions listed in %load-extensions.
758(define (load-from-path name)
759 (start-stack 'load-stack
760 (primitive-load-path name)))
761
762
763\f
764;;; {Transcendental Functions}
765;;;
766;;; Derived from "Transcen.scm", Complex trancendental functions for SCM.
767;;; Written by Jerry D. Hedden, (C) FSF.
768;;; See the file `COPYING' for terms applying to this program.
769;;;
770
771(define (exp z)
772 (if (real? z) ($exp z)
773 (make-polar ($exp (real-part z)) (imag-part z))))
774
775(define (log z)
776 (if (and (real? z) (>= z 0))
777 ($log z)
778 (make-rectangular ($log (magnitude z)) (angle z))))
779
780(define (sqrt z)
781 (if (real? z)
782 (if (negative? z) (make-rectangular 0 ($sqrt (- z)))
783 ($sqrt z))
784 (make-polar ($sqrt (magnitude z)) (/ (angle z) 2))))
785
786(define expt
787 (let ((integer-expt integer-expt))
788 (lambda (z1 z2)
789 (cond ((integer? z2)
790 (if (>= z2 0)
791 (integer-expt z1 z2)
792 (/ 1 (integer-expt z1 (- z2)))))
793 ((and (real? z2) (real? z1) (>= z1 0))
794 ($expt z1 z2))
795 (else
796 (exp (* z2 (log z1))))))))
797
798(define (sinh z)
799 (if (real? z) ($sinh z)
800 (let ((x (real-part z)) (y (imag-part z)))
801 (make-rectangular (* ($sinh x) ($cos y))
802 (* ($cosh x) ($sin y))))))
803(define (cosh z)
804 (if (real? z) ($cosh z)
805 (let ((x (real-part z)) (y (imag-part z)))
806 (make-rectangular (* ($cosh x) ($cos y))
807 (* ($sinh x) ($sin y))))))
808(define (tanh z)
809 (if (real? z) ($tanh z)
810 (let* ((x (* 2 (real-part z)))
811 (y (* 2 (imag-part z)))
812 (w (+ ($cosh x) ($cos y))))
813 (make-rectangular (/ ($sinh x) w) (/ ($sin y) w)))))
814
815(define (asinh z)
816 (if (real? z) ($asinh z)
817 (log (+ z (sqrt (+ (* z z) 1))))))
818
819(define (acosh z)
820 (if (and (real? z) (>= z 1))
821 ($acosh z)
822 (log (+ z (sqrt (- (* z z) 1))))))
823
824(define (atanh z)
825 (if (and (real? z) (> z -1) (< z 1))
826 ($atanh z)
827 (/ (log (/ (+ 1 z) (- 1 z))) 2)))
828
829(define (sin z)
830 (if (real? z) ($sin z)
831 (let ((x (real-part z)) (y (imag-part z)))
832 (make-rectangular (* ($sin x) ($cosh y))
833 (* ($cos x) ($sinh y))))))
834(define (cos z)
835 (if (real? z) ($cos z)
836 (let ((x (real-part z)) (y (imag-part z)))
837 (make-rectangular (* ($cos x) ($cosh y))
838 (- (* ($sin x) ($sinh y)))))))
839(define (tan z)
840 (if (real? z) ($tan z)
841 (let* ((x (* 2 (real-part z)))
842 (y (* 2 (imag-part z)))
843 (w (+ ($cos x) ($cosh y))))
844 (make-rectangular (/ ($sin x) w) (/ ($sinh y) w)))))
845
846(define (asin z)
847 (if (and (real? z) (>= z -1) (<= z 1))
848 ($asin z)
849 (* -i (asinh (* +i z)))))
850
851(define (acos z)
852 (if (and (real? z) (>= z -1) (<= z 1))
853 ($acos z)
854 (+ (/ (angle -1) 2) (* +i (asinh (* +i z))))))
855
856(define (atan z . y)
857 (if (null? y)
858 (if (real? z) ($atan z)
859 (/ (log (/ (- +i z) (+ +i z))) +2i))
860 ($atan2 z (car y))))
861
862(define (log10 arg)
863 (/ (log arg) (log 10)))
864
865\f
866
867;;; {Reader Extensions}
868;;;
869
870;;; Reader code for various "#c" forms.
871;;;
872
873(read-hash-extend #\' (lambda (c port)
874 (read port)))
875(read-hash-extend #\. (lambda (c port)
876 (eval (read port) (interaction-environment))))
877
878\f
879;;; {Command Line Options}
880;;;
881
882(define (get-option argv kw-opts kw-args return)
883 (cond
884 ((null? argv)
885 (return #f #f argv))
886
887 ((or (not (eq? #\- (string-ref (car argv) 0)))
888 (eq? (string-length (car argv)) 1))
889 (return 'normal-arg (car argv) (cdr argv)))
890
891 ((eq? #\- (string-ref (car argv) 1))
892 (let* ((kw-arg-pos (or (string-index (car argv) #\=)
893 (string-length (car argv))))
894 (kw (symbol->keyword (substring (car argv) 2 kw-arg-pos)))
895 (kw-opt? (member kw kw-opts))
896 (kw-arg? (member kw kw-args))
897 (arg (or (and (not (eq? kw-arg-pos (string-length (car argv))))
898 (substring (car argv)
899 (+ kw-arg-pos 1)
900 (string-length (car argv))))
901 (and kw-arg?
902 (begin (set! argv (cdr argv)) (car argv))))))
903 (if (or kw-opt? kw-arg?)
904 (return kw arg (cdr argv))
905 (return 'usage-error kw (cdr argv)))))
906
907 (else
908 (let* ((char (substring (car argv) 1 2))
909 (kw (symbol->keyword char)))
910 (cond
911
912 ((member kw kw-opts)
913 (let* ((rest-car (substring (car argv) 2 (string-length (car argv))))
914 (new-argv (if (= 0 (string-length rest-car))
915 (cdr argv)
916 (cons (string-append "-" rest-car) (cdr argv)))))
917 (return kw #f new-argv)))
918
919 ((member kw kw-args)
920 (let* ((rest-car (substring (car argv) 2 (string-length (car argv))))
921 (arg (if (= 0 (string-length rest-car))
922 (cadr argv)
923 rest-car))
924 (new-argv (if (= 0 (string-length rest-car))
925 (cddr argv)
926 (cdr argv))))
927 (return kw arg new-argv)))
928
929 (else (return 'usage-error kw argv)))))))
930
931(define (for-next-option proc argv kw-opts kw-args)
932 (let loop ((argv argv))
933 (get-option argv kw-opts kw-args
934 (lambda (opt opt-arg argv)
935 (and opt (proc opt opt-arg argv loop))))))
936
937(define (display-usage-report kw-desc)
938 (for-each
939 (lambda (kw)
940 (or (eq? (car kw) #t)
941 (eq? (car kw) 'else)
942 (let* ((opt-desc kw)
943 (help (cadr opt-desc))
944 (opts (car opt-desc))
945 (opts-proper (if (string? (car opts)) (cdr opts) opts))
946 (arg-name (if (string? (car opts))
947 (string-append "<" (car opts) ">")
948 ""))
949 (left-part (string-append
950 (with-output-to-string
951 (lambda ()
952 (map (lambda (x) (display (keyword-symbol x)) (display " "))
953 opts-proper)))
954 arg-name))
955 (middle-part (if (and (< (string-length left-part) 30)
956 (< (string-length help) 40))
957 (make-string (- 30 (string-length left-part)) #\ )
958 "\n\t")))
959 (display left-part)
960 (display middle-part)
961 (display help)
962 (newline))))
963 kw-desc))
964
965
966
967(define (transform-usage-lambda cases)
968 (let* ((raw-usage (delq! 'else (map car cases)))
969 (usage-sans-specials (map (lambda (x)
970 (or (and (not (list? x)) x)
971 (and (symbol? (car x)) #t)
972 (and (boolean? (car x)) #t)
973 x))
974 raw-usage))
975 (usage-desc (delq! #t usage-sans-specials))
976 (kw-desc (map car usage-desc))
977 (kw-opts (apply append (map (lambda (x) (and (not (string? (car x))) x)) kw-desc)))
978 (kw-args (apply append (map (lambda (x) (and (string? (car x)) (cdr x))) kw-desc)))
979 (transmogrified-cases (map (lambda (case)
980 (cons (let ((opts (car case)))
981 (if (or (boolean? opts) (eq? 'else opts))
982 opts
983 (cond
984 ((symbol? (car opts)) opts)
985 ((boolean? (car opts)) opts)
986 ((string? (caar opts)) (cdar opts))
987 (else (car opts)))))
988 (cdr case)))
989 cases)))
990 `(let ((%display-usage (lambda () (display-usage-report ',usage-desc))))
991 (lambda (%argv)
992 (let %next-arg ((%argv %argv))
993 (get-option %argv
994 ',kw-opts
995 ',kw-args
996 (lambda (%opt %arg %new-argv)
997 (case %opt
998 ,@ transmogrified-cases))))))))
999
1000
1001\f
1002
1003;;; {Low Level Modules}
1004;;;
1005;;; These are the low level data structures for modules.
1006;;;
1007;;; !!! warning: The interface to lazy binder procedures is going
1008;;; to be changed in an incompatible way to permit all the basic
1009;;; module ops to be virtualized.
1010;;;
1011;;; (make-module size use-list lazy-binding-proc) => module
1012;;; module-{obarray,uses,binder}[|-set!]
1013;;; (module? obj) => [#t|#f]
1014;;; (module-locally-bound? module symbol) => [#t|#f]
1015;;; (module-bound? module symbol) => [#t|#f]
1016;;; (module-symbol-locally-interned? module symbol) => [#t|#f]
1017;;; (module-symbol-interned? module symbol) => [#t|#f]
1018;;; (module-local-variable module symbol) => [#<variable ...> | #f]
1019;;; (module-variable module symbol) => [#<variable ...> | #f]
1020;;; (module-symbol-binding module symbol opt-value)
1021;;; => [ <obj> | opt-value | an error occurs ]
1022;;; (module-make-local-var! module symbol) => #<variable...>
1023;;; (module-add! module symbol var) => unspecified
1024;;; (module-remove! module symbol) => unspecified
1025;;; (module-for-each proc module) => unspecified
1026;;; (make-scm-module) => module ; a lazy copy of the symhash module
1027;;; (set-current-module module) => unspecified
1028;;; (current-module) => #<module...>
1029;;;
1030;;;
1031
1032\f
1033;;; {Printing Modules}
1034;; This is how modules are printed. You can re-define it.
1035;; (Redefining is actually more complicated than simply redefining
1036;; %print-module because that would only change the binding and not
1037;; the value stored in the vtable that determines how record are
1038;; printed. Sigh.)
1039
1040(define (%print-module mod port) ; unused args: depth length style table)
1041 (display "#<" port)
1042 (display (or (module-kind mod) "module") port)
1043 (let ((name (module-name mod)))
1044 (if name
1045 (begin
1046 (display " " port)
1047 (display name port))))
1048 (display " " port)
1049 (display (number->string (object-address mod) 16) port)
1050 (display ">" port))
1051
1052;; module-type
1053;;
1054;; A module is characterized by an obarray in which local symbols
1055;; are interned, a list of modules, "uses", from which non-local
1056;; bindings can be inherited, and an optional lazy-binder which
1057;; is a (CLOSURE module symbol) which, as a last resort, can provide
1058;; bindings that would otherwise not be found locally in the module.
1059;;
1060;; NOTE: If you change here, you also need to change libguile/modules.h.
1061;;
1062(define module-type
1063 (make-record-type 'module
1064 '(obarray uses binder eval-closure transformer name kind
1065 observers weak-observers observer-id)
1066 %print-module))
1067
1068;; make-module &opt size uses binder
1069;;
1070;; Create a new module, perhaps with a particular size of obarray,
1071;; initial uses list, or binding procedure.
1072;;
1073(define make-module
1074 (lambda args
1075
1076 (define (parse-arg index default)
1077 (if (> (length args) index)
1078 (list-ref args index)
1079 default))
1080
1081 (if (> (length args) 3)
1082 (error "Too many args to make-module." args))
1083
1084 (let ((size (parse-arg 0 1021))
1085 (uses (parse-arg 1 '()))
1086 (binder (parse-arg 2 #f)))
1087
1088 (if (not (integer? size))
1089 (error "Illegal size to make-module." size))
1090 (if (not (and (list? uses)
1091 (and-map module? uses)))
1092 (error "Incorrect use list." uses))
1093 (if (and binder (not (procedure? binder)))
1094 (error
1095 "Lazy-binder expected to be a procedure or #f." binder))
1096
1097 (let ((module (module-constructor (make-vector size '())
1098 uses binder #f #f #f #f
1099 '()
1100 (make-weak-value-hash-table 31)
1101 0)))
1102
1103 ;; We can't pass this as an argument to module-constructor,
1104 ;; because we need it to close over a pointer to the module
1105 ;; itself.
1106 (set-module-eval-closure! module (standard-eval-closure module))
1107
1108 module))))
1109
1110(define module-constructor (record-constructor module-type))
1111(define module-obarray (record-accessor module-type 'obarray))
1112(define set-module-obarray! (record-modifier module-type 'obarray))
1113(define module-uses (record-accessor module-type 'uses))
1114(define set-module-uses! (record-modifier module-type 'uses))
1115(define module-binder (record-accessor module-type 'binder))
1116(define set-module-binder! (record-modifier module-type 'binder))
1117
1118;; NOTE: This binding is used in libguile/modules.c.
1119(define module-eval-closure (record-accessor module-type 'eval-closure))
1120
1121(define module-transformer (record-accessor module-type 'transformer))
1122(define set-module-transformer! (record-modifier module-type 'transformer))
1123(define module-name (record-accessor module-type 'name))
1124(define set-module-name! (record-modifier module-type 'name))
1125(define module-kind (record-accessor module-type 'kind))
1126(define set-module-kind! (record-modifier module-type 'kind))
1127(define module-observers (record-accessor module-type 'observers))
1128(define set-module-observers! (record-modifier module-type 'observers))
1129(define module-weak-observers (record-accessor module-type 'weak-observers))
1130(define module-observer-id (record-accessor module-type 'observer-id))
1131(define set-module-observer-id! (record-modifier module-type 'observer-id))
1132(define module? (record-predicate module-type))
1133
1134(define set-module-eval-closure!
1135 (let ((setter (record-modifier module-type 'eval-closure)))
1136 (lambda (module closure)
1137 (setter module closure)
1138 ;; Make it possible to lookup the module from the environment.
1139 ;; This implementation is correct since an eval closure can belong
1140 ;; to maximally one module.
1141 (set-procedure-property! closure 'module module))))
1142
1143;;; This procedure is depreated
1144;;;
1145(define eval-in-module eval)
1146
1147\f
1148;;; {Observer protocol}
1149;;;
1150
1151(define (module-observe module proc)
1152 (set-module-observers! module (cons proc (module-observers module)))
1153 (cons module proc))
1154
1155(define (module-observe-weak module proc)
1156 (let ((id (module-observer-id module)))
1157 (hash-set! (module-weak-observers module) id proc)
1158 (set-module-observer-id! module (+ 1 id))
1159 (cons module id)))
1160
1161(define (module-unobserve token)
1162 (let ((module (car token))
1163 (id (cdr token)))
1164 (if (integer? id)
1165 (hash-remove! (module-weak-observers module) id)
1166 (set-module-observers! module (delq1! id (module-observers module)))))
1167 *unspecified*)
1168
1169(define (module-modified m)
1170 (for-each (lambda (proc) (proc m)) (module-observers m))
1171 (hash-fold (lambda (id proc res) (proc m)) #f (module-weak-observers m)))
1172
1173\f
1174;;; {Module Searching in General}
1175;;;
1176;;; We sometimes want to look for properties of a symbol
1177;;; just within the obarray of one module. If the property
1178;;; holds, then it is said to hold ``locally'' as in, ``The symbol
1179;;; DISPLAY is locally rebound in the module `safe-guile'.''
1180;;;
1181;;;
1182;;; Other times, we want to test for a symbol property in the obarray
1183;;; of M and, if it is not found there, try each of the modules in the
1184;;; uses list of M. This is the normal way of testing for some
1185;;; property, so we state these properties without qualification as
1186;;; in: ``The symbol 'fnord is interned in module M because it is
1187;;; interned locally in module M2 which is a member of the uses list
1188;;; of M.''
1189;;;
1190
1191;; module-search fn m
1192;;
1193;; return the first non-#f result of FN applied to M and then to
1194;; the modules in the uses of m, and so on recursively. If all applications
1195;; return #f, then so does this function.
1196;;
1197(define (module-search fn m v)
1198 (define (loop pos)
1199 (and (pair? pos)
1200 (or (module-search fn (car pos) v)
1201 (loop (cdr pos)))))
1202 (or (fn m v)
1203 (loop (module-uses m))))
1204
1205
1206;;; {Is a symbol bound in a module?}
1207;;;
1208;;; Symbol S in Module M is bound if S is interned in M and if the binding
1209;;; of S in M has been set to some well-defined value.
1210;;;
1211
1212;; module-locally-bound? module symbol
1213;;
1214;; Is a symbol bound (interned and defined) locally in a given module?
1215;;
1216(define (module-locally-bound? m v)
1217 (let ((var (module-local-variable m v)))
1218 (and var
1219 (variable-bound? var))))
1220
1221;; module-bound? module symbol
1222;;
1223;; Is a symbol bound (interned and defined) anywhere in a given module
1224;; or its uses?
1225;;
1226(define (module-bound? m v)
1227 (module-search module-locally-bound? m v))
1228
1229;;; {Is a symbol interned in a module?}
1230;;;
1231;;; Symbol S in Module M is interned if S occurs in
1232;;; of S in M has been set to some well-defined value.
1233;;;
1234;;; It is possible to intern a symbol in a module without providing
1235;;; an initial binding for the corresponding variable. This is done
1236;;; with:
1237;;; (module-add! module symbol (make-undefined-variable))
1238;;;
1239;;; In that case, the symbol is interned in the module, but not
1240;;; bound there. The unbound symbol shadows any binding for that
1241;;; symbol that might otherwise be inherited from a member of the uses list.
1242;;;
1243
1244(define (module-obarray-get-handle ob key)
1245 ((if (symbol? key) hashq-get-handle hash-get-handle) ob key))
1246
1247(define (module-obarray-ref ob key)
1248 ((if (symbol? key) hashq-ref hash-ref) ob key))
1249
1250(define (module-obarray-set! ob key val)
1251 ((if (symbol? key) hashq-set! hash-set!) ob key val))
1252
1253(define (module-obarray-remove! ob key)
1254 ((if (symbol? key) hashq-remove! hash-remove!) ob key))
1255
1256;; module-symbol-locally-interned? module symbol
1257;;
1258;; is a symbol interned (not neccessarily defined) locally in a given module
1259;; or its uses? Interned symbols shadow inherited bindings even if
1260;; they are not themselves bound to a defined value.
1261;;
1262(define (module-symbol-locally-interned? m v)
1263 (not (not (module-obarray-get-handle (module-obarray m) v))))
1264
1265;; module-symbol-interned? module symbol
1266;;
1267;; is a symbol interned (not neccessarily defined) anywhere in a given module
1268;; or its uses? Interned symbols shadow inherited bindings even if
1269;; they are not themselves bound to a defined value.
1270;;
1271(define (module-symbol-interned? m v)
1272 (module-search module-symbol-locally-interned? m v))
1273
1274
1275;;; {Mapping modules x symbols --> variables}
1276;;;
1277
1278;; module-local-variable module symbol
1279;; return the local variable associated with a MODULE and SYMBOL.
1280;;
1281;;; This function is very important. It is the only function that can
1282;;; return a variable from a module other than the mutators that store
1283;;; new variables in modules. Therefore, this function is the location
1284;;; of the "lazy binder" hack.
1285;;;
1286;;; If symbol is defined in MODULE, and if the definition binds symbol
1287;;; to a variable, return that variable object.
1288;;;
1289;;; If the symbols is not found at first, but the module has a lazy binder,
1290;;; then try the binder.
1291;;;
1292;;; If the symbol is not found at all, return #f.
1293;;;
1294(define (module-local-variable m v)
1295; (caddr
1296; (list m v
1297 (let ((b (module-obarray-ref (module-obarray m) v)))
1298 (or (and (variable? b) b)
1299 (and (module-binder m)
1300 ((module-binder m) m v #f)))))
1301;))
1302
1303;; module-variable module symbol
1304;;
1305;; like module-local-variable, except search the uses in the
1306;; case V is not found in M.
1307;;
1308;; NOTE: This function is superseded with C code (see modules.c)
1309;;; when using the standard eval closure.
1310;;
1311(define (module-variable m v)
1312 (module-search module-local-variable m v))
1313
1314
1315;;; {Mapping modules x symbols --> bindings}
1316;;;
1317;;; These are similar to the mapping to variables, except that the
1318;;; variable is dereferenced.
1319;;;
1320
1321;; module-symbol-binding module symbol opt-value
1322;;
1323;; return the binding of a variable specified by name within
1324;; a given module, signalling an error if the variable is unbound.
1325;; If the OPT-VALUE is passed, then instead of signalling an error,
1326;; return OPT-VALUE.
1327;;
1328(define (module-symbol-local-binding m v . opt-val)
1329 (let ((var (module-local-variable m v)))
1330 (if var
1331 (variable-ref var)
1332 (if (not (null? opt-val))
1333 (car opt-val)
1334 (error "Locally unbound variable." v)))))
1335
1336;; module-symbol-binding module symbol opt-value
1337;;
1338;; return the binding of a variable specified by name within
1339;; a given module, signalling an error if the variable is unbound.
1340;; If the OPT-VALUE is passed, then instead of signalling an error,
1341;; return OPT-VALUE.
1342;;
1343(define (module-symbol-binding m v . opt-val)
1344 (let ((var (module-variable m v)))
1345 (if var
1346 (variable-ref var)
1347 (if (not (null? opt-val))
1348 (car opt-val)
1349 (error "Unbound variable." v)))))
1350
1351
1352\f
1353;;; {Adding Variables to Modules}
1354;;;
1355;;;
1356
1357
1358;; module-make-local-var! module symbol
1359;;
1360;; ensure a variable for V in the local namespace of M.
1361;; If no variable was already there, then create a new and uninitialzied
1362;; variable.
1363;;
1364(define (module-make-local-var! m v)
1365 (or (let ((b (module-obarray-ref (module-obarray m) v)))
1366 (and (variable? b)
1367 (begin
1368 (module-modified m)
1369 b)))
1370 (and (module-binder m)
1371 ((module-binder m) m v #t))
1372 (begin
1373 (let ((answer (make-undefined-variable v)))
1374 (module-obarray-set! (module-obarray m) v answer)
1375 (module-modified m)
1376 answer))))
1377
1378;; module-add! module symbol var
1379;;
1380;; ensure a particular variable for V in the local namespace of M.
1381;;
1382(define (module-add! m v var)
1383 (if (not (variable? var))
1384 (error "Bad variable to module-add!" var))
1385 (module-obarray-set! (module-obarray m) v var)
1386 (module-modified m))
1387
1388;; module-remove!
1389;;
1390;; make sure that a symbol is undefined in the local namespace of M.
1391;;
1392(define (module-remove! m v)
1393 (module-obarray-remove! (module-obarray m) v)
1394 (module-modified m))
1395
1396(define (module-clear! m)
1397 (vector-fill! (module-obarray m) '())
1398 (module-modified m))
1399
1400;; MODULE-FOR-EACH -- exported
1401;;
1402;; Call PROC on each symbol in MODULE, with arguments of (SYMBOL VARIABLE).
1403;;
1404(define (module-for-each proc module)
1405 (let ((obarray (module-obarray module)))
1406 (do ((index 0 (+ index 1))
1407 (end (vector-length obarray)))
1408 ((= index end))
1409 (for-each
1410 (lambda (bucket)
1411 (proc (car bucket) (cdr bucket)))
1412 (vector-ref obarray index)))))
1413
1414
1415(define (module-map proc module)
1416 (let* ((obarray (module-obarray module))
1417 (end (vector-length obarray)))
1418
1419 (let loop ((i 0)
1420 (answer '()))
1421 (if (= i end)
1422 answer
1423 (loop (+ 1 i)
1424 (append!
1425 (map (lambda (bucket)
1426 (proc (car bucket) (cdr bucket)))
1427 (vector-ref obarray i))
1428 answer))))))
1429\f
1430
1431;;; {Low Level Bootstrapping}
1432;;;
1433
1434;; make-root-module
1435
1436;; A root module uses the symhash table (the system's privileged
1437;; obarray). Being inside a root module is like using SCM without
1438;; any module system.
1439;;
1440
1441
1442(define (root-module-closure m s define?)
1443 (let ((bi (and (symbol-interned? #f s)
1444 (builtin-variable s))))
1445 (and bi
1446 (or define? (variable-bound? bi))
1447 (begin
1448 (module-add! m s bi)
1449 bi))))
1450
1451(define (make-root-module)
1452 (make-module 1019 '() root-module-closure))
1453
1454
1455;; make-scm-module
1456
1457;; An scm module is a module into which the lazy binder copies
1458;; variable bindings from the system symhash table. The mapping is
1459;; one way only; newly introduced bindings in an scm module are not
1460;; copied back into the system symhash table (and can be used to override
1461;; bindings from the symhash table).
1462;;
1463
1464(define (scm-module-closure m s define?)
1465 (let ((bi (and (symbol-interned? #f s)
1466 (builtin-variable s))))
1467 (and bi
1468 (variable-bound? bi)
1469 (begin
1470 (module-add! m s bi)
1471 bi))))
1472
1473(define (make-scm-module)
1474 (make-module 1019 '() scm-module-closure))
1475
1476
1477
1478;; the-module
1479;;
1480;; NOTE: This binding is used in libguile/modules.c.
1481;;
1482(define the-module (make-fluid))
1483
1484;; scm:eval-transformer
1485;;
1486;;(define scm:eval-transformer (make-fluid)) ; initialized in eval.c.
1487
1488;; set-current-module module
1489;;
1490;; set the current module as viewed by the normalizer.
1491;;
1492;; NOTE: This binding is used in libguile/modules.c.
1493;;
1494(define (set-current-module m)
1495 (fluid-set! the-module m)
1496 (if m
1497 (begin
1498 ;; *top-level-lookup-closure* is now deprecated
1499 (fluid-set! *top-level-lookup-closure*
1500 (module-eval-closure (fluid-ref the-module)))
1501 (fluid-set! scm:eval-transformer (module-transformer (fluid-ref the-module))))
1502 (fluid-set! *top-level-lookup-closure* #f)))
1503
1504
1505;; current-module
1506;;
1507;; return the current module as viewed by the normalizer.
1508;;
1509(define (current-module) (fluid-ref the-module))
1510\f
1511;;; {Module-based Loading}
1512;;;
1513
1514(define (save-module-excursion thunk)
1515 (let ((inner-module (current-module))
1516 (outer-module #f))
1517 (dynamic-wind (lambda ()
1518 (set! outer-module (current-module))
1519 (set-current-module inner-module)
1520 (set! inner-module #f))
1521 thunk
1522 (lambda ()
1523 (set! inner-module (current-module))
1524 (set-current-module outer-module)
1525 (set! outer-module #f)))))
1526
1527(define basic-load load)
1528
1529(define (load-module filename)
1530 (save-module-excursion
1531 (lambda ()
1532 (let ((oldname (and (current-load-port)
1533 (port-filename (current-load-port)))))
1534 (basic-load (if (and oldname
1535 (> (string-length filename) 0)
1536 (not (char=? (string-ref filename 0) #\/))
1537 (not (string=? (dirname oldname) ".")))
1538 (string-append (dirname oldname) "/" filename)
1539 filename))))))
1540
1541
1542\f
1543;;; {MODULE-REF -- exported}
1544;;
1545;; Returns the value of a variable called NAME in MODULE or any of its
1546;; used modules. If there is no such variable, then if the optional third
1547;; argument DEFAULT is present, it is returned; otherwise an error is signaled.
1548;;
1549(define (module-ref module name . rest)
1550 (let ((variable (module-variable module name)))
1551 (if (and variable (variable-bound? variable))
1552 (variable-ref variable)
1553 (if (null? rest)
1554 (error "No variable named" name 'in module)
1555 (car rest) ; default value
1556 ))))
1557
1558;; MODULE-SET! -- exported
1559;;
1560;; Sets the variable called NAME in MODULE (or in a module that MODULE uses)
1561;; to VALUE; if there is no such variable, an error is signaled.
1562;;
1563(define (module-set! module name value)
1564 (let ((variable (module-variable module name)))
1565 (if variable
1566 (variable-set! variable value)
1567 (error "No variable named" name 'in module))))
1568
1569;; MODULE-DEFINE! -- exported
1570;;
1571;; Sets the variable called NAME in MODULE to VALUE; if there is no such
1572;; variable, it is added first.
1573;;
1574(define (module-define! module name value)
1575 (let ((variable (module-local-variable module name)))
1576 (if variable
1577 (begin
1578 (variable-set! variable value)
1579 (module-modified module))
1580 (module-add! module name (make-variable value name)))))
1581
1582;; MODULE-DEFINED? -- exported
1583;;
1584;; Return #t iff NAME is defined in MODULE (or in a module that MODULE
1585;; uses)
1586;;
1587(define (module-defined? module name)
1588 (let ((variable (module-variable module name)))
1589 (and variable (variable-bound? variable))))
1590
1591;; MODULE-USE! module interface
1592;;
1593;; Add INTERFACE to the list of interfaces used by MODULE.
1594;;
1595(define (module-use! module interface)
1596 (set-module-uses! module
1597 (cons interface (delq! interface (module-uses module))))
1598 (module-modified module))
1599
1600\f
1601;;; {Recursive Namespaces}
1602;;;
1603;;;
1604;;; A hierarchical namespace emerges if we consider some module to be
1605;;; root, and variables bound to modules as nested namespaces.
1606;;;
1607;;; The routines in this file manage variable names in hierarchical namespace.
1608;;; Each variable name is a list of elements, looked up in successively nested
1609;;; modules.
1610;;;
1611;;; (nested-ref some-root-module '(foo bar baz))
1612;;; => <value of a variable named baz in the module bound to bar in
1613;;; the module bound to foo in some-root-module>
1614;;;
1615;;;
1616;;; There are:
1617;;;
1618;;; ;; a-root is a module
1619;;; ;; name is a list of symbols
1620;;;
1621;;; nested-ref a-root name
1622;;; nested-set! a-root name val
1623;;; nested-define! a-root name val
1624;;; nested-remove! a-root name
1625;;;
1626;;;
1627;;; (current-module) is a natural choice for a-root so for convenience there are
1628;;; also:
1629;;;
1630;;; local-ref name == nested-ref (current-module) name
1631;;; local-set! name val == nested-set! (current-module) name val
1632;;; local-define! name val == nested-define! (current-module) name val
1633;;; local-remove! name == nested-remove! (current-module) name
1634;;;
1635
1636
1637(define (nested-ref root names)
1638 (let loop ((cur root)
1639 (elts names))
1640 (cond
1641 ((null? elts) cur)
1642 ((not (module? cur)) #f)
1643 (else (loop (module-ref cur (car elts) #f) (cdr elts))))))
1644
1645(define (nested-set! root names val)
1646 (let loop ((cur root)
1647 (elts names))
1648 (if (null? (cdr elts))
1649 (module-set! cur (car elts) val)
1650 (loop (module-ref cur (car elts)) (cdr elts)))))
1651
1652(define (nested-define! root names val)
1653 (let loop ((cur root)
1654 (elts names))
1655 (if (null? (cdr elts))
1656 (module-define! cur (car elts) val)
1657 (loop (module-ref cur (car elts)) (cdr elts)))))
1658
1659(define (nested-remove! root names)
1660 (let loop ((cur root)
1661 (elts names))
1662 (if (null? (cdr elts))
1663 (module-remove! cur (car elts))
1664 (loop (module-ref cur (car elts)) (cdr elts)))))
1665
1666(define (local-ref names) (nested-ref (current-module) names))
1667(define (local-set! names val) (nested-set! (current-module) names val))
1668(define (local-define names val) (nested-define! (current-module) names val))
1669(define (local-remove names) (nested-remove! (current-module) names))
1670
1671
1672\f
1673;;; {The (app) module}
1674;;;
1675;;; The root of conventionally named objects not directly in the top level.
1676;;;
1677;;; (app modules)
1678;;; (app modules guile)
1679;;;
1680;;; The directory of all modules and the standard root module.
1681;;;
1682
1683(define (module-public-interface m)
1684 (module-ref m '%module-public-interface #f))
1685(define (set-module-public-interface! m i)
1686 (module-define! m '%module-public-interface i))
1687(define (set-system-module! m s)
1688 (set-procedure-property! (module-eval-closure m) 'system-module s))
1689(define the-root-module (make-root-module))
1690(define the-scm-module (make-scm-module))
1691(set-module-public-interface! the-root-module the-scm-module)
1692(set-module-name! the-root-module '(guile))
1693(set-module-name! the-scm-module '(guile))
1694(set-module-kind! the-scm-module 'interface)
1695(for-each set-system-module! (list the-root-module the-scm-module) '(#t #t))
1696
1697(set-current-module the-root-module)
1698
1699(define app (make-module 31))
1700(local-define '(app modules) (make-module 31))
1701(local-define '(app modules guile) the-root-module)
1702
1703;; (define-special-value '(app modules new-ws) (lambda () (make-scm-module)))
1704
1705(define (try-load-module name)
1706 (or (try-module-linked name)
1707 (try-module-autoload name)
1708 (try-module-dynamic-link name)))
1709
1710;; NOTE: This binding is used in libguile/modules.c.
1711;;
1712(define (resolve-module name . maybe-autoload)
1713 (let ((full-name (append '(app modules) name)))
1714 (let ((already (local-ref full-name)))
1715 (if already
1716 ;; The module already exists...
1717 (if (and (or (null? maybe-autoload) (car maybe-autoload))
1718 (not (module-ref already '%module-public-interface #f)))
1719 ;; ...but we are told to load and it doesn't contain source, so
1720 (begin
1721 (try-load-module name)
1722 already)
1723 ;; simply return it.
1724 already)
1725 (begin
1726 ;; Try to autoload it if we are told so
1727 (if (or (null? maybe-autoload) (car maybe-autoload))
1728 (try-load-module name))
1729 ;; Get/create it.
1730 (make-modules-in (current-module) full-name))))))
1731
1732(define (beautify-user-module! module)
1733 (let ((interface (module-public-interface module)))
1734 (if (or (not interface)
1735 (eq? interface module))
1736 (let ((interface (make-module 31)))
1737 (set-module-name! interface (module-name module))
1738 (set-module-kind! interface 'interface)
1739 (set-module-public-interface! module interface))))
1740 (if (and (not (memq the-scm-module (module-uses module)))
1741 (not (eq? module the-root-module)))
1742 (set-module-uses! module (append (module-uses module) (list the-scm-module)))))
1743
1744(define (purify-module! module)
1745 "Removes bindings in MODULE which are inherited from the (guile) module."
1746 (let ((use-list (module-uses module)))
1747 (if (and (pair? use-list)
1748 (eq? (car (last-pair use-list)) the-scm-module))
1749 (set-module-uses! module (reverse (cdr (reverse use-list)))))))
1750
1751;; NOTE: This binding is used in libguile/modules.c.
1752;;
1753(define (make-modules-in module name)
1754 (if (null? name)
1755 module
1756 (cond
1757 ((module-ref module (car name) #f)
1758 => (lambda (m) (make-modules-in m (cdr name))))
1759 (else (let ((m (make-module 31)))
1760 (set-module-kind! m 'directory)
1761 (set-module-name! m (append (or (module-name module)
1762 '())
1763 (list (car name))))
1764 (module-define! module (car name) m)
1765 (make-modules-in m (cdr name)))))))
1766
1767(define (resolve-interface name)
1768 (let ((module (resolve-module name)))
1769 (and module (module-public-interface module))))
1770
1771
1772(define %autoloader-developer-mode #t)
1773
1774(define (process-define-module args)
1775 (let* ((module-id (car args))
1776 (module (resolve-module module-id #f))
1777 (kws (cdr args)))
1778 (beautify-user-module! module)
1779 (let loop ((kws kws)
1780 (reversed-interfaces '())
1781 (exports '()))
1782 (if (null? kws)
1783 (begin
1784 (for-each (lambda (interface)
1785 (module-use! module interface))
1786 reversed-interfaces)
1787 (module-export! module exports))
1788 (let ((keyword (if (keyword? (car kws))
1789 (keyword->symbol (car kws))
1790 (and (symbol? (car kws))
1791 (let ((s (symbol->string (car kws))))
1792 (and (eq? (string-ref s 0) #\:)
1793 (string->symbol (substring s 1))))))))
1794 (case keyword
1795 ((use-module use-syntax)
1796 (if (not (pair? (cdr kws)))
1797 (error "unrecognized defmodule argument" kws))
1798 (let* ((used-name (cadr kws))
1799 (used-module (resolve-module used-name)))
1800 (if (not (module-ref used-module
1801 '%module-public-interface
1802 #f))
1803 (begin
1804 ((if %autoloader-developer-mode warn error)
1805 "no code for module" (module-name used-module))
1806 (beautify-user-module! used-module)))
1807 (let ((interface (module-public-interface used-module)))
1808 (if (not interface)
1809 (error "missing interface for use-module"
1810 used-module))
1811 (if (eq? keyword 'use-syntax)
1812 (set-module-transformer!
1813 module
1814 (module-ref interface (car (last-pair used-name))
1815 #f)))
1816 (loop (cddr kws)
1817 (cons interface reversed-interfaces)
1818 exports))))
1819 ((autoload)
1820 (if (not (and (pair? (cdr kws)) (pair? (cddr kws))))
1821 (error "unrecognized defmodule argument" kws))
1822 (loop (cdddr kws)
1823 (cons (make-autoload-interface module
1824 (cadr kws)
1825 (caddr kws))
1826 reversed-interfaces)
1827 exports))
1828 ((no-backtrace)
1829 (set-system-module! module #t)
1830 (loop (cdr kws) reversed-interfaces exports))
1831 ((pure)
1832 (purify-module! module)
1833 (loop (cdr kws) reversed-interfaces exports))
1834 ((export)
1835 (if (not (pair? (cdr kws)))
1836 (error "unrecognized defmodule argument" kws))
1837 (loop (cddr kws)
1838 reversed-interfaces
1839 (append (cadr kws) exports)))
1840 (else
1841 (error "unrecognized defmodule argument" kws))))))
1842 module))
1843
1844;;; {Autoload}
1845
1846(define (make-autoload-interface module name bindings)
1847 (let ((b (lambda (a sym definep)
1848 (and (memq sym bindings)
1849 (let ((i (module-public-interface (resolve-module name))))
1850 (if (not i)
1851 (error "missing interface for module" name))
1852 ;; Replace autoload-interface with interface
1853 (set-car! (memq a (module-uses module)) i)
1854 (module-local-variable i sym))))))
1855 (module-constructor #() '() b #f #f name 'autoload
1856 '() (make-weak-value-hash-table 31) 0)))
1857
1858\f
1859;;; {Autoloading modules}
1860
1861(define autoloads-in-progress '())
1862
1863(define (try-module-autoload module-name)
1864 (let* ((reverse-name (reverse module-name))
1865 (name (symbol->string (car reverse-name)))
1866 (dir-hint-module-name (reverse (cdr reverse-name)))
1867 (dir-hint (apply string-append
1868 (map (lambda (elt)
1869 (string-append (symbol->string elt) "/"))
1870 dir-hint-module-name))))
1871 (resolve-module dir-hint-module-name #f)
1872 (and (not (autoload-done-or-in-progress? dir-hint name))
1873 (let ((didit #f))
1874 (dynamic-wind
1875 (lambda () (autoload-in-progress! dir-hint name))
1876 (lambda ()
1877 (let ((full (%search-load-path (in-vicinity dir-hint name))))
1878 (if full
1879 (begin
1880 (save-module-excursion (lambda () (primitive-load full)))
1881 (set! didit #t)))))
1882 (lambda () (set-autoloaded! dir-hint name didit)))
1883 didit))))
1884
1885\f
1886;;; Dynamic linking of modules
1887
1888;; Initializing a module that is written in C is a two step process.
1889;; First the module's `module init' function is called. This function
1890;; is expected to call `scm_register_module_xxx' to register the `real
1891;; init' function. Later, when the module is referenced for the first
1892;; time, this real init function is called in the right context. See
1893;; gtcltk-lib/gtcltk-module.c for an example.
1894;;
1895;; The code for the module can be in a regular shared library (so that
1896;; the `module init' function will be called when libguile is
1897;; initialized). Or it can be dynamically linked.
1898;;
1899;; You can safely call `scm_register_module_xxx' before libguile
1900;; itself is initialized. You could call it from an C++ constructor
1901;; of a static object, for example.
1902;;
1903;; To make your Guile extension into a dynamic linkable module, follow
1904;; these easy steps:
1905;;
1906;; - Find a name for your module, like (ice-9 gtcltk)
1907;; - Write a function with a name like
1908;;
1909;; scm_init_ice_9_gtcltk_module
1910;;
1911;; This is your `module init' function. It should call
1912;;
1913;; scm_register_module_xxx ("ice-9 gtcltk", scm_init_gtcltk);
1914;;
1915;; "ice-9 gtcltk" is the C version of the module name. Slashes are
1916;; replaced by spaces, the rest is untouched. `scm_init_gtcltk' is
1917;; the real init function that executes the usual initializations
1918;; like making new smobs, etc.
1919;;
1920;; - Make a shared library with your code and a name like
1921;;
1922;; ice-9/libgtcltk.so
1923;;
1924;; and put it somewhere in %load-path.
1925;;
1926;; - Then you can simply write `:use-module (ice-9 gtcltk)' and it
1927;; will be linked automatically.
1928;;
1929;; This is all very experimental.
1930
1931(define (split-c-module-name str)
1932 (let loop ((rev '())
1933 (start 0)
1934 (pos 0)
1935 (end (string-length str)))
1936 (cond
1937 ((= pos end)
1938 (reverse (cons (string->symbol (substring str start pos)) rev)))
1939 ((eq? (string-ref str pos) #\space)
1940 (loop (cons (string->symbol (substring str start pos)) rev)
1941 (+ pos 1)
1942 (+ pos 1)
1943 end))
1944 (else
1945 (loop rev start (+ pos 1) end)))))
1946
1947(define (convert-c-registered-modules dynobj)
1948 (let ((res (map (lambda (c)
1949 (list (split-c-module-name (car c)) (cdr c) dynobj))
1950 (c-registered-modules))))
1951 (c-clear-registered-modules)
1952 res))
1953
1954(define registered-modules '())
1955
1956(define (register-modules dynobj)
1957 (set! registered-modules
1958 (append! (convert-c-registered-modules dynobj)
1959 registered-modules)))
1960
1961(define (init-dynamic-module modname)
1962 ;; Register any linked modules which has been registered on the C level
1963 (register-modules #f)
1964 (or-map (lambda (modinfo)
1965 (if (equal? (car modinfo) modname)
1966 (begin
1967 (set! registered-modules (delq! modinfo registered-modules))
1968 (let ((mod (resolve-module modname #f)))
1969 (save-module-excursion
1970 (lambda ()
1971 (set-current-module mod)
1972 (set-module-public-interface! mod mod)
1973 (dynamic-call (cadr modinfo) (caddr modinfo))
1974 ))
1975 #t))
1976 #f))
1977 registered-modules))
1978
1979(define (dynamic-maybe-call name dynobj)
1980 (catch #t ; could use false-if-exception here
1981 (lambda ()
1982 (dynamic-call name dynobj))
1983 (lambda args
1984 #f)))
1985
1986(define (dynamic-maybe-link filename)
1987 (catch #t ; could use false-if-exception here
1988 (lambda ()
1989 (dynamic-link filename))
1990 (lambda args
1991 #f)))
1992
1993(define (find-and-link-dynamic-module module-name)
1994 (define (make-init-name mod-name)
1995 (string-append "scm_init"
1996 (list->string (map (lambda (c)
1997 (if (or (char-alphabetic? c)
1998 (char-numeric? c))
1999 c
2000 #\_))
2001 (string->list mod-name)))
2002 "_module"))
2003
2004 ;; Put the subdirectory for this module in the car of SUBDIR-AND-LIBNAME,
2005 ;; and the `libname' (the name of the module prepended by `lib') in the cdr
2006 ;; field. For example, if MODULE-NAME is the list (inet tcp-ip udp), then
2007 ;; SUBDIR-AND-LIBNAME will be the pair ("inet/tcp-ip" . "libudp").
2008 (let ((subdir-and-libname
2009 (let loop ((dirs "")
2010 (syms module-name))
2011 (if (null? (cdr syms))
2012 (cons dirs (string-append "lib" (symbol->string (car syms))))
2013 (loop (string-append dirs (symbol->string (car syms)) "/")
2014 (cdr syms)))))
2015 (init (make-init-name (apply string-append
2016 (map (lambda (s)
2017 (string-append "_"
2018 (symbol->string s)))
2019 module-name)))))
2020 (let ((subdir (car subdir-and-libname))
2021 (libname (cdr subdir-and-libname)))
2022
2023 ;; Now look in each dir in %LOAD-PATH for `subdir/libfoo.la'. If that
2024 ;; file exists, fetch the dlname from that file and attempt to link
2025 ;; against it. If `subdir/libfoo.la' does not exist, or does not seem
2026 ;; to name any shared library, look for `subdir/libfoo.so' instead and
2027 ;; link against that.
2028 (let check-dirs ((dir-list %load-path))
2029 (if (null? dir-list)
2030 #f
2031 (let* ((dir (in-vicinity (car dir-list) subdir))
2032 (sharlib-full
2033 (or (try-using-libtool-name dir libname)
2034 (try-using-sharlib-name dir libname))))
2035 (if (and sharlib-full (file-exists? sharlib-full))
2036 (link-dynamic-module sharlib-full init)
2037 (check-dirs (cdr dir-list)))))))))
2038
2039(define (try-using-libtool-name libdir libname)
2040 (let ((libtool-filename (in-vicinity libdir
2041 (string-append libname ".la"))))
2042 (and (file-exists? libtool-filename)
2043 libtool-filename)))
2044
2045(define (try-using-sharlib-name libdir libname)
2046 (in-vicinity libdir (string-append libname ".so")))
2047
2048(define (link-dynamic-module filename initname)
2049 ;; Register any linked modules which has been registered on the C level
2050 (register-modules #f)
2051 (let ((dynobj (dynamic-link filename)))
2052 (dynamic-call initname dynobj)
2053 (register-modules dynobj)))
2054
2055(define (try-module-linked module-name)
2056 (init-dynamic-module module-name))
2057
2058(define (try-module-dynamic-link module-name)
2059 (and (find-and-link-dynamic-module module-name)
2060 (init-dynamic-module module-name)))
2061
2062
2063
2064(define autoloads-done '((guile . guile)))
2065
2066(define (autoload-done-or-in-progress? p m)
2067 (let ((n (cons p m)))
2068 (->bool (or (member n autoloads-done)
2069 (member n autoloads-in-progress)))))
2070
2071(define (autoload-done! p m)
2072 (let ((n (cons p m)))
2073 (set! autoloads-in-progress
2074 (delete! n autoloads-in-progress))
2075 (or (member n autoloads-done)
2076 (set! autoloads-done (cons n autoloads-done)))))
2077
2078(define (autoload-in-progress! p m)
2079 (let ((n (cons p m)))
2080 (set! autoloads-done
2081 (delete! n autoloads-done))
2082 (set! autoloads-in-progress (cons n autoloads-in-progress))))
2083
2084(define (set-autoloaded! p m done?)
2085 (if done?
2086 (autoload-done! p m)
2087 (let ((n (cons p m)))
2088 (set! autoloads-done (delete! n autoloads-done))
2089 (set! autoloads-in-progress (delete! n autoloads-in-progress)))))
2090
2091
2092
2093
2094\f
2095;;; {Macros}
2096;;;
2097
2098(define (primitive-macro? m)
2099 (and (macro? m)
2100 (not (macro-transformer m))))
2101
2102;;; {Defmacros}
2103;;;
2104(define macro-table (make-weak-key-hash-table 523))
2105(define xformer-table (make-weak-key-hash-table 523))
2106
2107(define (defmacro? m) (hashq-ref macro-table m))
2108(define (assert-defmacro?! m) (hashq-set! macro-table m #t))
2109(define (defmacro-transformer m) (hashq-ref xformer-table m))
2110(define (set-defmacro-transformer! m t) (hashq-set! xformer-table m t))
2111
2112(define defmacro:transformer
2113 (lambda (f)
2114 (let* ((xform (lambda (exp env)
2115 (copy-tree (apply f (cdr exp)))))
2116 (a (procedure->memoizing-macro xform)))
2117 (assert-defmacro?! a)
2118 (set-defmacro-transformer! a f)
2119 a)))
2120
2121
2122(define defmacro
2123 (let ((defmacro-transformer
2124 (lambda (name parms . body)
2125 (let ((transformer `(lambda ,parms ,@body)))
2126 `(define ,name
2127 (,(lambda (transformer)
2128 (defmacro:transformer transformer))
2129 ,transformer))))))
2130 (defmacro:transformer defmacro-transformer)))
2131
2132(define defmacro:syntax-transformer
2133 (lambda (f)
2134 (procedure->syntax
2135 (lambda (exp env)
2136 (copy-tree (apply f (cdr exp)))))))
2137
2138
2139;; XXX - should the definition of the car really be looked up in the
2140;; current module?
2141
2142(define (macroexpand-1 e)
2143 (cond
2144 ((pair? e) (let* ((a (car e))
2145 (val (and (symbol? a) (local-ref (list a)))))
2146 (if (defmacro? val)
2147 (apply (defmacro-transformer val) (cdr e))
2148 e)))
2149 (#t e)))
2150
2151(define (macroexpand e)
2152 (cond
2153 ((pair? e) (let* ((a (car e))
2154 (val (and (symbol? a) (local-ref (list a)))))
2155 (if (defmacro? val)
2156 (macroexpand (apply (defmacro-transformer val) (cdr e)))
2157 e)))
2158 (#t e)))
2159
2160(provide 'defmacro)
2161
2162\f
2163
2164;;; {Run-time options}
2165
2166((let* ((names '((eval-options-interface
2167 (eval-options eval-enable eval-disable)
2168 (eval-set!))
2169
2170 (debug-options-interface
2171 (debug-options debug-enable debug-disable)
2172 (debug-set!))
2173
2174 (evaluator-traps-interface
2175 (traps trap-enable trap-disable)
2176 (trap-set!))
2177
2178 (read-options-interface
2179 (read-options read-enable read-disable)
2180 (read-set!))
2181
2182 (print-options-interface
2183 (print-options print-enable print-disable)
2184 (print-set!))
2185
2186 (readline-options-interface
2187 (readline-options readline-enable readline-disable)
2188 (readline-set!))
2189 ))
2190 (option-name car)
2191 (option-value cadr)
2192 (option-documentation caddr)
2193
2194 (print-option (lambda (option)
2195 (display (option-name option))
2196 (if (< (string-length
2197 (symbol->string (option-name option)))
2198 8)
2199 (display #\tab))
2200 (display #\tab)
2201 (display (option-value option))
2202 (display #\tab)
2203 (display (option-documentation option))
2204 (newline)))
2205
2206 ;; Below follows the macros defining the run-time option interfaces.
2207
2208 (make-options (lambda (interface)
2209 `(lambda args
2210 (cond ((null? args) (,interface))
2211 ((list? (car args))
2212 (,interface (car args)) (,interface))
2213 (else (for-each ,print-option
2214 (,interface #t)))))))
2215
2216 (make-enable (lambda (interface)
2217 `(lambda flags
2218 (,interface (append flags (,interface)))
2219 (,interface))))
2220
2221 (make-disable (lambda (interface)
2222 `(lambda flags
2223 (let ((options (,interface)))
2224 (for-each (lambda (flag)
2225 (set! options (delq! flag options)))
2226 flags)
2227 (,interface options)
2228 (,interface)))))
2229
2230 (make-set! (lambda (interface)
2231 `((name exp)
2232 (,'quasiquote
2233 (begin (,interface (append (,interface)
2234 (list '(,'unquote name)
2235 (,'unquote exp))))
2236 (,interface))))))
2237 )
2238 (procedure->macro
2239 (lambda (exp env)
2240 (cons 'begin
2241 (apply append
2242 (map (lambda (group)
2243 (let ((interface (car group)))
2244 (append (map (lambda (name constructor)
2245 `(define ,name
2246 ,(constructor interface)))
2247 (cadr group)
2248 (list make-options
2249 make-enable
2250 make-disable))
2251 (map (lambda (name constructor)
2252 `(defmacro ,name
2253 ,@(constructor interface)))
2254 (caddr group)
2255 (list make-set!)))))
2256 names)))))))
2257
2258\f
2259
2260;;; {Running Repls}
2261;;;
2262
2263(define (repl read evaler print)
2264 (let loop ((source (read (current-input-port))))
2265 (print (evaler source))
2266 (loop (read (current-input-port)))))
2267
2268;; A provisional repl that acts like the SCM repl:
2269;;
2270(define scm-repl-silent #f)
2271(define (assert-repl-silence v) (set! scm-repl-silent v))
2272
2273(define *unspecified* (if #f #f))
2274(define (unspecified? v) (eq? v *unspecified*))
2275
2276(define scm-repl-print-unspecified #f)
2277(define (assert-repl-print-unspecified v) (set! scm-repl-print-unspecified v))
2278
2279(define scm-repl-verbose #f)
2280(define (assert-repl-verbosity v) (set! scm-repl-verbose v))
2281
2282(define scm-repl-prompt "guile> ")
2283
2284(define (set-repl-prompt! v) (set! scm-repl-prompt v))
2285
2286(define (default-lazy-handler key . args)
2287 (save-stack lazy-handler-dispatch)
2288 (apply throw key args))
2289
2290(define enter-frame-handler default-lazy-handler)
2291(define apply-frame-handler default-lazy-handler)
2292(define exit-frame-handler default-lazy-handler)
2293
2294(define (lazy-handler-dispatch key . args)
2295 (case key
2296 ((apply-frame)
2297 (apply apply-frame-handler key args))
2298 ((exit-frame)
2299 (apply exit-frame-handler key args))
2300 ((enter-frame)
2301 (apply enter-frame-handler key args))
2302 (else
2303 (apply default-lazy-handler key args))))
2304
2305(define abort-hook (make-hook))
2306
2307;; these definitions are used if running a script.
2308;; otherwise redefined in error-catching-loop.
2309(define (set-batch-mode?! arg) #t)
2310(define (batch-mode?) #t)
2311
2312(define (error-catching-loop thunk)
2313 (let ((status #f)
2314 (interactive #t))
2315 (define (loop first)
2316 (let ((next
2317 (catch #t
2318
2319 (lambda ()
2320 (lazy-catch #t
2321 (lambda ()
2322 (dynamic-wind
2323 (lambda () (unmask-signals))
2324 (lambda ()
2325 (with-traps
2326 (lambda ()
2327 (first)
2328
2329 ;; This line is needed because mark
2330 ;; doesn't do closures quite right.
2331 ;; Unreferenced locals should be
2332 ;; collected.
2333 ;;
2334 (set! first #f)
2335 (let loop ((v (thunk)))
2336 (loop (thunk)))
2337 #f)))
2338 (lambda () (mask-signals))))
2339
2340 lazy-handler-dispatch))
2341
2342 (lambda (key . args)
2343 (case key
2344 ((quit)
2345 (set! status args)
2346 #f)
2347
2348 ((switch-repl)
2349 (apply throw 'switch-repl args))
2350
2351 ((abort)
2352 ;; This is one of the closures that require
2353 ;; (set! first #f) above
2354 ;;
2355 (lambda ()
2356 (run-hook abort-hook)
2357 (force-output (current-output-port))
2358 (display "ABORT: " (current-error-port))
2359 (write args (current-error-port))
2360 (newline (current-error-port))
2361 (if interactive
2362 (begin
2363 (if (and
2364 (not has-shown-debugger-hint?)
2365 (not (memq 'backtrace
2366 (debug-options-interface)))
2367 (stack? (fluid-ref the-last-stack)))
2368 (begin
2369 (newline (current-error-port))
2370 (display
2371 "Type \"(backtrace)\" to get more information or \"(debug)\" to enter the debugger.\n"
2372 (current-error-port))
2373 (set! has-shown-debugger-hint? #t)))
2374 (force-output (current-error-port)))
2375 (begin
2376 (primitive-exit 1)))
2377 (set! stack-saved? #f)))
2378
2379 (else
2380 ;; This is the other cons-leak closure...
2381 (lambda ()
2382 (cond ((= (length args) 4)
2383 (apply handle-system-error key args))
2384 (else
2385 (apply bad-throw key args))))))))))
2386 (if next (loop next) status)))
2387 (set! set-batch-mode?! (lambda (arg)
2388 (cond (arg
2389 (set! interactive #f)
2390 (restore-signals))
2391 (#t
2392 (error "sorry, not implemented")))))
2393 (set! batch-mode? (lambda () (not interactive)))
2394 (loop (lambda () #t))))
2395
2396;;(define the-last-stack (make-fluid)) Defined by scm_init_backtrace ()
2397(define before-signal-stack (make-fluid))
2398(define stack-saved? #f)
2399
2400(define (save-stack . narrowing)
2401 (or stack-saved?
2402 (cond ((not (memq 'debug (debug-options-interface)))
2403 (fluid-set! the-last-stack #f)
2404 (set! stack-saved? #t))
2405 (else
2406 (fluid-set!
2407 the-last-stack
2408 (case (stack-id #t)
2409 ((repl-stack)
2410 (apply make-stack #t save-stack eval #t 0 narrowing))
2411 ((load-stack)
2412 (apply make-stack #t save-stack 0 #t 0 narrowing))
2413 ((tk-stack)
2414 (apply make-stack #t save-stack tk-stack-mark #t 0 narrowing))
2415 ((#t)
2416 (apply make-stack #t save-stack 0 1 narrowing))
2417 (else
2418 (let ((id (stack-id #t)))
2419 (and (procedure? id)
2420 (apply make-stack #t save-stack id #t 0 narrowing))))))
2421 (set! stack-saved? #t)))))
2422
2423(define before-error-hook (make-hook))
2424(define after-error-hook (make-hook))
2425(define before-backtrace-hook (make-hook))
2426(define after-backtrace-hook (make-hook))
2427
2428(define has-shown-debugger-hint? #f)
2429
2430(define (handle-system-error key . args)
2431 (let ((cep (current-error-port)))
2432 (cond ((not (stack? (fluid-ref the-last-stack))))
2433 ((memq 'backtrace (debug-options-interface))
2434 (run-hook before-backtrace-hook)
2435 (newline cep)
2436 (display "Backtrace:\n")
2437 (display-backtrace (fluid-ref the-last-stack) cep)
2438 (newline cep)
2439 (run-hook after-backtrace-hook)))
2440 (run-hook before-error-hook)
2441 (apply display-error (fluid-ref the-last-stack) cep args)
2442 (run-hook after-error-hook)
2443 (force-output cep)
2444 (throw 'abort key)))
2445
2446(define (quit . args)
2447 (apply throw 'quit args))
2448
2449(define exit quit)
2450
2451;;(define has-shown-backtrace-hint? #f) Defined by scm_init_backtrace ()
2452
2453;; Replaced by C code:
2454;;(define (backtrace)
2455;; (if (fluid-ref the-last-stack)
2456;; (begin
2457;; (newline)
2458;; (display-backtrace (fluid-ref the-last-stack) (current-output-port))
2459;; (newline)
2460;; (if (and (not has-shown-backtrace-hint?)
2461;; (not (memq 'backtrace (debug-options-interface))))
2462;; (begin
2463;; (display
2464;;"Type \"(debug-enable 'backtrace)\" if you would like a backtrace
2465;;automatically if an error occurs in the future.\n")
2466;; (set! has-shown-backtrace-hint? #t))))
2467;; (display "No backtrace available.\n")))
2468
2469(define (error-catching-repl r e p)
2470 (error-catching-loop (lambda () (p (e (r))))))
2471
2472(define (gc-run-time)
2473 (cdr (assq 'gc-time-taken (gc-stats))))
2474
2475(define before-read-hook (make-hook))
2476(define after-read-hook (make-hook))
2477
2478;;; The default repl-reader function. We may override this if we've
2479;;; the readline library.
2480(define repl-reader
2481 (lambda (prompt)
2482 (display prompt)
2483 (force-output)
2484 (run-hook before-read-hook)
2485 (read (current-input-port))))
2486
2487(define (scm-style-repl)
2488 (letrec (
2489 (start-gc-rt #f)
2490 (start-rt #f)
2491 (repl-report-start-timing (lambda ()
2492 (set! start-gc-rt (gc-run-time))
2493 (set! start-rt (get-internal-run-time))))
2494 (repl-report (lambda ()
2495 (display ";;; ")
2496 (display (inexact->exact
2497 (* 1000 (/ (- (get-internal-run-time) start-rt)
2498 internal-time-units-per-second))))
2499 (display " msec (")
2500 (display (inexact->exact
2501 (* 1000 (/ (- (gc-run-time) start-gc-rt)
2502 internal-time-units-per-second))))
2503 (display " msec in gc)\n")))
2504
2505 (consume-trailing-whitespace
2506 (lambda ()
2507 (let ((ch (peek-char)))
2508 (cond
2509 ((eof-object? ch))
2510 ((or (char=? ch #\space) (char=? ch #\tab))
2511 (read-char)
2512 (consume-trailing-whitespace))
2513 ((char=? ch #\newline)
2514 (read-char))))))
2515 (-read (lambda ()
2516 (let ((val
2517 (let ((prompt (cond ((string? scm-repl-prompt)
2518 scm-repl-prompt)
2519 ((thunk? scm-repl-prompt)
2520 (scm-repl-prompt))
2521 (scm-repl-prompt "> ")
2522 (else ""))))
2523 (repl-reader prompt))))
2524
2525 ;; As described in R4RS, the READ procedure updates the
2526 ;; port to point to the first character past the end of
2527 ;; the external representation of the object. This
2528 ;; means that it doesn't consume the newline typically
2529 ;; found after an expression. This means that, when
2530 ;; debugging Guile with GDB, GDB gets the newline, which
2531 ;; it often interprets as a "continue" command, making
2532 ;; breakpoints kind of useless. So, consume any
2533 ;; trailing newline here, as well as any whitespace
2534 ;; before it.
2535 ;; But not if EOF, for control-D.
2536 (if (not (eof-object? val))
2537 (consume-trailing-whitespace))
2538 (run-hook after-read-hook)
2539 (if (eof-object? val)
2540 (begin
2541 (repl-report-start-timing)
2542 (if scm-repl-verbose
2543 (begin
2544 (newline)
2545 (display ";;; EOF -- quitting")
2546 (newline)))
2547 (quit 0)))
2548 val)))
2549
2550 (-eval (lambda (sourc)
2551 (repl-report-start-timing)
2552 (start-stack 'repl-stack
2553 (eval sourc (interaction-environment)))))
2554
2555 (-print (let ((maybe-print (lambda (result)
2556 (if (or scm-repl-print-unspecified
2557 (not (unspecified? result)))
2558 (begin
2559 (write result)
2560 (newline))))))
2561 (lambda (result)
2562 (if (not scm-repl-silent)
2563 (begin
2564 (maybe-print result)
2565 (if scm-repl-verbose
2566 (repl-report))
2567 (force-output))))))
2568
2569 (-quit (lambda (args)
2570 (if scm-repl-verbose
2571 (begin
2572 (display ";;; QUIT executed, repl exitting")
2573 (newline)
2574 (repl-report)))
2575 args))
2576
2577 (-abort (lambda ()
2578 (if scm-repl-verbose
2579 (begin
2580 (display ";;; ABORT executed.")
2581 (newline)
2582 (repl-report)))
2583 (repl -read -eval -print))))
2584
2585 (let ((status (error-catching-repl -read
2586 -eval
2587 -print)))
2588 (-quit status))))
2589
2590
2591\f
2592;;; {IOTA functions: generating lists of numbers}
2593
2594(define (iota n)
2595 (let loop ((count (1- n)) (result '()))
2596 (if (< count 0) result
2597 (loop (1- count) (cons count result)))))
2598
2599\f
2600;;; {While}
2601;;;
2602;;; with `continue' and `break'.
2603;;;
2604
2605(defmacro while (cond . body)
2606 `(letrec ((continue (lambda () (or (not ,cond) (begin (begin ,@ body) (continue)))))
2607 (break (lambda val (apply throw 'break val))))
2608 (catch 'break
2609 (lambda () (continue))
2610 (lambda v (cadr v)))))
2611
2612;;; {collect}
2613;;;
2614;;; Similar to `begin' but returns a list of the results of all constituent
2615;;; forms instead of the result of the last form.
2616;;; (The definition relies on the current left-to-right
2617;;; order of evaluation of operands in applications.)
2618
2619(defmacro collect forms
2620 (cons 'list forms))
2621
2622;;; {with-fluids}
2623
2624;; with-fluids is a convenience wrapper for the builtin procedure
2625;; `with-fluids*'. The syntax is just like `let':
2626;;
2627;; (with-fluids ((fluid val)
2628;; ...)
2629;; body)
2630
2631(defmacro with-fluids (bindings . body)
2632 `(with-fluids* (list ,@(map car bindings)) (list ,@(map cadr bindings))
2633 (lambda () ,@body)))
2634
2635\f
2636
2637;;; {Macros}
2638;;;
2639
2640;; actually....hobbit might be able to hack these with a little
2641;; coaxing
2642;;
2643
2644(defmacro define-macro (first . rest)
2645 (let ((name (if (symbol? first) first (car first)))
2646 (transformer
2647 (if (symbol? first)
2648 (car rest)
2649 `(lambda ,(cdr first) ,@rest))))
2650 `(define ,name (defmacro:transformer ,transformer))))
2651
2652
2653(defmacro define-syntax-macro (first . rest)
2654 (let ((name (if (symbol? first) first (car first)))
2655 (transformer
2656 (if (symbol? first)
2657 (car rest)
2658 `(lambda ,(cdr first) ,@rest))))
2659 `(define ,name (defmacro:syntax-transformer ,transformer))))
2660\f
2661;;; {Module System Macros}
2662;;;
2663
2664(defmacro define-module args
2665 `(let* ((process-define-module process-define-module)
2666 (set-current-module set-current-module)
2667 (module (process-define-module ',args)))
2668 (set-current-module module)
2669 module))
2670
2671;; the guts of the use-modules macro. add the interfaces of the named
2672;; modules to the use-list of the current module, in order
2673(define (process-use-modules module-names)
2674 (for-each (lambda (module-name)
2675 (let ((mod-iface (resolve-interface module-name)))
2676 (or mod-iface
2677 (error "no such module" module-name))
2678 (module-use! (current-module) mod-iface)))
2679 (reverse module-names)))
2680
2681(defmacro use-modules modules
2682 `(process-use-modules ',modules))
2683
2684(defmacro use-syntax (spec)
2685 `(begin
2686 ,@(if (pair? spec)
2687 `((process-use-modules ',(list spec))
2688 (set-module-transformer! (current-module)
2689 ,(car (last-pair spec))))
2690 `((set-module-transformer! (current-module) ,spec)))
2691 (fluid-set! scm:eval-transformer (module-transformer (current-module)))))
2692
2693(define define-private define)
2694
2695(defmacro define-public args
2696 (define (syntax)
2697 (error "bad syntax" (list 'define-public args)))
2698 (define (defined-name n)
2699 (cond
2700 ((symbol? n) n)
2701 ((pair? n) (defined-name (car n)))
2702 (else (syntax))))
2703 (cond
2704 ((null? args) (syntax))
2705
2706 (#t (let ((name (defined-name (car args))))
2707 `(begin
2708 (let ((public-i (module-public-interface (current-module))))
2709 ;; Make sure there is a local variable:
2710 ;;
2711 (module-define! (current-module)
2712 ',name
2713 (module-ref (current-module) ',name #f))
2714
2715 ;; Make sure that local is exported:
2716 ;;
2717 (module-add! public-i ',name
2718 (module-variable (current-module) ',name)))
2719
2720 ;; Now (re)define the var normally. Bernard URBAN
2721 ;; suggests we use eval here to accomodate Hobbit; it lets
2722 ;; the interpreter handle the define-private form, which
2723 ;; Hobbit can't digest.
2724 (eval '(define-private ,@ args) (interaction-environment)))))))
2725
2726
2727
2728(defmacro defmacro-public args
2729 (define (syntax)
2730 (error "bad syntax" (list 'defmacro-public args)))
2731 (define (defined-name n)
2732 (cond
2733 ((symbol? n) n)
2734 (else (syntax))))
2735 (cond
2736 ((null? args) (syntax))
2737
2738 (#t (let ((name (defined-name (car args))))
2739 `(begin
2740 (let ((public-i (module-public-interface (current-module))))
2741 ;; Make sure there is a local variable:
2742 ;;
2743 (module-define! (current-module)
2744 ',name
2745 (module-ref (current-module) ',name #f))
2746
2747 ;; Make sure that local is exported:
2748 ;;
2749 (module-add! public-i ',name (module-variable (current-module) ',name)))
2750
2751 ;; Now (re)define the var normally.
2752 ;;
2753 (defmacro ,@ args))))))
2754
2755
2756(define (module-export! m names)
2757 (let ((public-i (module-public-interface m)))
2758 (for-each (lambda (name)
2759 ;; Make sure there is a local variable:
2760 (module-define! m name (module-ref m name #f))
2761 ;; Make sure that local is exported:
2762 (module-add! public-i name (module-variable m name)))
2763 names)))
2764
2765(defmacro export names
2766 `(module-export! (current-module) ',names))
2767
2768(define export-syntax export)
2769
2770
2771(define load load-module)
2772
2773
2774\f
2775;;; {Load emacs interface support if emacs option is given.}
2776
2777(define (load-emacs-interface)
2778 (if (memq 'debug-extensions *features*)
2779 (debug-enable 'backtrace))
2780 (define-module (guile-user) :use-module (ice-9 emacs)))
2781
2782\f
2783
2784(define using-readline?
2785 (let ((using-readline? (make-fluid)))
2786 (make-procedure-with-setter
2787 (lambda () (fluid-ref using-readline?))
2788 (lambda (v) (fluid-set! using-readline? v)))))
2789
2790;; this is just (scm-style-repl) with a wrapper to install and remove
2791;; signal handlers.
2792(define (top-repl)
2793
2794 ;; Load emacs interface support if emacs option is given.
2795 (if (and (module-defined? the-root-module 'use-emacs-interface)
2796 (module-ref the-root-module 'use-emacs-interface))
2797 (load-emacs-interface))
2798
2799 ;; Place the user in the guile-user module.
2800 (define-module (guile-user)
2801 :use-module (guile) ;so that bindings will be checked here first
2802 :use-module (ice-9 session)
2803 :use-module (ice-9 debug)
2804 :autoload (ice-9 debugger) (debug)) ;load debugger on demand
2805 (if (memq 'threads *features*)
2806 (define-module (guile-user) :use-module (ice-9 threads)))
2807 (if (memq 'regex *features*)
2808 (define-module (guile-user) :use-module (ice-9 regex)))
2809
2810 (let ((old-handlers #f)
2811 (signals (if (provided? 'posix)
2812 `((,SIGINT . "User interrupt")
2813 (,SIGFPE . "Arithmetic error")
2814 (,SIGBUS . "Bad memory access (bus error)")
2815 (,SIGSEGV .
2816 "Bad memory access (Segmentation violation)"))
2817 '())))
2818
2819 (dynamic-wind
2820
2821 ;; call at entry
2822 (lambda ()
2823 (let ((make-handler (lambda (msg)
2824 (lambda (sig)
2825 ;; Make a backup copy of the stack
2826 (fluid-set! before-signal-stack
2827 (fluid-ref the-last-stack))
2828 (save-stack %deliver-signals)
2829 (scm-error 'signal
2830 #f
2831 msg
2832 #f
2833 (list sig))))))
2834 (set! old-handlers
2835 (map (lambda (sig-msg)
2836 (sigaction (car sig-msg)
2837 (make-handler (cdr sig-msg))))
2838 signals))))
2839
2840 ;; the protected thunk.
2841 (lambda ()
2842 (let ((status (scm-style-repl)))
2843 (run-hook exit-hook)
2844 status))
2845
2846 ;; call at exit.
2847 (lambda ()
2848 (map (lambda (sig-msg old-handler)
2849 (if (not (car old-handler))
2850 ;; restore original C handler.
2851 (sigaction (car sig-msg) #f)
2852 ;; restore Scheme handler, SIG_IGN or SIG_DFL.
2853 (sigaction (car sig-msg)
2854 (car old-handler)
2855 (cdr old-handler))))
2856 signals old-handlers)))))
2857
2858(defmacro false-if-exception (expr)
2859 `(catch #t (lambda () ,expr)
2860 (lambda args #f)))
2861
2862;;; This hook is run at the very end of an interactive session.
2863;;;
2864(define exit-hook (make-hook))
2865
2866\f
2867(define-module (guile))
2868
2869(append! %load-path (cons "." ()))