GOOPS needs the observer protocol specified for the new module
[bpt/guile.git] / ice-9 / boot-9.scm
1 ;;; installed-scm-file
2
3 ;;;; Copyright (C) 1995, 1996, 1997, 1998, 1999 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 \f
44 ;;; {R4RS compliance}
45
46 (primitive-load-path "ice-9/r4rs.scm")
47
48 \f
49 ;;; {Simple Debugging Tools}
50 ;;
51
52
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.:
57 ;;
58 ;; (+ 10 (troublesome-fn))
59 ;; => (+ 10 (pk 'troublesome-fn-returned (troublesome-fn)))
60 ;;
61
62 (define (peek . stuff)
63 (newline)
64 (display ";;; ")
65 (write stuff)
66 (newline)
67 (car (last-pair stuff)))
68
69 (define pk peek)
70
71 (define (warn . stuff)
72 (with-output-to-port (current-error-port)
73 (lambda ()
74 (newline)
75 (display ";;; WARNING ")
76 (display stuff)
77 (newline)
78 (car (last-pair stuff)))))
79
80 \f
81 ;;; {Trivial Functions}
82 ;;;
83
84 (define (id x) x)
85 (define (1+ n) (+ n 1))
86 (define (-1+ n) (+ n -1))
87 (define 1- -1+)
88 (define return-it noop)
89 (define (and=> value procedure) (and value (procedure value)))
90 (define (make-hash-table k) (make-vector k '()))
91
92 ;;; apply-to-args is functionally redunant with apply and, worse,
93 ;;; is less general than apply since it only takes two arguments.
94 ;;;
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.:
98 ;;;
99 ;;; (apply-to-args (return-3d-mouse-coords)
100 ;;; (lambda (x y z)
101 ;;; ...))
102 ;;;
103
104 (define (apply-to-args args fn) (apply fn args))
105
106 \f
107 ;;; {Integer Math}
108 ;;;
109
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)
114 (quotient k 2)
115 (if (even? k) acc (proc acc x))
116 proc))))
117
118 (define string-character-length string-length)
119
120
121
122 ;; A convenience function for combining flag bits. Like logior, but
123 ;; handles the cases of 0 and 1 arguments.
124 ;;
125 (define (flags . args)
126 (cond
127 ((null? args) 0)
128 ((null? (cdr args)) (car args))
129 (else (apply logior args))))
130
131 \f
132 ;;; {Symbol Properties}
133 ;;;
134
135 (define (symbol-property sym prop)
136 (let ((pair (assoc prop (symbol-pref sym))))
137 (and pair (cdr pair))))
138
139 (define (set-symbol-property! sym prop val)
140 (let ((pair (assoc prop (symbol-pref sym))))
141 (if pair
142 (set-cdr! pair val)
143 (symbol-pset! sym (acons prop val (symbol-pref sym))))))
144
145 (define (symbol-property-remove! sym prop)
146 (let ((pair (assoc prop (symbol-pref sym))))
147 (if pair
148 (symbol-pset! sym (delq! pair (symbol-pref sym))))))
149
150 \f
151
152 ;;; {Line and Delimited I/O}
153
154 ;;; corresponds to SCM_LINE_INCREMENTORS in libguile.
155 (define scm-line-incrementors "\n")
156
157 (define (read-line! string . maybe-port)
158 (let* ((port (if (pair? maybe-port)
159 (car maybe-port)
160 (current-input-port))))
161 (let* ((rv (%read-delimited! scm-line-incrementors
162 string
163 #t
164 port))
165 (terminator (car rv))
166 (nchars (cdr rv)))
167 (cond ((and (= nchars 0)
168 (eof-object? terminator))
169 terminator)
170 ((not terminator) #f)
171 (else nchars)))))
172
173 (define (read-delimited! delims buf . args)
174 (let* ((num-args (length args))
175 (port (if (> num-args 0)
176 (car args)
177 (current-input-port)))
178 (handle-delim (if (> num-args 1)
179 (cadr args)
180 'trim))
181 (start (if (> num-args 2)
182 (caddr args)
183 0))
184 (end (if (> num-args 3)
185 (cadddr args)
186 (string-length buf))))
187 (let* ((rv (%read-delimited! delims
188 buf
189 (not (eq? handle-delim 'peek))
190 port
191 start
192 end))
193 (terminator (car rv))
194 (nchars (cdr rv)))
195 (cond ((or (not terminator) ; buffer filled
196 (eof-object? terminator))
197 (if (zero? nchars)
198 (if (eq? handle-delim 'split)
199 (cons terminator terminator)
200 terminator)
201 (if (eq? handle-delim 'split)
202 (cons nchars terminator)
203 nchars)))
204 (else
205 (case handle-delim
206 ((trim peek) nchars)
207 ((concat) (string-set! buf (+ nchars start) terminator)
208 (+ nchars 1))
209 ((split) (cons nchars terminator))
210 (else (error "unexpected handle-delim value: "
211 handle-delim))))))))
212
213 (define (read-delimited delims . args)
214 (let* ((port (if (pair? args)
215 (let ((pt (car args)))
216 (set! args (cdr args))
217 pt)
218 (current-input-port)))
219 (handle-delim (if (pair? args)
220 (car args)
221 'trim)))
222 (let loop ((substrings ())
223 (total-chars 0)
224 (buf-size 100)) ; doubled each time through.
225 (let* ((buf (make-string buf-size))
226 (rv (%read-delimited! delims
227 buf
228 (not (eq? handle-delim 'peek))
229 port))
230 (terminator (car rv))
231 (nchars (cdr rv))
232 (join-substrings
233 (lambda ()
234 (apply string-append
235 (reverse
236 (cons (if (and (eq? handle-delim 'concat)
237 (not (eof-object? terminator)))
238 (string terminator)
239 "")
240 (cons (make-shared-substring buf 0 nchars)
241 substrings))))))
242 (new-total (+ total-chars nchars)))
243 (cond ((not terminator)
244 ;; buffer filled.
245 (loop (cons (substring buf 0 nchars) substrings)
246 new-total
247 (* buf-size 2)))
248 ((eof-object? terminator)
249 (if (zero? new-total)
250 (if (eq? handle-delim 'split)
251 (cons terminator terminator)
252 terminator)
253 (if (eq? handle-delim 'split)
254 (cons (join-substrings) terminator)
255 (join-substrings))))
256 (else
257 (case handle-delim
258 ((trim peek concat) (join-substrings))
259 ((split) (cons (join-substrings) terminator))
260
261
262 (else (error "unexpected handle-delim value: "
263 handle-delim)))))))))
264
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.
274
275 (define (read-line . args)
276 (let* ((port (if (null? args)
277 (current-input-port)
278 (car args)))
279 (handle-delim (if (> (length args) 1)
280 (cadr args)
281 'trim))
282 (line/delim (%read-line port))
283 (line (car line/delim))
284 (delim (cdr line/delim)))
285 (case handle-delim
286 ((trim) line)
287 ((split) line/delim)
288 ((concat) (if (and (string? line) (char? delim))
289 (string-append line (string delim))
290 line))
291 ((peek) (if (char? delim)
292 (unread-char delim port))
293 line)
294 (else
295 (error "unexpected handle-delim value: " handle-delim)))))
296
297 \f
298 ;;; {Arrays}
299 ;;;
300
301 (begin
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)
310
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))))
322
323 \f
324 ;;; {Keywords}
325 ;;;
326
327 (define (symbol->keyword symbol)
328 (make-keyword-from-dash-symbol (symbol-append '- symbol)))
329
330 (define (keyword->symbol kw)
331 (let ((sym (keyword-dash-symbol kw)))
332 (string->symbol (substring sym 1 (string-length sym)))))
333
334 (define (kw-arg-ref args kw)
335 (let ((rem (member kw args)))
336 (and rem (pair? (cdr rem)) (cadr rem))))
337
338 \f
339
340 ;;; {Structs}
341
342 (define (struct-layout s)
343 (struct-ref (struct-vtable s) vtable-index-layout))
344
345 \f
346 ;;; {Records}
347 ;;;
348
349 ;; Printing records: by default, records are printed as
350 ;;
351 ;; #<type-name field1: val1 field2: val2 ...>
352 ;;
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
356 ;;
357 ;; (<printer> object port)
358 ;;
359 ;; It should print OBJECT to PORT.
360
361 (define (inherit-print-state old-port new-port)
362 (if (pair? old-port)
363 (cons (if (pair? new-port) (car new-port) new-port)
364 (cdr old-port))
365 new-port))
366
367 ;; 0: type-name, 1: fields
368 (define record-type-vtable
369 (make-vtable-vtable "prpr" 0
370 (lambda (s p)
371 (cond ((eq? s record-type-vtable)
372 (display "#<record-type-vtable>" p))
373 (else
374 (display "#<record-type " p)
375 (display (record-type-name s) p)
376 (display ">" p))))))
377
378 (define (record-type? obj)
379 (and (struct? obj) (eq? record-type-vtable (struct-vtable obj))))
380
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
384 (make-struct-layout
385 (apply symbol-append
386 (map (lambda (f) "pw") fields)))
387 (or printer-fn
388 (lambda (s p)
389 (display "#<" p)
390 (display type-name p)
391 (let loop ((fields fields)
392 (off 0))
393 (cond
394 ((not (null? fields))
395 (display " " p)
396 (display (car fields) p)
397 (display ": " p)
398 (display (struct-ref s off) p)
399 (loop (cdr fields) (+ 1 off)))))
400 (display ">" p)))
401 type-name
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)
406 type-name
407 (string->symbol type-name)))
408 struct)))
409
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)))
414
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)))
419
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)
425 f
426 #f))
427 (record-type-fields rtd)))))))
428
429 (define (record-predicate rtd)
430 (lambda (obj) (and (struct? obj) (eq? rtd (struct-vtable obj)))))
431
432 (define (record-accessor rtd field-name)
433 (let* ((pos (list-index (record-type-fields rtd) field-name)))
434 (if (not pos)
435 (error 'no-such-field field-name))
436 (eval `(lambda (obj)
437 (and (eq? ',rtd (record-type-descriptor obj))
438 (struct-ref obj ,pos))))))
439
440 (define (record-modifier rtd field-name)
441 (let* ((pos (list-index (record-type-fields rtd) field-name)))
442 (if (not pos)
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))))))
447
448
449 (define (record? obj)
450 (and (struct? obj) (record-type? (struct-vtable obj))))
451
452 (define (record-type-descriptor obj)
453 (if (struct? obj)
454 (struct-vtable obj)
455 (error 'not-a-record obj)))
456
457 (provide 'record)
458
459 \f
460 ;;; {Booleans}
461 ;;;
462
463 (define (->bool x) (not (not x)))
464
465 \f
466 ;;; {Symbols}
467 ;;;
468
469 (define (symbol-append . args)
470 (string->symbol (apply string-append args)))
471
472 (define (list->symbol . args)
473 (string->symbol (apply list->string args)))
474
475 (define (symbol . args)
476 (string->symbol (apply string args)))
477
478 (define (obarray-symbol-append ob . args)
479 (string->obarray-symbol (apply string-append ob args)))
480
481 (define (obarray-gensym obarray . opt)
482 (if (null? opt)
483 (gensym "%%gensym" obarray)
484 (gensym (car opt) obarray)))
485
486 \f
487 ;;; {Lists}
488 ;;;
489
490 (define (list-index l k)
491 (let loop ((n 0)
492 (l l))
493 (and (not (null? l))
494 (if (eq? (car l) k)
495 n
496 (loop (+ n 1) (cdr l))))))
497
498 (define (make-list n . init)
499 (if (pair? init) (set! init (car init)))
500 (let loop ((answer '())
501 (n n))
502 (if (<= n 0)
503 answer
504 (loop (cons init answer) (- n 1)))))
505
506
507 \f
508 ;;; {Multiple return values}
509
510 (define *values-rtd*
511 (make-record-type "values"
512 '(values)))
513
514 (define values
515 (let ((make-values (record-constructor *values-rtd*)))
516 (lambda x
517 (if (and (not (null? x))
518 (null? (cdr x)))
519 (car x)
520 (make-values x)))))
521
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))))))
530
531 (provide 'values)
532
533 \f
534 ;;; {and-map and or-map}
535 ;;;
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.
539 ;;;
540
541 ;; and-map f l
542 ;;
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.
546 ;;
547 (define (and-map f lst)
548 (let loop ((result #t)
549 (l lst))
550 (and result
551 (or (and (null? l)
552 result)
553 (loop (f (car l)) (cdr l))))))
554
555 ;; or-map f l
556 ;;
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.
559 ;;
560 (define (or-map f lst)
561 (let loop ((result #f)
562 (l lst))
563 (or result
564 (and (not (null? l))
565 (loop (f (car l)) (cdr l))))))
566
567 \f
568 ;;; {Hooks}
569 ;;;
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.
573 ;;;
574 (if (not (defined? 'new-add-hook!))
575 (begin
576 (define new-add-hook! add-hook!)
577 (define new-remove-hook! remove-hook!)))
578
579 (define (run-hooks hook)
580 (if (and (pair? hook) (eq? (car hook) 'hook))
581 (run-hook hook)
582 (for-each (lambda (thunk) (thunk)) hook)))
583
584 (define *suppress-old-style-hook-warning* #f)
585
586 (define add-hook!
587 (procedure->memoizing-macro
588 (lambda (exp env)
589 (let ((hook (local-eval (cadr exp) env)))
590 (if (and (pair? hook) (eq? (car hook) 'hook))
591 `(new-add-hook! ,@(cdr exp))
592 (begin
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)))
597 (set! ,(cadr exp)
598 (cons thunk ,(cadr exp)))))))))))
599
600 (define remove-hook!
601 (procedure->memoizing-macro
602 (lambda (exp env)
603 (let ((hook (local-eval (cadr exp) env)))
604 (if (and (pair? hook) (eq? (car hook) 'hook))
605 `(new-remove-hook! ,@(cdr exp))
606 (begin
607 (or *suppress-old-style-hook-warning*
608 (display "Warning: Old style hooks\n" (current-error-port)))
609 `(let ((thunk ,(caddr exp)))
610 (set! ,(cadr exp)
611 (delq! thunk ,(cadr exp))))))))))
612
613 \f
614 ;;; {Files}
615 ;;;
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.
619
620 (define (feature? feature)
621 (and (memq feature *features*) #t))
622
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))
638
639 ;; derived from stat mode.
640 (define (stat:type f) (vector-ref f 13))
641 (define (stat:perms f) (vector-ref f 14))
642
643 (define file-exists?
644 (if (feature? 'posix)
645 (lambda (str)
646 (access? str F_OK))
647 (lambda (str)
648 (let ((port (catch 'system-error (lambda () (open-file str OPEN_READ))
649 (lambda args #f))))
650 (if port (begin (close-port port) #t)
651 #f)))))
652
653 (define file-is-directory?
654 (if (feature? 'i/o-extensions)
655 (lambda (str)
656 (eq? (stat:type (stat str)) 'directory))
657 (lambda (str)
658 (display str)
659 (newline)
660 (let ((port (catch 'system-error
661 (lambda () (open-file (string-append str "/.")
662 OPEN_READ))
663 (lambda args #f))))
664 (if port (begin (close-port port) #t)
665 #f)))))
666
667 (define (has-suffix? str suffix)
668 (let ((sufl (string-length suffix))
669 (sl (string-length str)))
670 (and (> sl sufl)
671 (string=? (substring str (- sl sufl) sl) suffix))))
672
673 \f
674 ;;; {Error Handling}
675 ;;;
676
677 (define (error . args)
678 (save-stack)
679 (if (null? args)
680 (scm-error 'misc-error #f "?" #f #f)
681 (let loop ((msg "%s")
682 (rest (cdr args)))
683 (if (not (null? rest))
684 (loop (string-append msg " %S")
685 (cdr rest))
686 (scm-error 'misc-error #f msg args #f)))))
687
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.
693 ;;
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))))
698
699 \f
700 ;;; {Non-polymorphic versions of POSIX functions}
701
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))
732
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))
740
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))
745
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))
751
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))
756
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))
760
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))
765
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))
770
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))
776
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))
788
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))
800
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))
806
807 (define (file-position . args) (apply ftell args))
808 (define (file-set-position . args) (apply fseek args))
809
810 (define (move->fdes fd/port fd)
811 (cond ((integer? fd/port)
812 (dup->fdes fd/port fd)
813 (close fd/port)
814 fd)
815 (else
816 (primitive-move->fdes fd/port fd)
817 (set-port-revealed! fd/port 1)
818 fd/port)))
819
820 (define (release-port-handle port)
821 (let ((revealed (port-revealed port)))
822 (if (> revealed 0)
823 (set-port-revealed! port (- revealed 1)))))
824
825 (define (dup->port port/fd mode . maybe-fd)
826 (let ((port (fdopen (apply dup->fdes port/fd maybe-fd)
827 mode)))
828 (if (pair? maybe-fd)
829 (set-port-revealed! port 1))
830 port))
831
832 (define (dup->inport port/fd . maybe-fd)
833 (apply dup->port port/fd "r" maybe-fd))
834
835 (define (dup->outport port/fd . maybe-fd)
836 (apply dup->port port/fd "w" maybe-fd))
837
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)))
842
843 (define (duplicate-port port modes)
844 (dup->port port modes))
845
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)
851 result))
852 ((input-port? (car rest-ports))
853 (set-port-revealed! (car rest-ports)
854 (+ (port-revealed (car rest-ports)) 1))
855 (car rest-ports))
856 (else
857 (loop (cdr rest-ports))))))
858
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)
864 result))
865 ((output-port? (car rest-ports))
866 (set-port-revealed! (car rest-ports)
867 (+ (port-revealed (car rest-ports)) 1))
868 (car rest-ports))
869 (else
870 (loop (cdr rest-ports))))))
871
872 (define (port->fdes port)
873 (set-port-revealed! port (+ (port-revealed port) 1))
874 (fileno port))
875
876 (define (setenv name value)
877 (if value
878 (putenv (string-append name "=" value))
879 (putenv name)))
880
881 \f
882 ;;; {Load Paths}
883 ;;;
884
885 ;;; Here for backward compatability
886 ;;
887 (define scheme-file-suffix (lambda () ".scm"))
888
889 (define (in-vicinity vicinity file)
890 (let ((tail (let ((len (string-length vicinity)))
891 (if (zero? len)
892 #f
893 (string-ref vicinity (- len 1))))))
894 (string-append vicinity
895 (if (or (not tail)
896 (eq? tail #\/))
897 ""
898 "/")
899 file)))
900
901 \f
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.
906
907 (define (command-line) (program-arguments))
908
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")))
914 (catch 'system-error
915 (lambda ()
916 (let ((stats (stat path)))
917 (if (not (eq? (stat:type stats) 'directory))
918 path)))
919 (lambda dummy #f))))
920 (let ((path (or (has-init? (or (getenv "HOME") "/"))
921 (has-init? (passwd:dir (getpw (getuid)))))))
922 (if path (primitive-load path))))
923
924 \f
925 ;;; {Loading by paths}
926
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)))
933
934
935 \f
936 ;;; {Transcendental Functions}
937 ;;;
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.
941 ;;;
942
943 (define (exp z)
944 (if (real? z) ($exp z)
945 (make-polar ($exp (real-part z)) (imag-part z))))
946
947 (define (log z)
948 (if (and (real? z) (>= z 0))
949 ($log z)
950 (make-rectangular ($log (magnitude z)) (angle z))))
951
952 (define (sqrt z)
953 (if (real? z)
954 (if (negative? z) (make-rectangular 0 ($sqrt (- z)))
955 ($sqrt z))
956 (make-polar ($sqrt (magnitude z)) (/ (angle z) 2))))
957
958 (define expt
959 (let ((integer-expt integer-expt))
960 (lambda (z1 z2)
961 (cond ((exact? z2)
962 (integer-expt z1 z2))
963 ((and (real? z2) (real? z1) (>= z1 0))
964 ($expt z1 z2))
965 (else
966 (exp (* z2 (log z1))))))))
967
968 (define (sinh z)
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))))))
973 (define (cosh z)
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))))))
978 (define (tanh z)
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)))))
984
985 (define (asinh z)
986 (if (real? z) ($asinh z)
987 (log (+ z (sqrt (+ (* z z) 1))))))
988
989 (define (acosh z)
990 (if (and (real? z) (>= z 1))
991 ($acosh z)
992 (log (+ z (sqrt (- (* z z) 1))))))
993
994 (define (atanh z)
995 (if (and (real? z) (> z -1) (< z 1))
996 ($atanh z)
997 (/ (log (/ (+ 1 z) (- 1 z))) 2)))
998
999 (define (sin z)
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))))))
1004 (define (cos z)
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)))))))
1009 (define (tan z)
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)))))
1015
1016 (define (asin z)
1017 (if (and (real? z) (>= z -1) (<= z 1))
1018 ($asin z)
1019 (* -i (asinh (* +i z)))))
1020
1021 (define (acos z)
1022 (if (and (real? z) (>= z -1) (<= z 1))
1023 ($acos z)
1024 (+ (/ (angle -1) 2) (* +i (asinh (* +i z))))))
1025
1026 (define (atan z . y)
1027 (if (null? y)
1028 (if (real? z) ($atan z)
1029 (/ (log (/ (- +i z) (+ +i z))) +2i))
1030 ($atan2 z (car y))))
1031
1032 (set! abs magnitude)
1033
1034 (define (log10 arg)
1035 (/ (log arg) (log 10)))
1036
1037 \f
1038
1039 ;;; {Reader Extensions}
1040 ;;;
1041
1042 ;;; Reader code for various "#c" forms.
1043 ;;;
1044
1045 ;;; Parse the portion of a #/ list that comes after the first slash.
1046 (define (read-path-list-notation slash port)
1047 (letrec
1048
1049 ;; Is C a delimiter?
1050 ((delimiter? (lambda (c) (or (eof-object? c)
1051 (char-whitespace? c)
1052 (string-index "()\";" c))))
1053
1054 ;; Read and return one component of a path list.
1055 (read-component
1056 (lambda ()
1057 (let loop ((reversed-chars '()))
1058 (let ((c (peek-char port)))
1059 (if (or (delimiter? c)
1060 (char=? c #\/))
1061 (string->symbol (list->string (reverse reversed-chars)))
1062 (loop (cons (read-char port) reversed-chars))))))))
1063
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 #\/))
1068 (begin
1069 (read-char port)
1070 (loop (cons (read-component) reversed-path)))
1071 (reverse reversed-path))))))
1072
1073 (define (read-path-list-notation-warning slash port)
1074 (if (not (getenv "GUILE_HUSH"))
1075 (begin
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))
1086
1087
1088 (read-hash-extend #\' (lambda (c port)
1089 (read port)))
1090 (read-hash-extend #\. (lambda (c port)
1091 (eval (read port))))
1092
1093 (if (feature? 'array)
1094 (begin
1095 (let ((make-array-proc (lambda (template)
1096 (lambda (c port)
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)))))
1107
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)
1111
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)))
1118 val)))
1119 (prot (if (eq? #\( (peek-char port))
1120 '()
1121 (let ((c (read-char port)))
1122 (case c ((#\b) #t)
1123 ((#\a) #\a)
1124 ((#\u) 1)
1125 ((#\e) -1)
1126 ((#\s) 1.0)
1127 ((#\i) 1/3)
1128 ((#\c) 0+i)
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"))))
1133
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")))
1138
1139 \f
1140 ;;; {Command Line Options}
1141 ;;;
1142
1143 (define (get-option argv kw-opts kw-args return)
1144 (cond
1145 ((null? argv)
1146 (return #f #f argv))
1147
1148 ((or (not (eq? #\- (string-ref (car argv) 0)))
1149 (eq? (string-length (car argv)) 1))
1150 (return 'normal-arg (car argv) (cdr argv)))
1151
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)
1160 (+ kw-arg-pos 1)
1161 (string-length (car argv))))
1162 (and kw-arg?
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)))))
1167
1168 (else
1169 (let* ((char (substring (car argv) 1 2))
1170 (kw (symbol->keyword char)))
1171 (cond
1172
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))
1176 (cdr argv)
1177 (cons (string-append "-" rest-car) (cdr argv)))))
1178 (return kw #f new-argv)))
1179
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))
1183 (cadr argv)
1184 rest-car))
1185 (new-argv (if (= 0 (string-length rest-car))
1186 (cddr argv)
1187 (cdr argv))))
1188 (return kw arg new-argv)))
1189
1190 (else (return 'usage-error kw argv)))))))
1191
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))))))
1197
1198 (define (display-usage-report kw-desc)
1199 (for-each
1200 (lambda (kw)
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) ">")
1209 ""))
1210 (left-part (string-append
1211 (with-output-to-string
1212 (lambda ()
1213 (map (lambda (x) (display (keyword-symbol x)) (display " "))
1214 opts-proper)))
1215 arg-name))
1216 (middle-part (if (and (< (string-length left-part) 30)
1217 (< (string-length help) 40))
1218 (make-string (- 30 (string-length left-part)) #\ )
1219 "\n\t")))
1220 (display left-part)
1221 (display middle-part)
1222 (display help)
1223 (newline))))
1224 kw-desc))
1225
1226
1227
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)
1234 x))
1235 raw-usage))
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))
1243 opts
1244 (cond
1245 ((symbol? (car opts)) opts)
1246 ((boolean? (car opts)) opts)
1247 ((string? (caar opts)) (cdar opts))
1248 (else (car opts)))))
1249 (cdr case)))
1250 cases)))
1251 `(let ((%display-usage (lambda () (display-usage-report ',usage-desc))))
1252 (lambda (%argv)
1253 (let %next-arg ((%argv %argv))
1254 (get-option %argv
1255 ',kw-opts
1256 ',kw-args
1257 (lambda (%opt %arg %new-argv)
1258 (case %opt
1259 ,@ transmogrified-cases))))))))
1260
1261
1262 \f
1263
1264 ;;; {Low Level Modules}
1265 ;;;
1266 ;;; These are the low level data structures for modules.
1267 ;;;
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.
1271 ;;;
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...>
1290 ;;;
1291 ;;;
1292
1293 \f
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
1299 ;; printed. Sigh.)
1300
1301 (define (%print-module mod port) ; unused args: depth length style table)
1302 (display "#<" port)
1303 (display (or (module-kind mod) "module") port)
1304 (let ((name (module-name mod)))
1305 (if name
1306 (begin
1307 (display " " port)
1308 (display name port))))
1309 (display " " port)
1310 (display (number->string (object-address mod) 16) port)
1311 (display ">" port))
1312
1313 ;; module-type
1314 ;;
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.
1320 ;;
1321 (define module-type
1322 (make-record-type 'module
1323 '(obarray uses binder eval-closure transformer name kind
1324 observers weak-observers observer-id)
1325 %print-module))
1326
1327 ;; make-module &opt size uses binder
1328 ;;
1329 ;; Create a new module, perhaps with a particular size of obarray,
1330 ;; initial uses list, or binding procedure.
1331 ;;
1332 (define make-module
1333 (lambda args
1334
1335 (define (parse-arg index default)
1336 (if (> (length args) index)
1337 (list-ref args index)
1338 default))
1339
1340 (if (> (length args) 3)
1341 (error "Too many args to make-module." args))
1342
1343 (let ((size (parse-arg 0 1021))
1344 (uses (parse-arg 1 '()))
1345 (binder (parse-arg 2 #f)))
1346
1347 (if (not (integer? size))
1348 (error "Illegal size to make-module." size))
1349 (if (not (and (list? uses)
1350 (and-map module? uses)))
1351 (error "Incorrect use list." uses))
1352 (if (and binder (not (procedure? binder)))
1353 (error
1354 "Lazy-binder expected to be a procedure or #f." binder))
1355
1356 (let ((module (module-constructor (make-vector size '())
1357 uses binder #f #f #f #f
1358 '()
1359 (make-weak-value-hash-table 31)
1360 0)))
1361
1362 ;; We can't pass this as an argument to module-constructor,
1363 ;; because we need it to close over a pointer to the module
1364 ;; itself.
1365 (set-module-eval-closure! module
1366 (lambda (symbol define?)
1367 (if define?
1368 (module-make-local-var! module symbol)
1369 (module-variable module symbol))))
1370
1371 module))))
1372
1373 (define module-constructor (record-constructor module-type))
1374 (define module-obarray (record-accessor module-type 'obarray))
1375 (define set-module-obarray! (record-modifier module-type 'obarray))
1376 (define module-uses (record-accessor module-type 'uses))
1377 (define set-module-uses! (record-modifier module-type 'uses))
1378 (define module-binder (record-accessor module-type 'binder))
1379 (define set-module-binder! (record-modifier module-type 'binder))
1380
1381 ;; NOTE: This binding is used in libguile/modules.c.
1382 (define module-eval-closure (record-accessor module-type 'eval-closure))
1383
1384 (define module-transformer (record-accessor module-type 'transformer))
1385 (define set-module-transformer! (record-modifier module-type 'transformer))
1386 (define module-name (record-accessor module-type 'name))
1387 (define set-module-name! (record-modifier module-type 'name))
1388 (define module-kind (record-accessor module-type 'kind))
1389 (define set-module-kind! (record-modifier module-type 'kind))
1390 (define module-observers (record-accessor module-type 'observers))
1391 (define set-module-observers! (record-modifier module-type 'observers))
1392 (define module-weak-observers (record-accessor module-type 'weak-observers))
1393 (define module-observer-id (record-accessor module-type 'observer-id))
1394 (define set-module-observer-id! (record-modifier module-type 'observer-id))
1395 (define module? (record-predicate module-type))
1396
1397 (define set-module-eval-closure!
1398 (let ((setter (record-modifier module-type 'eval-closure)))
1399 (lambda (module closure)
1400 (setter module closure)
1401 ;; Make it possible to lookup the module from the environment.
1402 ;; This implementation is correct since an eval closure can belong
1403 ;; to maximally one module.
1404 (set-procedure-property! closure 'module module))))
1405
1406 (define (eval-in-module exp module)
1407 (eval2 exp (module-eval-closure module)))
1408
1409 \f
1410 ;;; {Observer protocol}
1411 ;;;
1412
1413 (define (module-observe module proc)
1414 (set-module-observers! module (cons proc (module-observers module)))
1415 (cons module proc))
1416
1417 (define (module-observe-weak module proc)
1418 (let ((id (module-observer-id module)))
1419 (hash-set! (module-weak-observers module) id proc)
1420 (set-module-observer-id! module (+ 1 id))
1421 (cons module id)))
1422
1423 (define (module-unobserve token)
1424 (let ((module (car token))
1425 (id (cdr token)))
1426 (if (integer? id)
1427 (hash-remove! (module-weak-observers module) id)
1428 (set-module-observers! module (delq1! id (module-observers module)))))
1429 *unspecified*)
1430
1431 (define (module-modified! m)
1432 (for-each (lambda (proc) (proc m)) (module-observers m))
1433 (hash-fold (lambda (id proc res) (proc m)) #f (module-weak-observers m)))
1434
1435 \f
1436 ;;; {Module Searching in General}
1437 ;;;
1438 ;;; We sometimes want to look for properties of a symbol
1439 ;;; just within the obarray of one module. If the property
1440 ;;; holds, then it is said to hold ``locally'' as in, ``The symbol
1441 ;;; DISPLAY is locally rebound in the module `safe-guile'.''
1442 ;;;
1443 ;;;
1444 ;;; Other times, we want to test for a symbol property in the obarray
1445 ;;; of M and, if it is not found there, try each of the modules in the
1446 ;;; uses list of M. This is the normal way of testing for some
1447 ;;; property, so we state these properties without qualification as
1448 ;;; in: ``The symbol 'fnord is interned in module M because it is
1449 ;;; interned locally in module M2 which is a member of the uses list
1450 ;;; of M.''
1451 ;;;
1452
1453 ;; module-search fn m
1454 ;;
1455 ;; return the first non-#f result of FN applied to M and then to
1456 ;; the modules in the uses of m, and so on recursively. If all applications
1457 ;; return #f, then so does this function.
1458 ;;
1459 (define (module-search fn m v)
1460 (define (loop pos)
1461 (and (pair? pos)
1462 (or (module-search fn (car pos) v)
1463 (loop (cdr pos)))))
1464 (or (fn m v)
1465 (loop (module-uses m))))
1466
1467
1468 ;;; {Is a symbol bound in a module?}
1469 ;;;
1470 ;;; Symbol S in Module M is bound if S is interned in M and if the binding
1471 ;;; of S in M has been set to some well-defined value.
1472 ;;;
1473
1474 ;; module-locally-bound? module symbol
1475 ;;
1476 ;; Is a symbol bound (interned and defined) locally in a given module?
1477 ;;
1478 (define (module-locally-bound? m v)
1479 (let ((var (module-local-variable m v)))
1480 (and var
1481 (variable-bound? var))))
1482
1483 ;; module-bound? module symbol
1484 ;;
1485 ;; Is a symbol bound (interned and defined) anywhere in a given module
1486 ;; or its uses?
1487 ;;
1488 (define (module-bound? m v)
1489 (module-search module-locally-bound? m v))
1490
1491 ;;; {Is a symbol interned in a module?}
1492 ;;;
1493 ;;; Symbol S in Module M is interned if S occurs in
1494 ;;; of S in M has been set to some well-defined value.
1495 ;;;
1496 ;;; It is possible to intern a symbol in a module without providing
1497 ;;; an initial binding for the corresponding variable. This is done
1498 ;;; with:
1499 ;;; (module-add! module symbol (make-undefined-variable))
1500 ;;;
1501 ;;; In that case, the symbol is interned in the module, but not
1502 ;;; bound there. The unbound symbol shadows any binding for that
1503 ;;; symbol that might otherwise be inherited from a member of the uses list.
1504 ;;;
1505
1506 (define (module-obarray-get-handle ob key)
1507 ((if (symbol? key) hashq-get-handle hash-get-handle) ob key))
1508
1509 (define (module-obarray-ref ob key)
1510 ((if (symbol? key) hashq-ref hash-ref) ob key))
1511
1512 (define (module-obarray-set! ob key val)
1513 ((if (symbol? key) hashq-set! hash-set!) ob key val))
1514
1515 (define (module-obarray-remove! ob key)
1516 ((if (symbol? key) hashq-remove! hash-remove!) ob key))
1517
1518 ;; module-symbol-locally-interned? module symbol
1519 ;;
1520 ;; is a symbol interned (not neccessarily defined) locally in a given module
1521 ;; or its uses? Interned symbols shadow inherited bindings even if
1522 ;; they are not themselves bound to a defined value.
1523 ;;
1524 (define (module-symbol-locally-interned? m v)
1525 (not (not (module-obarray-get-handle (module-obarray m) v))))
1526
1527 ;; module-symbol-interned? module symbol
1528 ;;
1529 ;; is a symbol interned (not neccessarily defined) anywhere in a given module
1530 ;; or its uses? Interned symbols shadow inherited bindings even if
1531 ;; they are not themselves bound to a defined value.
1532 ;;
1533 (define (module-symbol-interned? m v)
1534 (module-search module-symbol-locally-interned? m v))
1535
1536
1537 ;;; {Mapping modules x symbols --> variables}
1538 ;;;
1539
1540 ;; module-local-variable module symbol
1541 ;; return the local variable associated with a MODULE and SYMBOL.
1542 ;;
1543 ;;; This function is very important. It is the only function that can
1544 ;;; return a variable from a module other than the mutators that store
1545 ;;; new variables in modules. Therefore, this function is the location
1546 ;;; of the "lazy binder" hack.
1547 ;;;
1548 ;;; If symbol is defined in MODULE, and if the definition binds symbol
1549 ;;; to a variable, return that variable object.
1550 ;;;
1551 ;;; If the symbols is not found at first, but the module has a lazy binder,
1552 ;;; then try the binder.
1553 ;;;
1554 ;;; If the symbol is not found at all, return #f.
1555 ;;;
1556 (define (module-local-variable m v)
1557 ; (caddr
1558 ; (list m v
1559 (let ((b (module-obarray-ref (module-obarray m) v)))
1560 (or (and (variable? b) b)
1561 (and (module-binder m)
1562 ((module-binder m) m v #f)))))
1563 ;))
1564
1565 ;; module-variable module symbol
1566 ;;
1567 ;; like module-local-variable, except search the uses in the
1568 ;; case V is not found in M.
1569 ;;
1570 (define (module-variable m v)
1571 (module-search module-local-variable m v))
1572
1573
1574 ;;; {Mapping modules x symbols --> bindings}
1575 ;;;
1576 ;;; These are similar to the mapping to variables, except that the
1577 ;;; variable is dereferenced.
1578 ;;;
1579
1580 ;; module-symbol-binding module symbol opt-value
1581 ;;
1582 ;; return the binding of a variable specified by name within
1583 ;; a given module, signalling an error if the variable is unbound.
1584 ;; If the OPT-VALUE is passed, then instead of signalling an error,
1585 ;; return OPT-VALUE.
1586 ;;
1587 (define (module-symbol-local-binding m v . opt-val)
1588 (let ((var (module-local-variable m v)))
1589 (if var
1590 (variable-ref var)
1591 (if (not (null? opt-val))
1592 (car opt-val)
1593 (error "Locally unbound variable." v)))))
1594
1595 ;; module-symbol-binding module symbol opt-value
1596 ;;
1597 ;; return the binding of a variable specified by name within
1598 ;; a given module, signalling an error if the variable is unbound.
1599 ;; If the OPT-VALUE is passed, then instead of signalling an error,
1600 ;; return OPT-VALUE.
1601 ;;
1602 (define (module-symbol-binding m v . opt-val)
1603 (let ((var (module-variable m v)))
1604 (if var
1605 (variable-ref var)
1606 (if (not (null? opt-val))
1607 (car opt-val)
1608 (error "Unbound variable." v)))))
1609
1610
1611 \f
1612 ;;; {Adding Variables to Modules}
1613 ;;;
1614 ;;;
1615
1616
1617 ;; module-make-local-var! module symbol
1618 ;;
1619 ;; ensure a variable for V in the local namespace of M.
1620 ;; If no variable was already there, then create a new and uninitialzied
1621 ;; variable.
1622 ;;
1623 (define (module-make-local-var! m v)
1624 (or (let ((b (module-obarray-ref (module-obarray m) v)))
1625 (and (variable? b)
1626 (begin
1627 (module-modified! m)
1628 b)))
1629 (and (module-binder m)
1630 ((module-binder m) m v #t))
1631 (begin
1632 (let ((answer (make-undefined-variable v)))
1633 (module-obarray-set! (module-obarray m) v answer)
1634 (module-modified! m)
1635 answer))))
1636
1637 ;; module-add! module symbol var
1638 ;;
1639 ;; ensure a particular variable for V in the local namespace of M.
1640 ;;
1641 (define (module-add! m v var)
1642 (if (not (variable? var))
1643 (error "Bad variable to module-add!" var))
1644 (module-obarray-set! (module-obarray m) v var)
1645 (module-modified! m))
1646
1647 ;; module-remove!
1648 ;;
1649 ;; make sure that a symbol is undefined in the local namespace of M.
1650 ;;
1651 (define (module-remove! m v)
1652 (module-obarray-remove! (module-obarray m) v)
1653 (module-modified! m))
1654
1655 (define (module-clear! m)
1656 (vector-fill! (module-obarray m) '())
1657 (module-modified! m))
1658
1659 ;; MODULE-FOR-EACH -- exported
1660 ;;
1661 ;; Call PROC on each symbol in MODULE, with arguments of (SYMBOL VARIABLE).
1662 ;;
1663 (define (module-for-each proc module)
1664 (let ((obarray (module-obarray module)))
1665 (do ((index 0 (+ index 1))
1666 (end (vector-length obarray)))
1667 ((= index end))
1668 (for-each
1669 (lambda (bucket)
1670 (proc (car bucket) (cdr bucket)))
1671 (vector-ref obarray index)))))
1672
1673
1674 (define (module-map proc module)
1675 (let* ((obarray (module-obarray module))
1676 (end (vector-length obarray)))
1677
1678 (let loop ((i 0)
1679 (answer '()))
1680 (if (= i end)
1681 answer
1682 (loop (+ 1 i)
1683 (append!
1684 (map (lambda (bucket)
1685 (proc (car bucket) (cdr bucket)))
1686 (vector-ref obarray i))
1687 answer))))))
1688 \f
1689
1690 ;;; {Low Level Bootstrapping}
1691 ;;;
1692
1693 ;; make-root-module
1694
1695 ;; A root module uses the symhash table (the system's privileged
1696 ;; obarray). Being inside a root module is like using SCM without
1697 ;; any module system.
1698 ;;
1699
1700
1701 (define (root-module-closure m s define?)
1702 (let ((bi (and (symbol-interned? #f s)
1703 (builtin-variable s))))
1704 (and bi
1705 (or define? (variable-bound? bi))
1706 (begin
1707 (module-add! m s bi)
1708 bi))))
1709
1710 (define (make-root-module)
1711 (make-module 1019 '() root-module-closure))
1712
1713
1714 ;; make-scm-module
1715
1716 ;; An scm module is a module into which the lazy binder copies
1717 ;; variable bindings from the system symhash table. The mapping is
1718 ;; one way only; newly introduced bindings in an scm module are not
1719 ;; copied back into the system symhash table (and can be used to override
1720 ;; bindings from the symhash table).
1721 ;;
1722
1723 (define (make-scm-module)
1724 (make-module 1019 '()
1725 (lambda (m s define?)
1726 (let ((bi (and (symbol-interned? #f s)
1727 (builtin-variable s))))
1728 (and bi
1729 (variable-bound? bi)
1730 (begin
1731 (module-add! m s bi)
1732 bi))))))
1733
1734
1735
1736
1737 ;; the-module
1738 ;;
1739 ;; NOTE: This binding is used in libguile/modules.c.
1740 ;;
1741 (define the-module #f)
1742
1743 ;; scm:eval-transformer
1744 ;;
1745 (define scm:eval-transformer #f)
1746
1747 ;; set-current-module module
1748 ;;
1749 ;; set the current module as viewed by the normalizer.
1750 ;;
1751 ;; NOTE: This binding is used in libguile/modules.c.
1752 ;;
1753 (define (set-current-module m)
1754 (set! the-module m)
1755 (if m
1756 (begin
1757 (set! *top-level-lookup-closure* (module-eval-closure the-module))
1758 (set! scm:eval-transformer (module-transformer the-module)))
1759 (set! *top-level-lookup-closure* #f)))
1760
1761
1762 ;; current-module
1763 ;;
1764 ;; return the current module as viewed by the normalizer.
1765 ;;
1766 (define (current-module) the-module)
1767 \f
1768 ;;; {Module-based Loading}
1769 ;;;
1770
1771 (define (save-module-excursion thunk)
1772 (let ((inner-module (current-module))
1773 (outer-module #f))
1774 (dynamic-wind (lambda ()
1775 (set! outer-module (current-module))
1776 (set-current-module inner-module)
1777 (set! inner-module #f))
1778 thunk
1779 (lambda ()
1780 (set! inner-module (current-module))
1781 (set-current-module outer-module)
1782 (set! outer-module #f)))))
1783
1784 (define basic-load load)
1785
1786 (define (load-module filename)
1787 (save-module-excursion
1788 (lambda ()
1789 (let ((oldname (and (current-load-port)
1790 (port-filename (current-load-port)))))
1791 (basic-load (if (and oldname
1792 (> (string-length filename) 0)
1793 (not (char=? (string-ref filename 0) #\/))
1794 (not (string=? (dirname oldname) ".")))
1795 (string-append (dirname oldname) "/" filename)
1796 filename))))))
1797
1798
1799 \f
1800 ;;; {MODULE-REF -- exported}
1801 ;;
1802 ;; Returns the value of a variable called NAME in MODULE or any of its
1803 ;; used modules. If there is no such variable, then if the optional third
1804 ;; argument DEFAULT is present, it is returned; otherwise an error is signaled.
1805 ;;
1806 (define (module-ref module name . rest)
1807 (let ((variable (module-variable module name)))
1808 (if (and variable (variable-bound? variable))
1809 (variable-ref variable)
1810 (if (null? rest)
1811 (error "No variable named" name 'in module)
1812 (car rest) ; default value
1813 ))))
1814
1815 ;; MODULE-SET! -- exported
1816 ;;
1817 ;; Sets the variable called NAME in MODULE (or in a module that MODULE uses)
1818 ;; to VALUE; if there is no such variable, an error is signaled.
1819 ;;
1820 (define (module-set! module name value)
1821 (let ((variable (module-variable module name)))
1822 (if variable
1823 (variable-set! variable value)
1824 (error "No variable named" name 'in module))))
1825
1826 ;; MODULE-DEFINE! -- exported
1827 ;;
1828 ;; Sets the variable called NAME in MODULE to VALUE; if there is no such
1829 ;; variable, it is added first.
1830 ;;
1831 (define (module-define! module name value)
1832 (let ((variable (module-local-variable module name)))
1833 (if variable
1834 (begin
1835 (variable-set! variable value)
1836 (module-modified! module))
1837 (module-add! module name (make-variable value name)))))
1838
1839 ;; MODULE-DEFINED? -- exported
1840 ;;
1841 ;; Return #t iff NAME is defined in MODULE (or in a module that MODULE
1842 ;; uses)
1843 ;;
1844 (define (module-defined? module name)
1845 (let ((variable (module-variable module name)))
1846 (and variable (variable-bound? variable))))
1847
1848 ;; MODULE-USE! module interface
1849 ;;
1850 ;; Add INTERFACE to the list of interfaces used by MODULE.
1851 ;;
1852 (define (module-use! module interface)
1853 (set-module-uses! module
1854 (cons interface (delq! interface (module-uses module))))
1855 (module-modified! module))
1856
1857 \f
1858 ;;; {Recursive Namespaces}
1859 ;;;
1860 ;;;
1861 ;;; A hierarchical namespace emerges if we consider some module to be
1862 ;;; root, and variables bound to modules as nested namespaces.
1863 ;;;
1864 ;;; The routines in this file manage variable names in hierarchical namespace.
1865 ;;; Each variable name is a list of elements, looked up in successively nested
1866 ;;; modules.
1867 ;;;
1868 ;;; (nested-ref some-root-module '(foo bar baz))
1869 ;;; => <value of a variable named baz in the module bound to bar in
1870 ;;; the module bound to foo in some-root-module>
1871 ;;;
1872 ;;;
1873 ;;; There are:
1874 ;;;
1875 ;;; ;; a-root is a module
1876 ;;; ;; name is a list of symbols
1877 ;;;
1878 ;;; nested-ref a-root name
1879 ;;; nested-set! a-root name val
1880 ;;; nested-define! a-root name val
1881 ;;; nested-remove! a-root name
1882 ;;;
1883 ;;;
1884 ;;; (current-module) is a natural choice for a-root so for convenience there are
1885 ;;; also:
1886 ;;;
1887 ;;; local-ref name == nested-ref (current-module) name
1888 ;;; local-set! name val == nested-set! (current-module) name val
1889 ;;; local-define! name val == nested-define! (current-module) name val
1890 ;;; local-remove! name == nested-remove! (current-module) name
1891 ;;;
1892
1893
1894 (define (nested-ref root names)
1895 (let loop ((cur root)
1896 (elts names))
1897 (cond
1898 ((null? elts) cur)
1899 ((not (module? cur)) #f)
1900 (else (loop (module-ref cur (car elts) #f) (cdr elts))))))
1901
1902 (define (nested-set! root names val)
1903 (let loop ((cur root)
1904 (elts names))
1905 (if (null? (cdr elts))
1906 (module-set! cur (car elts) val)
1907 (loop (module-ref cur (car elts)) (cdr elts)))))
1908
1909 (define (nested-define! root names val)
1910 (let loop ((cur root)
1911 (elts names))
1912 (if (null? (cdr elts))
1913 (module-define! cur (car elts) val)
1914 (loop (module-ref cur (car elts)) (cdr elts)))))
1915
1916 (define (nested-remove! root names)
1917 (let loop ((cur root)
1918 (elts names))
1919 (if (null? (cdr elts))
1920 (module-remove! cur (car elts))
1921 (loop (module-ref cur (car elts)) (cdr elts)))))
1922
1923 (define (local-ref names) (nested-ref (current-module) names))
1924 (define (local-set! names val) (nested-set! (current-module) names val))
1925 (define (local-define names val) (nested-define! (current-module) names val))
1926 (define (local-remove names) (nested-remove! (current-module) names))
1927
1928
1929 \f
1930 ;;; {The (app) module}
1931 ;;;
1932 ;;; The root of conventionally named objects not directly in the top level.
1933 ;;;
1934 ;;; (app modules)
1935 ;;; (app modules guile)
1936 ;;;
1937 ;;; The directory of all modules and the standard root module.
1938 ;;;
1939
1940 (define (module-public-interface m)
1941 (module-ref m '%module-public-interface #f))
1942 (define (set-module-public-interface! m i)
1943 (module-define! m '%module-public-interface i))
1944 (define (set-system-module! m s)
1945 (set-procedure-property! (module-eval-closure m) 'system-module s))
1946 (define the-root-module (make-root-module))
1947 (define the-scm-module (make-scm-module))
1948 (set-module-public-interface! the-root-module the-scm-module)
1949 (set-module-name! the-root-module 'the-root-module)
1950 (set-module-name! the-scm-module 'the-scm-module)
1951 (for-each set-system-module! (list the-root-module the-scm-module) '(#t #t))
1952
1953 (set-current-module the-root-module)
1954
1955 (define app (make-module 31))
1956 (local-define '(app modules) (make-module 31))
1957 (local-define '(app modules guile) the-root-module)
1958
1959 ;; (define-special-value '(app modules new-ws) (lambda () (make-scm-module)))
1960
1961 (define (try-load-module name)
1962 (or (try-module-linked name)
1963 (try-module-autoload name)
1964 (try-module-dynamic-link name)))
1965
1966 ;; NOTE: This binding is used in libguile/modules.c.
1967 ;;
1968 (define (resolve-module name . maybe-autoload)
1969 (let ((full-name (append '(app modules) name)))
1970 (let ((already (local-ref full-name)))
1971 (if already
1972 ;; The module already exists...
1973 (if (and (or (null? maybe-autoload) (car maybe-autoload))
1974 (not (module-ref already '%module-public-interface #f)))
1975 ;; ...but we are told to load and it doesn't contain source, so
1976 (begin
1977 (try-load-module name)
1978 already)
1979 ;; simply return it.
1980 already)
1981 (begin
1982 ;; Try to autoload it if we are told so
1983 (if (or (null? maybe-autoload) (car maybe-autoload))
1984 (try-load-module name))
1985 ;; Get/create it.
1986 (make-modules-in (current-module) full-name))))))
1987
1988 (define (beautify-user-module! module)
1989 (let ((interface (module-public-interface module)))
1990 (if (or (not interface)
1991 (eq? interface module))
1992 (let ((interface (make-module 31)))
1993 (set-module-name! interface (module-name module))
1994 (set-module-kind! interface 'interface)
1995 (set-module-public-interface! module interface))))
1996 (if (and (not (memq the-scm-module (module-uses module)))
1997 (not (eq? module the-root-module)))
1998 (set-module-uses! module (append (module-uses module) (list the-scm-module)))))
1999
2000 ;; NOTE: This binding is used in libguile/modules.c.
2001 ;;
2002 (define (make-modules-in module name)
2003 (if (null? name)
2004 module
2005 (cond
2006 ((module-ref module (car name) #f)
2007 => (lambda (m) (make-modules-in m (cdr name))))
2008 (else (let ((m (make-module 31)))
2009 (set-module-kind! m 'directory)
2010 (set-module-name! m (car name))
2011 (module-define! module (car name) m)
2012 (make-modules-in m (cdr name)))))))
2013
2014 (define (resolve-interface name)
2015 (let ((module (resolve-module name)))
2016 (and module (module-public-interface module))))
2017
2018
2019 (define %autoloader-developer-mode #t)
2020
2021 (define (process-define-module args)
2022 (let* ((module-id (car args))
2023 (module (resolve-module module-id #f))
2024 (kws (cdr args)))
2025 (beautify-user-module! module)
2026 (let loop ((kws kws)
2027 (reversed-interfaces '()))
2028 (if (null? kws)
2029 (for-each (lambda (interface)
2030 (module-use! module interface))
2031 reversed-interfaces)
2032 (let ((keyword (cond ((keyword? (car kws))
2033 (keyword->symbol (car kws)))
2034 ((and (symbol? (car kws))
2035 (eq? (string-ref (car kws) 0) #\:))
2036 (string->symbol (substring (car kws) 1)))
2037 (else #f))))
2038 (case keyword
2039 ((use-module use-syntax)
2040 (if (not (pair? (cdr kws)))
2041 (error "unrecognized defmodule argument" kws))
2042 (let* ((used-name (cadr kws))
2043 (used-module (resolve-module used-name)))
2044 (if (not (module-ref used-module
2045 '%module-public-interface
2046 #f))
2047 (begin
2048 ((if %autoloader-developer-mode warn error)
2049 "no code for module" (module-name used-module))
2050 (beautify-user-module! used-module)))
2051 (let ((interface (module-public-interface used-module)))
2052 (if (not interface)
2053 (error "missing interface for use-module"
2054 used-module))
2055 (if (eq? keyword 'use-syntax)
2056 (set-module-transformer!
2057 module
2058 (module-ref interface (car (last-pair used-name))
2059 #f)))
2060 (loop (cddr kws)
2061 (cons interface reversed-interfaces)))))
2062 ((autoload)
2063 (if (not (and (pair? (cdr kws)) (pair? (cddr kws))))
2064 (error "unrecognized defmodule argument" kws))
2065 (loop (cdddr kws)
2066 (cons (make-autoload-interface module
2067 (cadr kws)
2068 (caddr kws))
2069 reversed-interfaces)))
2070 ((no-backtrace)
2071 (set-system-module! module #t)
2072 (loop (cdr kws) reversed-interfaces))
2073 (else
2074 (error "unrecognized defmodule argument" kws))))))
2075 module))
2076
2077 ;;; {Autoload}
2078
2079 (define (make-autoload-interface module name bindings)
2080 (let ((b (lambda (a sym definep)
2081 (and (memq sym bindings)
2082 (let ((i (module-public-interface (resolve-module name))))
2083 (if (not i)
2084 (error "missing interface for module" name))
2085 ;; Replace autoload-interface with interface
2086 (set-car! (memq a (module-uses module)) i)
2087 (module-local-variable i sym))))))
2088 (module-constructor #() #f b #f #f name 'autoload)))
2089
2090 \f
2091 ;;; {Autoloading modules}
2092
2093 (define autoloads-in-progress '())
2094
2095 (define (try-module-autoload module-name)
2096
2097 (define (sfx name) (string-append name (scheme-file-suffix)))
2098 (let* ((reverse-name (reverse module-name))
2099 (name (car reverse-name))
2100 (dir-hint-module-name (reverse (cdr reverse-name)))
2101 (dir-hint (apply symbol-append (map (lambda (elt) (symbol-append elt "/")) dir-hint-module-name))))
2102 (resolve-module dir-hint-module-name #f)
2103 (and (not (autoload-done-or-in-progress? dir-hint name))
2104 (let ((didit #f))
2105 (dynamic-wind
2106 (lambda () (autoload-in-progress! dir-hint name))
2107 (lambda ()
2108 (let loop ((dirs %load-path))
2109 (and (not (null? dirs))
2110 (or
2111 (let ((d (car dirs))
2112 (trys (list
2113 dir-hint
2114 (sfx dir-hint)
2115 (in-vicinity dir-hint name)
2116 (in-vicinity dir-hint (sfx name)))))
2117 (and (or-map (lambda (f)
2118 (let ((full (in-vicinity d f)))
2119 full
2120 (and (file-exists? full)
2121 (not (file-is-directory? full))
2122 (begin
2123 (save-module-excursion
2124 (lambda ()
2125 (load (string-append
2126 d "/" f))))
2127 #t))))
2128 trys)
2129 (begin
2130 (set! didit #t)
2131 #t)))
2132 (loop (cdr dirs))))))
2133 (lambda () (set-autoloaded! dir-hint name didit)))
2134 didit))))
2135
2136 \f
2137 ;;; Dynamic linking of modules
2138
2139 ;; Initializing a module that is written in C is a two step process.
2140 ;; First the module's `module init' function is called. This function
2141 ;; is expected to call `scm_register_module_xxx' to register the `real
2142 ;; init' function. Later, when the module is referenced for the first
2143 ;; time, this real init function is called in the right context. See
2144 ;; gtcltk-lib/gtcltk-module.c for an example.
2145 ;;
2146 ;; The code for the module can be in a regular shared library (so that
2147 ;; the `module init' function will be called when libguile is
2148 ;; initialized). Or it can be dynamically linked.
2149 ;;
2150 ;; You can safely call `scm_register_module_xxx' before libguile
2151 ;; itself is initialized. You could call it from an C++ constructor
2152 ;; of a static object, for example.
2153 ;;
2154 ;; To make your Guile extension into a dynamic linkable module, follow
2155 ;; these easy steps:
2156 ;;
2157 ;; - Find a name for your module, like (ice-9 gtcltk)
2158 ;; - Write a function with a name like
2159 ;;
2160 ;; scm_init_ice_9_gtcltk_module
2161 ;;
2162 ;; This is your `module init' function. It should call
2163 ;;
2164 ;; scm_register_module_xxx ("ice-9 gtcltk", scm_init_gtcltk);
2165 ;;
2166 ;; "ice-9 gtcltk" is the C version of the module name. Slashes are
2167 ;; replaced by spaces, the rest is untouched. `scm_init_gtcltk' is
2168 ;; the real init function that executes the usual initializations
2169 ;; like making new smobs, etc.
2170 ;;
2171 ;; - Make a shared library with your code and a name like
2172 ;;
2173 ;; ice-9/libgtcltk.so
2174 ;;
2175 ;; and put it somewhere in %load-path.
2176 ;;
2177 ;; - Then you can simply write `:use-module (ice-9 gtcltk)' and it
2178 ;; will be linked automatically.
2179 ;;
2180 ;; This is all very experimental.
2181
2182 (define (split-c-module-name str)
2183 (let loop ((rev '())
2184 (start 0)
2185 (pos 0)
2186 (end (string-length str)))
2187 (cond
2188 ((= pos end)
2189 (reverse (cons (string->symbol (substring str start pos)) rev)))
2190 ((eq? (string-ref str pos) #\space)
2191 (loop (cons (string->symbol (substring str start pos)) rev)
2192 (+ pos 1)
2193 (+ pos 1)
2194 end))
2195 (else
2196 (loop rev start (+ pos 1) end)))))
2197
2198 (define (convert-c-registered-modules dynobj)
2199 (let ((res (map (lambda (c)
2200 (list (split-c-module-name (car c)) (cdr c) dynobj))
2201 (c-registered-modules))))
2202 (c-clear-registered-modules)
2203 res))
2204
2205 (define registered-modules '())
2206
2207 (define (register-modules dynobj)
2208 (set! registered-modules
2209 (append! (convert-c-registered-modules dynobj)
2210 registered-modules)))
2211
2212 (define (init-dynamic-module modname)
2213 ;; Register any linked modules which has been registered on the C level
2214 (register-modules #f)
2215 (or-map (lambda (modinfo)
2216 (if (equal? (car modinfo) modname)
2217 (begin
2218 (set! registered-modules (delq! modinfo registered-modules))
2219 (let ((mod (resolve-module modname #f)))
2220 (save-module-excursion
2221 (lambda ()
2222 (set-current-module mod)
2223 (set-module-public-interface! mod mod)
2224 (dynamic-call (cadr modinfo) (caddr modinfo))
2225 ))
2226 #t))
2227 #f))
2228 registered-modules))
2229
2230 (define (dynamic-maybe-call name dynobj)
2231 (catch #t ; could use false-if-exception here
2232 (lambda ()
2233 (dynamic-call name dynobj))
2234 (lambda args
2235 #f)))
2236
2237 (define (dynamic-maybe-link filename)
2238 (catch #t ; could use false-if-exception here
2239 (lambda ()
2240 (dynamic-link filename))
2241 (lambda args
2242 #f)))
2243
2244 (define (find-and-link-dynamic-module module-name)
2245 (define (make-init-name mod-name)
2246 (string-append 'scm_init
2247 (list->string (map (lambda (c)
2248 (if (or (char-alphabetic? c)
2249 (char-numeric? c))
2250 c
2251 #\_))
2252 (string->list mod-name)))
2253 '_module))
2254
2255 ;; Put the subdirectory for this module in the car of SUBDIR-AND-LIBNAME,
2256 ;; and the `libname' (the name of the module prepended by `lib') in the cdr
2257 ;; field. For example, if MODULE-NAME is the list (inet tcp-ip udp), then
2258 ;; SUBDIR-AND-LIBNAME will be the pair ("inet/tcp-ip" . "libudp").
2259 (let ((subdir-and-libname
2260 (let loop ((dirs "")
2261 (syms module-name))
2262 (if (null? (cdr syms))
2263 (cons dirs (string-append "lib" (car syms)))
2264 (loop (string-append dirs (car syms) "/") (cdr syms)))))
2265 (init (make-init-name (apply string-append
2266 (map (lambda (s)
2267 (string-append "_" s))
2268 module-name)))))
2269 (let ((subdir (car subdir-and-libname))
2270 (libname (cdr subdir-and-libname)))
2271
2272 ;; Now look in each dir in %LOAD-PATH for `subdir/libfoo.la'. If that
2273 ;; file exists, fetch the dlname from that file and attempt to link
2274 ;; against it. If `subdir/libfoo.la' does not exist, or does not seem
2275 ;; to name any shared library, look for `subdir/libfoo.so' instead and
2276 ;; link against that.
2277 (let check-dirs ((dir-list %load-path))
2278 (if (null? dir-list)
2279 #f
2280 (let* ((dir (in-vicinity (car dir-list) subdir))
2281 (sharlib-full
2282 (or (try-using-libtool-name dir libname)
2283 (try-using-sharlib-name dir libname))))
2284 (if (and sharlib-full (file-exists? sharlib-full))
2285 (link-dynamic-module sharlib-full init)
2286 (check-dirs (cdr dir-list)))))))))
2287
2288 (define (try-using-libtool-name libdir libname)
2289 (let ((libtool-filename (in-vicinity libdir
2290 (string-append libname ".la"))))
2291 (and (file-exists? libtool-filename)
2292 (with-input-from-file libtool-filename
2293 (lambda ()
2294 (let loop ((ln (read-line)))
2295 (cond ((eof-object? ln) #f)
2296 ((and (> (string-length ln) 9)
2297 (string=? "dlname='" (substring ln 0 8))
2298 (string-index ln #\' 8))
2299 =>
2300 (lambda (end)
2301 (in-vicinity libdir (substring ln 8 end))))
2302 (else (loop (read-line))))))))))
2303
2304 (define (try-using-sharlib-name libdir libname)
2305 (in-vicinity libdir (string-append libname ".so")))
2306
2307 (define (link-dynamic-module filename initname)
2308 ;; Register any linked modules which has been registered on the C level
2309 (register-modules #f)
2310 (let ((dynobj (dynamic-link filename)))
2311 (dynamic-call initname dynobj)
2312 (register-modules dynobj)))
2313
2314 (define (try-module-linked module-name)
2315 (init-dynamic-module module-name))
2316
2317 (define (try-module-dynamic-link module-name)
2318 (and (find-and-link-dynamic-module module-name)
2319 (init-dynamic-module module-name)))
2320
2321
2322
2323 (define autoloads-done '((guile . guile)))
2324
2325 (define (autoload-done-or-in-progress? p m)
2326 (let ((n (cons p m)))
2327 (->bool (or (member n autoloads-done)
2328 (member n autoloads-in-progress)))))
2329
2330 (define (autoload-done! p m)
2331 (let ((n (cons p m)))
2332 (set! autoloads-in-progress
2333 (delete! n autoloads-in-progress))
2334 (or (member n autoloads-done)
2335 (set! autoloads-done (cons n autoloads-done)))))
2336
2337 (define (autoload-in-progress! p m)
2338 (let ((n (cons p m)))
2339 (set! autoloads-done
2340 (delete! n autoloads-done))
2341 (set! autoloads-in-progress (cons n autoloads-in-progress))))
2342
2343 (define (set-autoloaded! p m done?)
2344 (if done?
2345 (autoload-done! p m)
2346 (let ((n (cons p m)))
2347 (set! autoloads-done (delete! n autoloads-done))
2348 (set! autoloads-in-progress (delete! n autoloads-in-progress)))))
2349
2350
2351
2352
2353 \f
2354 ;;; {Macros}
2355 ;;;
2356
2357 (define (primitive-macro? m)
2358 (and (macro? m)
2359 (not (macro-transformer m))))
2360
2361 ;;; {Defmacros}
2362 ;;;
2363 (define macro-table (make-weak-key-hash-table 523))
2364 (define xformer-table (make-weak-key-hash-table 523))
2365
2366 (define (defmacro? m) (hashq-ref macro-table m))
2367 (define (assert-defmacro?! m) (hashq-set! macro-table m #t))
2368 (define (defmacro-transformer m) (hashq-ref xformer-table m))
2369 (define (set-defmacro-transformer! m t) (hashq-set! xformer-table m t))
2370
2371 (define defmacro:transformer
2372 (lambda (f)
2373 (let* ((xform (lambda (exp env)
2374 (copy-tree (apply f (cdr exp)))))
2375 (a (procedure->memoizing-macro xform)))
2376 (assert-defmacro?! a)
2377 (set-defmacro-transformer! a f)
2378 a)))
2379
2380
2381 (define defmacro
2382 (let ((defmacro-transformer
2383 (lambda (name parms . body)
2384 (let ((transformer `(lambda ,parms ,@body)))
2385 `(define ,name
2386 (,(lambda (transformer)
2387 (defmacro:transformer transformer))
2388 ,transformer))))))
2389 (defmacro:transformer defmacro-transformer)))
2390
2391 (define defmacro:syntax-transformer
2392 (lambda (f)
2393 (procedure->syntax
2394 (lambda (exp env)
2395 (copy-tree (apply f (cdr exp)))))))
2396
2397
2398 ;; XXX - should the definition of the car really be looked up in the
2399 ;; current module?
2400
2401 (define (macroexpand-1 e)
2402 (cond
2403 ((pair? e) (let* ((a (car e))
2404 (val (and (symbol? a) (local-ref (list a)))))
2405 (if (defmacro? val)
2406 (apply (defmacro-transformer val) (cdr e))
2407 e)))
2408 (#t e)))
2409
2410 (define (macroexpand e)
2411 (cond
2412 ((pair? e) (let* ((a (car e))
2413 (val (and (symbol? a) (local-ref (list a)))))
2414 (if (defmacro? val)
2415 (macroexpand (apply (defmacro-transformer val) (cdr e)))
2416 e)))
2417 (#t e)))
2418
2419 (define (gentemp)
2420 (gensym "scm:G"))
2421
2422 (provide 'defmacro)
2423
2424 \f
2425
2426 ;;; {Run-time options}
2427
2428 ((let* ((names '((eval-options-interface
2429 (eval-options eval-enable eval-disable)
2430 (eval-set!))
2431
2432 (debug-options-interface
2433 (debug-options debug-enable debug-disable)
2434 (debug-set!))
2435
2436 (evaluator-traps-interface
2437 (traps trap-enable trap-disable)
2438 (trap-set!))
2439
2440 (read-options-interface
2441 (read-options read-enable read-disable)
2442 (read-set!))
2443
2444 (print-options-interface
2445 (print-options print-enable print-disable)
2446 (print-set!))
2447
2448 (readline-options-interface
2449 (readline-options readline-enable readline-disable)
2450 (readline-set!))
2451 ))
2452 (option-name car)
2453 (option-value cadr)
2454 (option-documentation caddr)
2455
2456 (print-option (lambda (option)
2457 (display (option-name option))
2458 (if (< (string-length
2459 (symbol->string (option-name option)))
2460 8)
2461 (display #\tab))
2462 (display #\tab)
2463 (display (option-value option))
2464 (display #\tab)
2465 (display (option-documentation option))
2466 (newline)))
2467
2468 ;; Below follows the macros defining the run-time option interfaces.
2469
2470 (make-options (lambda (interface)
2471 `(lambda args
2472 (cond ((null? args) (,interface))
2473 ((list? (car args))
2474 (,interface (car args)) (,interface))
2475 (else (for-each ,print-option
2476 (,interface #t)))))))
2477
2478 (make-enable (lambda (interface)
2479 `(lambda flags
2480 (,interface (append flags (,interface)))
2481 (,interface))))
2482
2483 (make-disable (lambda (interface)
2484 `(lambda flags
2485 (let ((options (,interface)))
2486 (for-each (lambda (flag)
2487 (set! options (delq! flag options)))
2488 flags)
2489 (,interface options)
2490 (,interface)))))
2491
2492 (make-set! (lambda (interface)
2493 `((name exp)
2494 (,'quasiquote
2495 (begin (,interface (append (,interface)
2496 (list '(,'unquote name)
2497 (,'unquote exp))))
2498 (,interface))))))
2499 )
2500 (procedure->macro
2501 (lambda (exp env)
2502 (cons 'begin
2503 (apply append
2504 (map (lambda (group)
2505 (let ((interface (car group)))
2506 (append (map (lambda (name constructor)
2507 `(define ,name
2508 ,(constructor interface)))
2509 (cadr group)
2510 (list make-options
2511 make-enable
2512 make-disable))
2513 (map (lambda (name constructor)
2514 `(defmacro ,name
2515 ,@(constructor interface)))
2516 (caddr group)
2517 (list make-set!)))))
2518 names)))))))
2519
2520 \f
2521
2522 ;;; {Running Repls}
2523 ;;;
2524
2525 (define (repl read evaler print)
2526 (let loop ((source (read (current-input-port))))
2527 (print (evaler source))
2528 (loop (read (current-input-port)))))
2529
2530 ;; A provisional repl that acts like the SCM repl:
2531 ;;
2532 (define scm-repl-silent #f)
2533 (define (assert-repl-silence v) (set! scm-repl-silent v))
2534
2535 (define *unspecified* (if #f #f))
2536 (define (unspecified? v) (eq? v *unspecified*))
2537
2538 (define scm-repl-print-unspecified #f)
2539 (define (assert-repl-print-unspecified v) (set! scm-repl-print-unspecified v))
2540
2541 (define scm-repl-verbose #f)
2542 (define (assert-repl-verbosity v) (set! scm-repl-verbose v))
2543
2544 (define scm-repl-prompt "guile> ")
2545
2546 (define (set-repl-prompt! v) (set! scm-repl-prompt v))
2547
2548 (define (default-lazy-handler key . args)
2549 (save-stack lazy-handler-dispatch)
2550 (apply throw key args))
2551
2552 (define enter-frame-handler default-lazy-handler)
2553 (define apply-frame-handler default-lazy-handler)
2554 (define exit-frame-handler default-lazy-handler)
2555
2556 (define (lazy-handler-dispatch key . args)
2557 (case key
2558 ((apply-frame)
2559 (apply apply-frame-handler key args))
2560 ((exit-frame)
2561 (apply exit-frame-handler key args))
2562 ((enter-frame)
2563 (apply enter-frame-handler key args))
2564 (else
2565 (apply default-lazy-handler key args))))
2566
2567 (define abort-hook (make-hook))
2568
2569 ;; these definitions are used if running a script.
2570 ;; otherwise redefined in error-catching-loop.
2571 (define (set-batch-mode?! arg) #t)
2572 (define (batch-mode?) #t)
2573
2574 (define (error-catching-loop thunk)
2575 (let ((status #f)
2576 (interactive #t))
2577 (define (loop first)
2578 (let ((next
2579 (catch #t
2580
2581 (lambda ()
2582 (lazy-catch #t
2583 (lambda ()
2584 (dynamic-wind
2585 (lambda () (unmask-signals))
2586 (lambda ()
2587 (with-traps
2588 (lambda ()
2589 (first)
2590
2591 ;; This line is needed because mark
2592 ;; doesn't do closures quite right.
2593 ;; Unreferenced locals should be
2594 ;; collected.
2595 ;;
2596 (set! first #f)
2597 (let loop ((v (thunk)))
2598 (loop (thunk)))
2599 #f)))
2600 (lambda () (mask-signals))))
2601
2602 lazy-handler-dispatch))
2603
2604 (lambda (key . args)
2605 (case key
2606 ((quit)
2607 (set! status args)
2608 #f)
2609
2610 ((switch-repl)
2611 (apply throw 'switch-repl args))
2612
2613 ((abort)
2614 ;; This is one of the closures that require
2615 ;; (set! first #f) above
2616 ;;
2617 (lambda ()
2618 (run-hook abort-hook)
2619 (force-output (current-output-port))
2620 (display "ABORT: " (current-error-port))
2621 (write args (current-error-port))
2622 (newline (current-error-port))
2623 (if interactive
2624 (begin
2625 (if (and
2626 (not has-shown-debugger-hint?)
2627 (not (memq 'backtrace
2628 (debug-options-interface)))
2629 (stack? (fluid-ref the-last-stack)))
2630 (begin
2631 (newline (current-error-port))
2632 (display
2633 "Type \"(backtrace)\" to get more information.\n"
2634 (current-error-port))
2635 (set! has-shown-debugger-hint? #t)))
2636 (force-output (current-error-port)))
2637 (begin
2638 (primitive-exit 1)))
2639 (set! stack-saved? #f)))
2640
2641 (else
2642 ;; This is the other cons-leak closure...
2643 (lambda ()
2644 (cond ((= (length args) 4)
2645 (apply handle-system-error key args))
2646 (else
2647 (apply bad-throw key args))))))))))
2648 (if next (loop next) status)))
2649 (set! set-batch-mode?! (lambda (arg)
2650 (cond (arg
2651 (set! interactive #f)
2652 (restore-signals))
2653 (#t
2654 (error "sorry, not implemented")))))
2655 (set! batch-mode? (lambda () (not interactive)))
2656 (loop (lambda () #t))))
2657
2658 ;;(define the-last-stack (make-fluid)) Defined by scm_init_backtrace ()
2659 (define stack-saved? #f)
2660
2661 (define (save-stack . narrowing)
2662 (or stack-saved?
2663 (cond ((not (memq 'debug (debug-options-interface)))
2664 (fluid-set! the-last-stack #f)
2665 (set! stack-saved? #t))
2666 (else
2667 (fluid-set!
2668 the-last-stack
2669 (case (stack-id #t)
2670 ((repl-stack)
2671 (apply make-stack #t save-stack eval #t 0 narrowing))
2672 ((load-stack)
2673 (apply make-stack #t save-stack 0 #t 0 narrowing))
2674 ((tk-stack)
2675 (apply make-stack #t save-stack tk-stack-mark #t 0 narrowing))
2676 ((#t)
2677 (apply make-stack #t save-stack 0 1 narrowing))
2678 (else
2679 (let ((id (stack-id #t)))
2680 (and (procedure? id)
2681 (apply make-stack #t save-stack id #t 0 narrowing))))))
2682 (set! stack-saved? #t)))))
2683
2684 (define before-error-hook (make-hook))
2685 (define after-error-hook (make-hook))
2686 (define before-backtrace-hook (make-hook))
2687 (define after-backtrace-hook (make-hook))
2688
2689 (define has-shown-debugger-hint? #f)
2690
2691 (define (handle-system-error key . args)
2692 (let ((cep (current-error-port)))
2693 (cond ((not (stack? (fluid-ref the-last-stack))))
2694 ((memq 'backtrace (debug-options-interface))
2695 (run-hook before-backtrace-hook)
2696 (newline cep)
2697 (display-backtrace (fluid-ref the-last-stack) cep)
2698 (newline cep)
2699 (run-hook after-backtrace-hook)))
2700 (run-hook before-error-hook)
2701 (apply display-error (fluid-ref the-last-stack) cep args)
2702 (run-hook after-error-hook)
2703 (force-output cep)
2704 (throw 'abort key)))
2705
2706 (define (quit . args)
2707 (apply throw 'quit args))
2708
2709 (define exit quit)
2710
2711 ;;(define has-shown-backtrace-hint? #f) Defined by scm_init_backtrace ()
2712
2713 ;; Replaced by C code:
2714 ;;(define (backtrace)
2715 ;; (if (fluid-ref the-last-stack)
2716 ;; (begin
2717 ;; (newline)
2718 ;; (display-backtrace (fluid-ref the-last-stack) (current-output-port))
2719 ;; (newline)
2720 ;; (if (and (not has-shown-backtrace-hint?)
2721 ;; (not (memq 'backtrace (debug-options-interface))))
2722 ;; (begin
2723 ;; (display
2724 ;;"Type \"(debug-enable 'backtrace)\" if you would like a backtrace
2725 ;;automatically if an error occurs in the future.\n")
2726 ;; (set! has-shown-backtrace-hint? #t))))
2727 ;; (display "No backtrace available.\n")))
2728
2729 (define (error-catching-repl r e p)
2730 (error-catching-loop (lambda () (p (e (r))))))
2731
2732 (define (gc-run-time)
2733 (cdr (assq 'gc-time-taken (gc-stats))))
2734
2735 (define before-read-hook (make-hook))
2736 (define after-read-hook (make-hook))
2737
2738 ;;; The default repl-reader function. We may override this if we've
2739 ;;; the readline library.
2740 (define repl-reader
2741 (lambda (prompt)
2742 (display prompt)
2743 (force-output)
2744 (run-hook before-read-hook)
2745 (read (current-input-port))))
2746
2747 (define (scm-style-repl)
2748 (letrec (
2749 (start-gc-rt #f)
2750 (start-rt #f)
2751 (repl-report-start-timing (lambda ()
2752 (set! start-gc-rt (gc-run-time))
2753 (set! start-rt (get-internal-run-time))))
2754 (repl-report (lambda ()
2755 (display ";;; ")
2756 (display (inexact->exact
2757 (* 1000 (/ (- (get-internal-run-time) start-rt)
2758 internal-time-units-per-second))))
2759 (display " msec (")
2760 (display (inexact->exact
2761 (* 1000 (/ (- (gc-run-time) start-gc-rt)
2762 internal-time-units-per-second))))
2763 (display " msec in gc)\n")))
2764
2765 (consume-trailing-whitespace
2766 (lambda ()
2767 (let ((ch (peek-char)))
2768 (cond
2769 ((eof-object? ch))
2770 ((or (char=? ch #\space) (char=? ch #\tab))
2771 (read-char)
2772 (consume-trailing-whitespace))
2773 ((char=? ch #\newline)
2774 (read-char))))))
2775 (-read (lambda ()
2776 (let ((val
2777 (let ((prompt (cond ((string? scm-repl-prompt)
2778 scm-repl-prompt)
2779 ((thunk? scm-repl-prompt)
2780 (scm-repl-prompt))
2781 (scm-repl-prompt "> ")
2782 (else ""))))
2783 (repl-reader prompt))))
2784
2785 ;; As described in R4RS, the READ procedure updates the
2786 ;; port to point to the first character past the end of
2787 ;; the external representation of the object. This
2788 ;; means that it doesn't consume the newline typically
2789 ;; found after an expression. This means that, when
2790 ;; debugging Guile with GDB, GDB gets the newline, which
2791 ;; it often interprets as a "continue" command, making
2792 ;; breakpoints kind of useless. So, consume any
2793 ;; trailing newline here, as well as any whitespace
2794 ;; before it.
2795 ;; But not if EOF, for control-D.
2796 (if (not (eof-object? val))
2797 (consume-trailing-whitespace))
2798 (run-hook after-read-hook)
2799 (if (eof-object? val)
2800 (begin
2801 (repl-report-start-timing)
2802 (if scm-repl-verbose
2803 (begin
2804 (newline)
2805 (display ";;; EOF -- quitting")
2806 (newline)))
2807 (quit 0)))
2808 val)))
2809
2810 (-eval (lambda (sourc)
2811 (repl-report-start-timing)
2812 (start-stack 'repl-stack (eval sourc))))
2813
2814 (-print (lambda (result)
2815 (if (not scm-repl-silent)
2816 (begin
2817 (if (or scm-repl-print-unspecified
2818 (not (unspecified? result)))
2819 (begin
2820 (write result)
2821 (newline)))
2822 (if scm-repl-verbose
2823 (repl-report))
2824 (force-output)))))
2825
2826 (-quit (lambda (args)
2827 (if scm-repl-verbose
2828 (begin
2829 (display ";;; QUIT executed, repl exitting")
2830 (newline)
2831 (repl-report)))
2832 args))
2833
2834 (-abort (lambda ()
2835 (if scm-repl-verbose
2836 (begin
2837 (display ";;; ABORT executed.")
2838 (newline)
2839 (repl-report)))
2840 (repl -read -eval -print))))
2841
2842 (let ((status (error-catching-repl -read
2843 -eval
2844 -print)))
2845 (-quit status))))
2846
2847
2848 \f
2849 ;;; {IOTA functions: generating lists of numbers}
2850
2851 (define (iota n)
2852 (let loop ((count (1- n)) (result '()))
2853 (if (< count 0) result
2854 (loop (1- count) (cons count result)))))
2855
2856 \f
2857 ;;; {While}
2858 ;;;
2859 ;;; with `continue' and `break'.
2860 ;;;
2861
2862 (defmacro while (cond . body)
2863 `(letrec ((continue (lambda () (or (not ,cond) (begin (begin ,@ body) (continue)))))
2864 (break (lambda val (apply throw 'break val))))
2865 (catch 'break
2866 (lambda () (continue))
2867 (lambda v (cadr v)))))
2868
2869 ;;; {collect}
2870 ;;;
2871 ;;; Similar to `begin' but returns a list of the results of all constituent
2872 ;;; forms instead of the result of the last form.
2873 ;;; (The definition relies on the current left-to-right
2874 ;;; order of evaluation of operands in applications.)
2875
2876 (defmacro collect forms
2877 (cons 'list forms))
2878
2879 ;;; {with-fluids}
2880
2881 ;; with-fluids is a convenience wrapper for the builtin procedure
2882 ;; `with-fluids*'. The syntax is just like `let':
2883 ;;
2884 ;; (with-fluids ((fluid val)
2885 ;; ...)
2886 ;; body)
2887
2888 (defmacro with-fluids (bindings . body)
2889 `(with-fluids* (list ,@(map car bindings)) (list ,@(map cadr bindings))
2890 (lambda () ,@body)))
2891
2892 ;;; Environments
2893
2894 (define the-environment
2895 (procedure->syntax
2896 (lambda (x e)
2897 e)))
2898
2899 (define (environment-module env)
2900 (let ((closure (and (pair? env) (car (last-pair env)))))
2901 (and closure (procedure-property closure 'module))))
2902
2903 \f
2904
2905 ;;; {Macros}
2906 ;;;
2907
2908 ;; actually....hobbit might be able to hack these with a little
2909 ;; coaxing
2910 ;;
2911
2912 (defmacro define-macro (first . rest)
2913 (let ((name (if (symbol? first) first (car first)))
2914 (transformer
2915 (if (symbol? first)
2916 (car rest)
2917 `(lambda ,(cdr first) ,@rest))))
2918 `(define ,name (defmacro:transformer ,transformer))))
2919
2920
2921 (defmacro define-syntax-macro (first . rest)
2922 (let ((name (if (symbol? first) first (car first)))
2923 (transformer
2924 (if (symbol? first)
2925 (car rest)
2926 `(lambda ,(cdr first) ,@rest))))
2927 `(define ,name (defmacro:syntax-transformer ,transformer))))
2928 \f
2929 ;;; {Module System Macros}
2930 ;;;
2931
2932 (defmacro define-module args
2933 `(let* ((process-define-module process-define-module)
2934 (set-current-module set-current-module)
2935 (module (process-define-module ',args)))
2936 (set-current-module module)
2937 module))
2938
2939 ;; the guts of the use-modules macro. add the interfaces of the named
2940 ;; modules to the use-list of the current module, in order
2941 (define (process-use-modules module-names)
2942 (for-each (lambda (module-name)
2943 (let ((mod-iface (resolve-interface module-name)))
2944 (or mod-iface
2945 (error "no such module" module-name))
2946 (module-use! (current-module) mod-iface)))
2947 (reverse module-names)))
2948
2949 (defmacro use-modules modules
2950 `(process-use-modules ',modules))
2951
2952 (defmacro use-syntax (spec)
2953 `(begin
2954 ,@(if (pair? spec)
2955 `((process-use-modules ',(list spec))
2956 (set-module-transformer! (current-module)
2957 ,(car (last-pair spec))))
2958 `((set-module-transformer! (current-module) ,spec)))
2959 (set! scm:eval-transformer (module-transformer (current-module)))))
2960
2961 (define define-private define)
2962
2963 (defmacro define-public args
2964 (define (syntax)
2965 (error "bad syntax" (list 'define-public args)))
2966 (define (defined-name n)
2967 (cond
2968 ((symbol? n) n)
2969 ((pair? n) (defined-name (car n)))
2970 (else (syntax))))
2971 (cond
2972 ((null? args) (syntax))
2973
2974 (#t (let ((name (defined-name (car args))))
2975 `(begin
2976 (let ((public-i (module-public-interface (current-module))))
2977 ;; Make sure there is a local variable:
2978 ;;
2979 (module-define! (current-module)
2980 ',name
2981 (module-ref (current-module) ',name #f))
2982
2983 ;; Make sure that local is exported:
2984 ;;
2985 (module-add! public-i ',name
2986 (module-variable (current-module) ',name)))
2987
2988 ;; Now (re)define the var normally. Bernard URBAN
2989 ;; suggests we use eval here to accomodate Hobbit; it lets
2990 ;; the interpreter handle the define-private form, which
2991 ;; Hobbit can't digest.
2992 (eval '(define-private ,@ args)))))))
2993
2994
2995
2996 (defmacro defmacro-public args
2997 (define (syntax)
2998 (error "bad syntax" (list 'defmacro-public args)))
2999 (define (defined-name n)
3000 (cond
3001 ((symbol? n) n)
3002 (else (syntax))))
3003 (cond
3004 ((null? args) (syntax))
3005
3006 (#t (let ((name (defined-name (car args))))
3007 `(begin
3008 (let ((public-i (module-public-interface (current-module))))
3009 ;; Make sure there is a local variable:
3010 ;;
3011 (module-define! (current-module)
3012 ',name
3013 (module-ref (current-module) ',name #f))
3014
3015 ;; Make sure that local is exported:
3016 ;;
3017 (module-add! public-i ',name (module-variable (current-module) ',name)))
3018
3019 ;; Now (re)define the var normally.
3020 ;;
3021 (defmacro ,@ args))))))
3022
3023
3024 (defmacro export names
3025 `(let* ((m (current-module))
3026 (public-i (module-public-interface m)))
3027 (for-each (lambda (name)
3028 ;; Make sure there is a local variable:
3029 (module-define! m name (module-ref m name #f))
3030 ;; Make sure that local is exported:
3031 (module-add! public-i name (module-variable m name)))
3032 ',names)))
3033
3034 (define export-syntax export)
3035
3036
3037
3038
3039 (define load load-module)
3040
3041
3042 \f
3043 ;;; {Load emacs interface support if emacs option is given.}
3044
3045 (define (load-emacs-interface)
3046 (if (memq 'debug-extensions *features*)
3047 (debug-enable 'backtrace))
3048 (define-module (guile-user) :use-module (ice-9 emacs)))
3049
3050 \f
3051 ;;; {I/O functions for Tcl channels (disabled)}
3052
3053 ;; (define in-ch (get-standard-channel TCL_STDIN))
3054 ;; (define out-ch (get-standard-channel TCL_STDOUT))
3055 ;; (define err-ch (get-standard-channel TCL_STDERR))
3056 ;;
3057 ;; (define inp (%make-channel-port in-ch "r"))
3058 ;; (define outp (%make-channel-port out-ch "w"))
3059 ;; (define errp (%make-channel-port err-ch "w"))
3060 ;;
3061 ;; (define %system-char-ready? char-ready?)
3062 ;;
3063 ;; (define (char-ready? p)
3064 ;; (if (not (channel-port? p))
3065 ;; (%system-char-ready? p)
3066 ;; (let* ((channel (%channel-port-channel p))
3067 ;; (old-blocking (channel-option-ref channel :blocking)))
3068 ;; (dynamic-wind
3069 ;; (lambda () (set-channel-option the-root-tcl-interpreter channel :blocking "0"))
3070 ;; (lambda () (not (eof-object? (peek-char p))))
3071 ;; (lambda () (set-channel-option the-root-tcl-interpreter channel :blocking old-blocking))))))
3072 ;;
3073 ;; (define (top-repl)
3074 ;; (with-input-from-port inp
3075 ;; (lambda ()
3076 ;; (with-output-to-port outp
3077 ;; (lambda ()
3078 ;; (with-error-to-port errp
3079 ;; (lambda ()
3080 ;; (scm-style-repl))))))))
3081 ;;
3082 ;; (set-current-input-port inp)
3083 ;; (set-current-output-port outp)
3084 ;; (set-current-error-port errp)
3085
3086 ;; this is just (scm-style-repl) with a wrapper to install and remove
3087 ;; signal handlers.
3088 (define (top-repl)
3089
3090 ;; Load emacs interface support if emacs option is given.
3091 (if (and (module-defined? the-root-module 'use-emacs-interface)
3092 use-emacs-interface)
3093 (load-emacs-interface))
3094
3095 ;; Place the user in the guile-user module.
3096 (define-module (guile-user))
3097
3098 (let ((old-handlers #f)
3099 (signals `((,SIGINT . "User interrupt")
3100 (,SIGFPE . "Arithmetic error")
3101 (,SIGBUS . "Bad memory access (bus error)")
3102 (,SIGSEGV . "Bad memory access (Segmentation violation)"))))
3103
3104 (dynamic-wind
3105
3106 ;; call at entry
3107 (lambda ()
3108 (let ((make-handler (lambda (msg)
3109 (lambda (sig)
3110 (save-stack %deliver-signals)
3111 (scm-error 'signal
3112 #f
3113 msg
3114 #f
3115 (list sig))))))
3116 (set! old-handlers
3117 (map (lambda (sig-msg)
3118 (sigaction (car sig-msg)
3119 (make-handler (cdr sig-msg))))
3120 signals))))
3121
3122 ;; the protected thunk.
3123 (lambda ()
3124
3125 ;; If we've got readline, use it to prompt the user. This is a
3126 ;; kludge, but we'll fix it soon. At least we only get
3127 ;; readline involved when we're actually running the repl.
3128 (if (and (memq 'readline *features*)
3129 (isatty? (current-input-port))
3130 (not (and (module-defined? the-root-module
3131 'use-emacs-interface)
3132 use-emacs-interface)))
3133 (let ((read-hook (lambda () (run-hook before-read-hook))))
3134 (set-current-input-port (readline-port))
3135 (set! repl-reader
3136 (lambda (prompt)
3137 (dynamic-wind
3138 (lambda ()
3139 (set-readline-prompt! prompt "... ")
3140 (set-readline-read-hook! read-hook))
3141 (lambda () (read))
3142 (lambda ()
3143 (set-readline-prompt! "" "")
3144 (set-readline-read-hook! #f)))))))
3145 (let ((status (scm-style-repl)))
3146 (run-hook exit-hook)
3147 status))
3148
3149 ;; call at exit.
3150 (lambda ()
3151 (map (lambda (sig-msg old-handler)
3152 (if (not (car old-handler))
3153 ;; restore original C handler.
3154 (sigaction (car sig-msg) #f)
3155 ;; restore Scheme handler, SIG_IGN or SIG_DFL.
3156 (sigaction (car sig-msg)
3157 (car old-handler)
3158 (cdr old-handler))))
3159 signals old-handlers)))))
3160
3161 (defmacro false-if-exception (expr)
3162 `(catch #t (lambda () ,expr)
3163 (lambda args #f)))
3164
3165 ;;; This hook is run at the very end of an interactive session.
3166 ;;;
3167 (define exit-hook (make-hook))
3168
3169 ;;; Load readline code into root module if readline primitives are available.
3170 ;;;
3171 ;;; Ideally, we wouldn't do this until we were sure we were actually
3172 ;;; going to enter the repl, but autoloading individual functions is
3173 ;;; clumsy at the moment.
3174 (if (and (memq 'readline *features*)
3175 (isatty? (current-input-port)))
3176 (begin
3177 (define-module (guile) :use-module (ice-9 readline))
3178 (define-module (guile-user) :use-module (ice-9 readline))))
3179
3180 \f
3181 ;;; {Load debug extension code into user module if debug extensions present.}
3182 ;;;
3183 ;;; *fixme* This is a temporary solution.
3184 ;;;
3185
3186 (if (memq 'debug-extensions *features*)
3187 (define-module (guile-user) :use-module (ice-9 debug)))
3188
3189 \f
3190 ;;; {Load session support into user module if present.}
3191 ;;;
3192 ;;; *fixme* This is a temporary solution.
3193 ;;;
3194
3195 (if (%search-load-path "ice-9/session.scm")
3196 (define-module (guile-user) :use-module (ice-9 session)))
3197
3198 ;;; {Load thread code into user module if threads are present.}
3199 ;;;
3200 ;;; *fixme* This is a temporary solution.
3201 ;;;
3202
3203 (if (memq 'threads *features*)
3204 (define-module (guile-user) :use-module (ice-9 threads)))
3205
3206 \f
3207 ;;; {Load regexp code if regexp primitives are available.}
3208
3209 (if (memq 'regex *features*)
3210 (define-module (guile-user) :use-module (ice-9 regex)))
3211
3212 \f
3213 (define-module (guile))
3214
3215 ;;; {Check that the interpreter and scheme code match up.}
3216
3217 (let ((show-line
3218 (lambda args
3219 (with-output-to-port (current-error-port)
3220 (lambda ()
3221 (display (car (command-line)))
3222 (display ": ")
3223 (for-each (lambda (string) (display string))
3224 args)
3225 (newline))))))
3226
3227 (load-from-path "ice-9/version.scm")
3228
3229 (if (not (string=?
3230 (libguile-config-stamp) ; from the interprpreter
3231 (ice-9-config-stamp))) ; from the Scheme code
3232 (begin
3233 (show-line "warning: different versions of libguile and ice-9:")
3234 (show-line "libguile: configured on " (libguile-config-stamp))
3235 (show-line "ice-9: configured on " (ice-9-config-stamp)))))
3236
3237 (append! %load-path (cons "." ()))
3238