* boot-9.scm (error-catching-loop): Correct non-RnRS usage of internal
[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 %print-module))
1325
1326 ;; make-module &opt size uses binder
1327 ;;
1328 ;; Create a new module, perhaps with a particular size of obarray,
1329 ;; initial uses list, or binding procedure.
1330 ;;
1331 (define make-module
1332 (lambda args
1333
1334 (define (parse-arg index default)
1335 (if (> (length args) index)
1336 (list-ref args index)
1337 default))
1338
1339 (if (> (length args) 3)
1340 (error "Too many args to make-module." args))
1341
1342 (let ((size (parse-arg 0 1021))
1343 (uses (parse-arg 1 '()))
1344 (binder (parse-arg 2 #f)))
1345
1346 (if (not (integer? size))
1347 (error "Illegal size to make-module." size))
1348 (if (not (and (list? uses)
1349 (and-map module? uses)))
1350 (error "Incorrect use list." uses))
1351 (if (and binder (not (procedure? binder)))
1352 (error
1353 "Lazy-binder expected to be a procedure or #f." binder))
1354
1355 (let ((module (module-constructor (make-vector size '())
1356 uses binder #f #f #f #f)))
1357
1358 ;; We can't pass this as an argument to module-constructor,
1359 ;; because we need it to close over a pointer to the module
1360 ;; itself.
1361 (set-module-eval-closure! module
1362 (lambda (symbol define?)
1363 (if define?
1364 (module-make-local-var! module symbol)
1365 (module-variable module symbol))))
1366
1367 module))))
1368
1369 (define module-constructor (record-constructor module-type))
1370 (define module-obarray (record-accessor module-type 'obarray))
1371 (define set-module-obarray! (record-modifier module-type 'obarray))
1372 (define module-uses (record-accessor module-type 'uses))
1373 (define set-module-uses! (record-modifier module-type 'uses))
1374 (define module-binder (record-accessor module-type 'binder))
1375 (define set-module-binder! (record-modifier module-type 'binder))
1376
1377 ;; NOTE: This binding is used in libguile/modules.c.
1378 (define module-eval-closure (record-accessor module-type 'eval-closure))
1379
1380 (define module-transformer (record-accessor module-type 'transformer))
1381 (define set-module-transformer! (record-modifier module-type 'transformer))
1382 (define module-name (record-accessor module-type 'name))
1383 (define set-module-name! (record-modifier module-type 'name))
1384 (define module-kind (record-accessor module-type 'kind))
1385 (define set-module-kind! (record-modifier module-type 'kind))
1386 (define module? (record-predicate module-type))
1387
1388 (define set-module-eval-closure!
1389 (let ((setter (record-modifier module-type 'eval-closure)))
1390 (lambda (module closure)
1391 (setter module closure)
1392 ;; Make it possible to lookup the module from the environment.
1393 ;; This implementation is correct since an eval closure can belong
1394 ;; to maximally one module.
1395 (set-procedure-property! closure 'module module))))
1396
1397 (define (eval-in-module exp module)
1398 (eval2 exp (module-eval-closure module)))
1399
1400 \f
1401 ;;; {Module Searching in General}
1402 ;;;
1403 ;;; We sometimes want to look for properties of a symbol
1404 ;;; just within the obarray of one module. If the property
1405 ;;; holds, then it is said to hold ``locally'' as in, ``The symbol
1406 ;;; DISPLAY is locally rebound in the module `safe-guile'.''
1407 ;;;
1408 ;;;
1409 ;;; Other times, we want to test for a symbol property in the obarray
1410 ;;; of M and, if it is not found there, try each of the modules in the
1411 ;;; uses list of M. This is the normal way of testing for some
1412 ;;; property, so we state these properties without qualification as
1413 ;;; in: ``The symbol 'fnord is interned in module M because it is
1414 ;;; interned locally in module M2 which is a member of the uses list
1415 ;;; of M.''
1416 ;;;
1417
1418 ;; module-search fn m
1419 ;;
1420 ;; return the first non-#f result of FN applied to M and then to
1421 ;; the modules in the uses of m, and so on recursively. If all applications
1422 ;; return #f, then so does this function.
1423 ;;
1424 (define (module-search fn m v)
1425 (define (loop pos)
1426 (and (pair? pos)
1427 (or (module-search fn (car pos) v)
1428 (loop (cdr pos)))))
1429 (or (fn m v)
1430 (loop (module-uses m))))
1431
1432
1433 ;;; {Is a symbol bound in a module?}
1434 ;;;
1435 ;;; Symbol S in Module M is bound if S is interned in M and if the binding
1436 ;;; of S in M has been set to some well-defined value.
1437 ;;;
1438
1439 ;; module-locally-bound? module symbol
1440 ;;
1441 ;; Is a symbol bound (interned and defined) locally in a given module?
1442 ;;
1443 (define (module-locally-bound? m v)
1444 (let ((var (module-local-variable m v)))
1445 (and var
1446 (variable-bound? var))))
1447
1448 ;; module-bound? module symbol
1449 ;;
1450 ;; Is a symbol bound (interned and defined) anywhere in a given module
1451 ;; or its uses?
1452 ;;
1453 (define (module-bound? m v)
1454 (module-search module-locally-bound? m v))
1455
1456 ;;; {Is a symbol interned in a module?}
1457 ;;;
1458 ;;; Symbol S in Module M is interned if S occurs in
1459 ;;; of S in M has been set to some well-defined value.
1460 ;;;
1461 ;;; It is possible to intern a symbol in a module without providing
1462 ;;; an initial binding for the corresponding variable. This is done
1463 ;;; with:
1464 ;;; (module-add! module symbol (make-undefined-variable))
1465 ;;;
1466 ;;; In that case, the symbol is interned in the module, but not
1467 ;;; bound there. The unbound symbol shadows any binding for that
1468 ;;; symbol that might otherwise be inherited from a member of the uses list.
1469 ;;;
1470
1471 (define (module-obarray-get-handle ob key)
1472 ((if (symbol? key) hashq-get-handle hash-get-handle) ob key))
1473
1474 (define (module-obarray-ref ob key)
1475 ((if (symbol? key) hashq-ref hash-ref) ob key))
1476
1477 (define (module-obarray-set! ob key val)
1478 ((if (symbol? key) hashq-set! hash-set!) ob key val))
1479
1480 (define (module-obarray-remove! ob key)
1481 ((if (symbol? key) hashq-remove! hash-remove!) ob key))
1482
1483 ;; module-symbol-locally-interned? module symbol
1484 ;;
1485 ;; is a symbol interned (not neccessarily defined) locally in a given module
1486 ;; or its uses? Interned symbols shadow inherited bindings even if
1487 ;; they are not themselves bound to a defined value.
1488 ;;
1489 (define (module-symbol-locally-interned? m v)
1490 (not (not (module-obarray-get-handle (module-obarray m) v))))
1491
1492 ;; module-symbol-interned? module symbol
1493 ;;
1494 ;; is a symbol interned (not neccessarily defined) anywhere in a given module
1495 ;; or its uses? Interned symbols shadow inherited bindings even if
1496 ;; they are not themselves bound to a defined value.
1497 ;;
1498 (define (module-symbol-interned? m v)
1499 (module-search module-symbol-locally-interned? m v))
1500
1501
1502 ;;; {Mapping modules x symbols --> variables}
1503 ;;;
1504
1505 ;; module-local-variable module symbol
1506 ;; return the local variable associated with a MODULE and SYMBOL.
1507 ;;
1508 ;;; This function is very important. It is the only function that can
1509 ;;; return a variable from a module other than the mutators that store
1510 ;;; new variables in modules. Therefore, this function is the location
1511 ;;; of the "lazy binder" hack.
1512 ;;;
1513 ;;; If symbol is defined in MODULE, and if the definition binds symbol
1514 ;;; to a variable, return that variable object.
1515 ;;;
1516 ;;; If the symbols is not found at first, but the module has a lazy binder,
1517 ;;; then try the binder.
1518 ;;;
1519 ;;; If the symbol is not found at all, return #f.
1520 ;;;
1521 (define (module-local-variable m v)
1522 ; (caddr
1523 ; (list m v
1524 (let ((b (module-obarray-ref (module-obarray m) v)))
1525 (or (and (variable? b) b)
1526 (and (module-binder m)
1527 ((module-binder m) m v #f)))))
1528 ;))
1529
1530 ;; module-variable module symbol
1531 ;;
1532 ;; like module-local-variable, except search the uses in the
1533 ;; case V is not found in M.
1534 ;;
1535 (define (module-variable m v)
1536 (module-search module-local-variable m v))
1537
1538
1539 ;;; {Mapping modules x symbols --> bindings}
1540 ;;;
1541 ;;; These are similar to the mapping to variables, except that the
1542 ;;; variable is dereferenced.
1543 ;;;
1544
1545 ;; module-symbol-binding module symbol opt-value
1546 ;;
1547 ;; return the binding of a variable specified by name within
1548 ;; a given module, signalling an error if the variable is unbound.
1549 ;; If the OPT-VALUE is passed, then instead of signalling an error,
1550 ;; return OPT-VALUE.
1551 ;;
1552 (define (module-symbol-local-binding m v . opt-val)
1553 (let ((var (module-local-variable m v)))
1554 (if var
1555 (variable-ref var)
1556 (if (not (null? opt-val))
1557 (car opt-val)
1558 (error "Locally unbound variable." v)))))
1559
1560 ;; module-symbol-binding module symbol opt-value
1561 ;;
1562 ;; return the binding of a variable specified by name within
1563 ;; a given module, signalling an error if the variable is unbound.
1564 ;; If the OPT-VALUE is passed, then instead of signalling an error,
1565 ;; return OPT-VALUE.
1566 ;;
1567 (define (module-symbol-binding m v . opt-val)
1568 (let ((var (module-variable m v)))
1569 (if var
1570 (variable-ref var)
1571 (if (not (null? opt-val))
1572 (car opt-val)
1573 (error "Unbound variable." v)))))
1574
1575
1576 \f
1577 ;;; {Adding Variables to Modules}
1578 ;;;
1579 ;;;
1580
1581
1582 ;; module-make-local-var! module symbol
1583 ;;
1584 ;; ensure a variable for V in the local namespace of M.
1585 ;; If no variable was already there, then create a new and uninitialzied
1586 ;; variable.
1587 ;;
1588 (define (module-make-local-var! m v)
1589 (or (let ((b (module-obarray-ref (module-obarray m) v)))
1590 (and (variable? b) b))
1591 (and (module-binder m)
1592 ((module-binder m) m v #t))
1593 (begin
1594 (let ((answer (make-undefined-variable v)))
1595 (module-obarray-set! (module-obarray m) v answer)
1596 answer))))
1597
1598 ;; module-add! module symbol var
1599 ;;
1600 ;; ensure a particular variable for V in the local namespace of M.
1601 ;;
1602 (define (module-add! m v var)
1603 (if (not (variable? var))
1604 (error "Bad variable to module-add!" var))
1605 (module-obarray-set! (module-obarray m) v var))
1606
1607 ;; module-remove!
1608 ;;
1609 ;; make sure that a symbol is undefined in the local namespace of M.
1610 ;;
1611 (define (module-remove! m v)
1612 (module-obarray-remove! (module-obarray m) v))
1613
1614 (define (module-clear! m)
1615 (vector-fill! (module-obarray m) '()))
1616
1617 ;; MODULE-FOR-EACH -- exported
1618 ;;
1619 ;; Call PROC on each symbol in MODULE, with arguments of (SYMBOL VARIABLE).
1620 ;;
1621 (define (module-for-each proc module)
1622 (let ((obarray (module-obarray module)))
1623 (do ((index 0 (+ index 1))
1624 (end (vector-length obarray)))
1625 ((= index end))
1626 (for-each
1627 (lambda (bucket)
1628 (proc (car bucket) (cdr bucket)))
1629 (vector-ref obarray index)))))
1630
1631
1632 (define (module-map proc module)
1633 (let* ((obarray (module-obarray module))
1634 (end (vector-length obarray)))
1635
1636 (let loop ((i 0)
1637 (answer '()))
1638 (if (= i end)
1639 answer
1640 (loop (+ 1 i)
1641 (append!
1642 (map (lambda (bucket)
1643 (proc (car bucket) (cdr bucket)))
1644 (vector-ref obarray i))
1645 answer))))))
1646 \f
1647
1648 ;;; {Low Level Bootstrapping}
1649 ;;;
1650
1651 ;; make-root-module
1652
1653 ;; A root module uses the symhash table (the system's privileged
1654 ;; obarray). Being inside a root module is like using SCM without
1655 ;; any module system.
1656 ;;
1657
1658
1659 (define (root-module-closure m s define?)
1660 (let ((bi (and (symbol-interned? #f s)
1661 (builtin-variable s))))
1662 (and bi
1663 (or define? (variable-bound? bi))
1664 (begin
1665 (module-add! m s bi)
1666 bi))))
1667
1668 (define (make-root-module)
1669 (make-module 1019 '() root-module-closure))
1670
1671
1672 ;; make-scm-module
1673
1674 ;; An scm module is a module into which the lazy binder copies
1675 ;; variable bindings from the system symhash table. The mapping is
1676 ;; one way only; newly introduced bindings in an scm module are not
1677 ;; copied back into the system symhash table (and can be used to override
1678 ;; bindings from the symhash table).
1679 ;;
1680
1681 (define (make-scm-module)
1682 (make-module 1019 '()
1683 (lambda (m s define?)
1684 (let ((bi (and (symbol-interned? #f s)
1685 (builtin-variable s))))
1686 (and bi
1687 (variable-bound? bi)
1688 (begin
1689 (module-add! m s bi)
1690 bi))))))
1691
1692
1693
1694
1695 ;; the-module
1696 ;;
1697 ;; NOTE: This binding is used in libguile/modules.c.
1698 ;;
1699 (define the-module #f)
1700
1701 ;; scm:eval-transformer
1702 ;;
1703 (define scm:eval-transformer #f)
1704
1705 ;; set-current-module module
1706 ;;
1707 ;; set the current module as viewed by the normalizer.
1708 ;;
1709 ;; NOTE: This binding is used in libguile/modules.c.
1710 ;;
1711 (define (set-current-module m)
1712 (set! the-module m)
1713 (if m
1714 (begin
1715 (set! *top-level-lookup-closure* (module-eval-closure the-module))
1716 (set! scm:eval-transformer (module-transformer the-module)))
1717 (set! *top-level-lookup-closure* #f)))
1718
1719
1720 ;; current-module
1721 ;;
1722 ;; return the current module as viewed by the normalizer.
1723 ;;
1724 (define (current-module) the-module)
1725 \f
1726 ;;; {Module-based Loading}
1727 ;;;
1728
1729 (define (save-module-excursion thunk)
1730 (let ((inner-module (current-module))
1731 (outer-module #f))
1732 (dynamic-wind (lambda ()
1733 (set! outer-module (current-module))
1734 (set-current-module inner-module)
1735 (set! inner-module #f))
1736 thunk
1737 (lambda ()
1738 (set! inner-module (current-module))
1739 (set-current-module outer-module)
1740 (set! outer-module #f)))))
1741
1742 (define basic-load load)
1743
1744 (define (load-module filename)
1745 (save-module-excursion
1746 (lambda ()
1747 (let ((oldname (and (current-load-port)
1748 (port-filename (current-load-port)))))
1749 (basic-load (if (and oldname
1750 (> (string-length filename) 0)
1751 (not (char=? (string-ref filename 0) #\/))
1752 (not (string=? (dirname oldname) ".")))
1753 (string-append (dirname oldname) "/" filename)
1754 filename))))))
1755
1756
1757 \f
1758 ;;; {MODULE-REF -- exported}
1759 ;;
1760 ;; Returns the value of a variable called NAME in MODULE or any of its
1761 ;; used modules. If there is no such variable, then if the optional third
1762 ;; argument DEFAULT is present, it is returned; otherwise an error is signaled.
1763 ;;
1764 (define (module-ref module name . rest)
1765 (let ((variable (module-variable module name)))
1766 (if (and variable (variable-bound? variable))
1767 (variable-ref variable)
1768 (if (null? rest)
1769 (error "No variable named" name 'in module)
1770 (car rest) ; default value
1771 ))))
1772
1773 ;; MODULE-SET! -- exported
1774 ;;
1775 ;; Sets the variable called NAME in MODULE (or in a module that MODULE uses)
1776 ;; to VALUE; if there is no such variable, an error is signaled.
1777 ;;
1778 (define (module-set! module name value)
1779 (let ((variable (module-variable module name)))
1780 (if variable
1781 (variable-set! variable value)
1782 (error "No variable named" name 'in module))))
1783
1784 ;; MODULE-DEFINE! -- exported
1785 ;;
1786 ;; Sets the variable called NAME in MODULE to VALUE; if there is no such
1787 ;; variable, it is added first.
1788 ;;
1789 (define (module-define! module name value)
1790 (let ((variable (module-local-variable module name)))
1791 (if variable
1792 (variable-set! variable value)
1793 (module-add! module name (make-variable value name)))))
1794
1795 ;; MODULE-DEFINED? -- exported
1796 ;;
1797 ;; Return #t iff NAME is defined in MODULE (or in a module that MODULE
1798 ;; uses)
1799 ;;
1800 (define (module-defined? module name)
1801 (let ((variable (module-variable module name)))
1802 (and variable (variable-bound? variable))))
1803
1804 ;; MODULE-USE! module interface
1805 ;;
1806 ;; Add INTERFACE to the list of interfaces used by MODULE.
1807 ;;
1808 (define (module-use! module interface)
1809 (set-module-uses! module
1810 (cons interface (delq! interface (module-uses module)))))
1811
1812 \f
1813 ;;; {Recursive Namespaces}
1814 ;;;
1815 ;;;
1816 ;;; A hierarchical namespace emerges if we consider some module to be
1817 ;;; root, and variables bound to modules as nested namespaces.
1818 ;;;
1819 ;;; The routines in this file manage variable names in hierarchical namespace.
1820 ;;; Each variable name is a list of elements, looked up in successively nested
1821 ;;; modules.
1822 ;;;
1823 ;;; (nested-ref some-root-module '(foo bar baz))
1824 ;;; => <value of a variable named baz in the module bound to bar in
1825 ;;; the module bound to foo in some-root-module>
1826 ;;;
1827 ;;;
1828 ;;; There are:
1829 ;;;
1830 ;;; ;; a-root is a module
1831 ;;; ;; name is a list of symbols
1832 ;;;
1833 ;;; nested-ref a-root name
1834 ;;; nested-set! a-root name val
1835 ;;; nested-define! a-root name val
1836 ;;; nested-remove! a-root name
1837 ;;;
1838 ;;;
1839 ;;; (current-module) is a natural choice for a-root so for convenience there are
1840 ;;; also:
1841 ;;;
1842 ;;; local-ref name == nested-ref (current-module) name
1843 ;;; local-set! name val == nested-set! (current-module) name val
1844 ;;; local-define! name val == nested-define! (current-module) name val
1845 ;;; local-remove! name == nested-remove! (current-module) name
1846 ;;;
1847
1848
1849 (define (nested-ref root names)
1850 (let loop ((cur root)
1851 (elts names))
1852 (cond
1853 ((null? elts) cur)
1854 ((not (module? cur)) #f)
1855 (else (loop (module-ref cur (car elts) #f) (cdr elts))))))
1856
1857 (define (nested-set! root names val)
1858 (let loop ((cur root)
1859 (elts names))
1860 (if (null? (cdr elts))
1861 (module-set! cur (car elts) val)
1862 (loop (module-ref cur (car elts)) (cdr elts)))))
1863
1864 (define (nested-define! root names val)
1865 (let loop ((cur root)
1866 (elts names))
1867 (if (null? (cdr elts))
1868 (module-define! cur (car elts) val)
1869 (loop (module-ref cur (car elts)) (cdr elts)))))
1870
1871 (define (nested-remove! root names)
1872 (let loop ((cur root)
1873 (elts names))
1874 (if (null? (cdr elts))
1875 (module-remove! cur (car elts))
1876 (loop (module-ref cur (car elts)) (cdr elts)))))
1877
1878 (define (local-ref names) (nested-ref (current-module) names))
1879 (define (local-set! names val) (nested-set! (current-module) names val))
1880 (define (local-define names val) (nested-define! (current-module) names val))
1881 (define (local-remove names) (nested-remove! (current-module) names))
1882
1883
1884 \f
1885 ;;; {The (app) module}
1886 ;;;
1887 ;;; The root of conventionally named objects not directly in the top level.
1888 ;;;
1889 ;;; (app modules)
1890 ;;; (app modules guile)
1891 ;;;
1892 ;;; The directory of all modules and the standard root module.
1893 ;;;
1894
1895 (define (module-public-interface m)
1896 (module-ref m '%module-public-interface #f))
1897 (define (set-module-public-interface! m i)
1898 (module-define! m '%module-public-interface i))
1899 (define (set-system-module! m s)
1900 (set-procedure-property! (module-eval-closure m) 'system-module s))
1901 (define the-root-module (make-root-module))
1902 (define the-scm-module (make-scm-module))
1903 (set-module-public-interface! the-root-module the-scm-module)
1904 (set-module-name! the-root-module 'the-root-module)
1905 (set-module-name! the-scm-module 'the-scm-module)
1906 (for-each set-system-module! (list the-root-module the-scm-module) '(#t #t))
1907
1908 (set-current-module the-root-module)
1909
1910 (define app (make-module 31))
1911 (local-define '(app modules) (make-module 31))
1912 (local-define '(app modules guile) the-root-module)
1913
1914 ;; (define-special-value '(app modules new-ws) (lambda () (make-scm-module)))
1915
1916 (define (try-load-module name)
1917 (or (try-module-linked name)
1918 (try-module-autoload name)
1919 (try-module-dynamic-link name)))
1920
1921 ;; NOTE: This binding is used in libguile/modules.c.
1922 ;;
1923 (define (resolve-module name . maybe-autoload)
1924 (let ((full-name (append '(app modules) name)))
1925 (let ((already (local-ref full-name)))
1926 (if already
1927 ;; The module already exists...
1928 (if (and (or (null? maybe-autoload) (car maybe-autoload))
1929 (not (module-ref already '%module-public-interface #f)))
1930 ;; ...but we are told to load and it doesn't contain source, so
1931 (begin
1932 (try-load-module name)
1933 already)
1934 ;; simply return it.
1935 already)
1936 (begin
1937 ;; Try to autoload it if we are told so
1938 (if (or (null? maybe-autoload) (car maybe-autoload))
1939 (try-load-module name))
1940 ;; Get/create it.
1941 (make-modules-in (current-module) full-name))))))
1942
1943 (define (beautify-user-module! module)
1944 (let ((interface (module-public-interface module)))
1945 (if (or (not interface)
1946 (eq? interface module))
1947 (let ((interface (make-module 31)))
1948 (set-module-name! interface (module-name module))
1949 (set-module-kind! interface 'interface)
1950 (set-module-public-interface! module interface))))
1951 (if (and (not (memq the-scm-module (module-uses module)))
1952 (not (eq? module the-root-module)))
1953 (set-module-uses! module (append (module-uses module) (list the-scm-module)))))
1954
1955 ;; NOTE: This binding is used in libguile/modules.c.
1956 ;;
1957 (define (make-modules-in module name)
1958 (if (null? name)
1959 module
1960 (cond
1961 ((module-ref module (car name) #f)
1962 => (lambda (m) (make-modules-in m (cdr name))))
1963 (else (let ((m (make-module 31)))
1964 (set-module-kind! m 'directory)
1965 (set-module-name! m (car name))
1966 (module-define! module (car name) m)
1967 (make-modules-in m (cdr name)))))))
1968
1969 (define (resolve-interface name)
1970 (let ((module (resolve-module name)))
1971 (and module (module-public-interface module))))
1972
1973
1974 (define %autoloader-developer-mode #t)
1975
1976 (define (process-define-module args)
1977 (let* ((module-id (car args))
1978 (module (resolve-module module-id #f))
1979 (kws (cdr args)))
1980 (beautify-user-module! module)
1981 (let loop ((kws kws)
1982 (reversed-interfaces '()))
1983 (if (null? kws)
1984 (for-each (lambda (interface)
1985 (module-use! module interface))
1986 reversed-interfaces)
1987 (let ((keyword (cond ((keyword? (car kws))
1988 (keyword->symbol (car kws)))
1989 ((and (symbol? (car kws))
1990 (eq? (string-ref (car kws) 0) #\:))
1991 (string->symbol (substring (car kws) 1)))
1992 (else #f))))
1993 (case keyword
1994 ((use-module use-syntax)
1995 (if (not (pair? (cdr kws)))
1996 (error "unrecognized defmodule argument" kws))
1997 (let* ((used-name (cadr kws))
1998 (used-module (resolve-module used-name)))
1999 (if (not (module-ref used-module
2000 '%module-public-interface
2001 #f))
2002 (begin
2003 ((if %autoloader-developer-mode warn error)
2004 "no code for module" (module-name used-module))
2005 (beautify-user-module! used-module)))
2006 (let ((interface (module-public-interface used-module)))
2007 (if (not interface)
2008 (error "missing interface for use-module"
2009 used-module))
2010 (if (eq? keyword 'use-syntax)
2011 (set-module-transformer!
2012 module
2013 (module-ref interface (car (last-pair used-name))
2014 #f)))
2015 (loop (cddr kws)
2016 (cons interface reversed-interfaces)))))
2017 ((autoload)
2018 (if (not (and (pair? (cdr kws)) (pair? (cddr kws))))
2019 (error "unrecognized defmodule argument" kws))
2020 (loop (cdddr kws)
2021 (cons (make-autoload-interface module
2022 (cadr kws)
2023 (caddr kws))
2024 reversed-interfaces)))
2025 ((no-backtrace)
2026 (set-system-module! module #t)
2027 (loop (cdr kws) reversed-interfaces))
2028 (else
2029 (error "unrecognized defmodule argument" kws))))))
2030 module))
2031
2032 ;;; {Autoload}
2033
2034 (define (make-autoload-interface module name bindings)
2035 (let ((b (lambda (a sym definep)
2036 (and (memq sym bindings)
2037 (let ((i (module-public-interface (resolve-module name))))
2038 (if (not i)
2039 (error "missing interface for module" name))
2040 ;; Replace autoload-interface with interface
2041 (set-car! (memq a (module-uses module)) i)
2042 (module-local-variable i sym))))))
2043 (module-constructor #() #f b #f #f name 'autoload)))
2044
2045 \f
2046 ;;; {Autoloading modules}
2047
2048 (define autoloads-in-progress '())
2049
2050 (define (try-module-autoload module-name)
2051
2052 (define (sfx name) (string-append name (scheme-file-suffix)))
2053 (let* ((reverse-name (reverse module-name))
2054 (name (car reverse-name))
2055 (dir-hint-module-name (reverse (cdr reverse-name)))
2056 (dir-hint (apply symbol-append (map (lambda (elt) (symbol-append elt "/")) dir-hint-module-name))))
2057 (resolve-module dir-hint-module-name #f)
2058 (and (not (autoload-done-or-in-progress? dir-hint name))
2059 (let ((didit #f))
2060 (dynamic-wind
2061 (lambda () (autoload-in-progress! dir-hint name))
2062 (lambda ()
2063 (let loop ((dirs %load-path))
2064 (and (not (null? dirs))
2065 (or
2066 (let ((d (car dirs))
2067 (trys (list
2068 dir-hint
2069 (sfx dir-hint)
2070 (in-vicinity dir-hint name)
2071 (in-vicinity dir-hint (sfx name)))))
2072 (and (or-map (lambda (f)
2073 (let ((full (in-vicinity d f)))
2074 full
2075 (and (file-exists? full)
2076 (not (file-is-directory? full))
2077 (begin
2078 (save-module-excursion
2079 (lambda ()
2080 (load (string-append
2081 d "/" f))))
2082 #t))))
2083 trys)
2084 (begin
2085 (set! didit #t)
2086 #t)))
2087 (loop (cdr dirs))))))
2088 (lambda () (set-autoloaded! dir-hint name didit)))
2089 didit))))
2090
2091 \f
2092 ;;; Dynamic linking of modules
2093
2094 ;; Initializing a module that is written in C is a two step process.
2095 ;; First the module's `module init' function is called. This function
2096 ;; is expected to call `scm_register_module_xxx' to register the `real
2097 ;; init' function. Later, when the module is referenced for the first
2098 ;; time, this real init function is called in the right context. See
2099 ;; gtcltk-lib/gtcltk-module.c for an example.
2100 ;;
2101 ;; The code for the module can be in a regular shared library (so that
2102 ;; the `module init' function will be called when libguile is
2103 ;; initialized). Or it can be dynamically linked.
2104 ;;
2105 ;; You can safely call `scm_register_module_xxx' before libguile
2106 ;; itself is initialized. You could call it from an C++ constructor
2107 ;; of a static object, for example.
2108 ;;
2109 ;; To make your Guile extension into a dynamic linkable module, follow
2110 ;; these easy steps:
2111 ;;
2112 ;; - Find a name for your module, like (ice-9 gtcltk)
2113 ;; - Write a function with a name like
2114 ;;
2115 ;; scm_init_ice_9_gtcltk_module
2116 ;;
2117 ;; This is your `module init' function. It should call
2118 ;;
2119 ;; scm_register_module_xxx ("ice-9 gtcltk", scm_init_gtcltk);
2120 ;;
2121 ;; "ice-9 gtcltk" is the C version of the module name. Slashes are
2122 ;; replaced by spaces, the rest is untouched. `scm_init_gtcltk' is
2123 ;; the real init function that executes the usual initializations
2124 ;; like making new smobs, etc.
2125 ;;
2126 ;; - Make a shared library with your code and a name like
2127 ;;
2128 ;; ice-9/libgtcltk.so
2129 ;;
2130 ;; and put it somewhere in %load-path.
2131 ;;
2132 ;; - Then you can simply write `:use-module (ice-9 gtcltk)' and it
2133 ;; will be linked automatically.
2134 ;;
2135 ;; This is all very experimental.
2136
2137 (define (split-c-module-name str)
2138 (let loop ((rev '())
2139 (start 0)
2140 (pos 0)
2141 (end (string-length str)))
2142 (cond
2143 ((= pos end)
2144 (reverse (cons (string->symbol (substring str start pos)) rev)))
2145 ((eq? (string-ref str pos) #\space)
2146 (loop (cons (string->symbol (substring str start pos)) rev)
2147 (+ pos 1)
2148 (+ pos 1)
2149 end))
2150 (else
2151 (loop rev start (+ pos 1) end)))))
2152
2153 (define (convert-c-registered-modules dynobj)
2154 (let ((res (map (lambda (c)
2155 (list (split-c-module-name (car c)) (cdr c) dynobj))
2156 (c-registered-modules))))
2157 (c-clear-registered-modules)
2158 res))
2159
2160 (define registered-modules '())
2161
2162 (define (register-modules dynobj)
2163 (set! registered-modules
2164 (append! (convert-c-registered-modules dynobj)
2165 registered-modules)))
2166
2167 (define (init-dynamic-module modname)
2168 ;; Register any linked modules which has been registered on the C level
2169 (register-modules #f)
2170 (or-map (lambda (modinfo)
2171 (if (equal? (car modinfo) modname)
2172 (begin
2173 (set! registered-modules (delq! modinfo registered-modules))
2174 (let ((mod (resolve-module modname #f)))
2175 (save-module-excursion
2176 (lambda ()
2177 (set-current-module mod)
2178 (set-module-public-interface! mod mod)
2179 (dynamic-call (cadr modinfo) (caddr modinfo))
2180 ))
2181 #t))
2182 #f))
2183 registered-modules))
2184
2185 (define (dynamic-maybe-call name dynobj)
2186 (catch #t ; could use false-if-exception here
2187 (lambda ()
2188 (dynamic-call name dynobj))
2189 (lambda args
2190 #f)))
2191
2192 (define (dynamic-maybe-link filename)
2193 (catch #t ; could use false-if-exception here
2194 (lambda ()
2195 (dynamic-link filename))
2196 (lambda args
2197 #f)))
2198
2199 (define (find-and-link-dynamic-module module-name)
2200 (define (make-init-name mod-name)
2201 (string-append 'scm_init
2202 (list->string (map (lambda (c)
2203 (if (or (char-alphabetic? c)
2204 (char-numeric? c))
2205 c
2206 #\_))
2207 (string->list mod-name)))
2208 '_module))
2209
2210 ;; Put the subdirectory for this module in the car of SUBDIR-AND-LIBNAME,
2211 ;; and the `libname' (the name of the module prepended by `lib') in the cdr
2212 ;; field. For example, if MODULE-NAME is the list (inet tcp-ip udp), then
2213 ;; SUBDIR-AND-LIBNAME will be the pair ("inet/tcp-ip" . "libudp").
2214 (let ((subdir-and-libname
2215 (let loop ((dirs "")
2216 (syms module-name))
2217 (if (null? (cdr syms))
2218 (cons dirs (string-append "lib" (car syms)))
2219 (loop (string-append dirs (car syms) "/") (cdr syms)))))
2220 (init (make-init-name (apply string-append
2221 (map (lambda (s)
2222 (string-append "_" s))
2223 module-name)))))
2224 (let ((subdir (car subdir-and-libname))
2225 (libname (cdr subdir-and-libname)))
2226
2227 ;; Now look in each dir in %LOAD-PATH for `subdir/libfoo.la'. If that
2228 ;; file exists, fetch the dlname from that file and attempt to link
2229 ;; against it. If `subdir/libfoo.la' does not exist, or does not seem
2230 ;; to name any shared library, look for `subdir/libfoo.so' instead and
2231 ;; link against that.
2232 (let check-dirs ((dir-list %load-path))
2233 (if (null? dir-list)
2234 #f
2235 (let* ((dir (in-vicinity (car dir-list) subdir))
2236 (sharlib-full
2237 (or (try-using-libtool-name dir libname)
2238 (try-using-sharlib-name dir libname))))
2239 (if (and sharlib-full (file-exists? sharlib-full))
2240 (link-dynamic-module sharlib-full init)
2241 (check-dirs (cdr dir-list)))))))))
2242
2243 (define (try-using-libtool-name libdir libname)
2244 (let ((libtool-filename (in-vicinity libdir
2245 (string-append libname ".la"))))
2246 (and (file-exists? libtool-filename)
2247 (with-input-from-file libtool-filename
2248 (lambda ()
2249 (let loop ((ln (read-line)))
2250 (cond ((eof-object? ln) #f)
2251 ((and (> (string-length ln) 9)
2252 (string=? "dlname='" (substring ln 0 8))
2253 (string-index ln #\' 8))
2254 =>
2255 (lambda (end)
2256 (in-vicinity libdir (substring ln 8 end))))
2257 (else (loop (read-line))))))))))
2258
2259 (define (try-using-sharlib-name libdir libname)
2260 (in-vicinity libdir (string-append libname ".so")))
2261
2262 (define (link-dynamic-module filename initname)
2263 ;; Register any linked modules which has been registered on the C level
2264 (register-modules #f)
2265 (let ((dynobj (dynamic-link filename)))
2266 (dynamic-call initname dynobj)
2267 (register-modules dynobj)))
2268
2269 (define (try-module-linked module-name)
2270 (init-dynamic-module module-name))
2271
2272 (define (try-module-dynamic-link module-name)
2273 (and (find-and-link-dynamic-module module-name)
2274 (init-dynamic-module module-name)))
2275
2276
2277
2278 (define autoloads-done '((guile . guile)))
2279
2280 (define (autoload-done-or-in-progress? p m)
2281 (let ((n (cons p m)))
2282 (->bool (or (member n autoloads-done)
2283 (member n autoloads-in-progress)))))
2284
2285 (define (autoload-done! p m)
2286 (let ((n (cons p m)))
2287 (set! autoloads-in-progress
2288 (delete! n autoloads-in-progress))
2289 (or (member n autoloads-done)
2290 (set! autoloads-done (cons n autoloads-done)))))
2291
2292 (define (autoload-in-progress! p m)
2293 (let ((n (cons p m)))
2294 (set! autoloads-done
2295 (delete! n autoloads-done))
2296 (set! autoloads-in-progress (cons n autoloads-in-progress))))
2297
2298 (define (set-autoloaded! p m done?)
2299 (if done?
2300 (autoload-done! p m)
2301 (let ((n (cons p m)))
2302 (set! autoloads-done (delete! n autoloads-done))
2303 (set! autoloads-in-progress (delete! n autoloads-in-progress)))))
2304
2305
2306
2307
2308 \f
2309 ;;; {Macros}
2310 ;;;
2311
2312 (define (primitive-macro? m)
2313 (and (macro? m)
2314 (not (macro-transformer m))))
2315
2316 ;;; {Defmacros}
2317 ;;;
2318 (define macro-table (make-weak-key-hash-table 523))
2319 (define xformer-table (make-weak-key-hash-table 523))
2320
2321 (define (defmacro? m) (hashq-ref macro-table m))
2322 (define (assert-defmacro?! m) (hashq-set! macro-table m #t))
2323 (define (defmacro-transformer m) (hashq-ref xformer-table m))
2324 (define (set-defmacro-transformer! m t) (hashq-set! xformer-table m t))
2325
2326 (define defmacro:transformer
2327 (lambda (f)
2328 (let* ((xform (lambda (exp env)
2329 (copy-tree (apply f (cdr exp)))))
2330 (a (procedure->memoizing-macro xform)))
2331 (assert-defmacro?! a)
2332 (set-defmacro-transformer! a f)
2333 a)))
2334
2335
2336 (define defmacro
2337 (let ((defmacro-transformer
2338 (lambda (name parms . body)
2339 (let ((transformer `(lambda ,parms ,@body)))
2340 `(define ,name
2341 (,(lambda (transformer)
2342 (defmacro:transformer transformer))
2343 ,transformer))))))
2344 (defmacro:transformer defmacro-transformer)))
2345
2346 (define defmacro:syntax-transformer
2347 (lambda (f)
2348 (procedure->syntax
2349 (lambda (exp env)
2350 (copy-tree (apply f (cdr exp)))))))
2351
2352
2353 ;; XXX - should the definition of the car really be looked up in the
2354 ;; current module?
2355
2356 (define (macroexpand-1 e)
2357 (cond
2358 ((pair? e) (let* ((a (car e))
2359 (val (and (symbol? a) (local-ref (list a)))))
2360 (if (defmacro? val)
2361 (apply (defmacro-transformer val) (cdr e))
2362 e)))
2363 (#t e)))
2364
2365 (define (macroexpand e)
2366 (cond
2367 ((pair? e) (let* ((a (car e))
2368 (val (and (symbol? a) (local-ref (list a)))))
2369 (if (defmacro? val)
2370 (macroexpand (apply (defmacro-transformer val) (cdr e)))
2371 e)))
2372 (#t e)))
2373
2374 (define (gentemp)
2375 (gensym "scm:G"))
2376
2377 (provide 'defmacro)
2378
2379 \f
2380
2381 ;;; {Run-time options}
2382
2383 ((let* ((names '((eval-options-interface
2384 (eval-options eval-enable eval-disable)
2385 (eval-set!))
2386
2387 (debug-options-interface
2388 (debug-options debug-enable debug-disable)
2389 (debug-set!))
2390
2391 (evaluator-traps-interface
2392 (traps trap-enable trap-disable)
2393 (trap-set!))
2394
2395 (read-options-interface
2396 (read-options read-enable read-disable)
2397 (read-set!))
2398
2399 (print-options-interface
2400 (print-options print-enable print-disable)
2401 (print-set!))
2402
2403 (readline-options-interface
2404 (readline-options readline-enable readline-disable)
2405 (readline-set!))
2406 ))
2407 (option-name car)
2408 (option-value cadr)
2409 (option-documentation caddr)
2410
2411 (print-option (lambda (option)
2412 (display (option-name option))
2413 (if (< (string-length
2414 (symbol->string (option-name option)))
2415 8)
2416 (display #\tab))
2417 (display #\tab)
2418 (display (option-value option))
2419 (display #\tab)
2420 (display (option-documentation option))
2421 (newline)))
2422
2423 ;; Below follows the macros defining the run-time option interfaces.
2424
2425 (make-options (lambda (interface)
2426 `(lambda args
2427 (cond ((null? args) (,interface))
2428 ((list? (car args))
2429 (,interface (car args)) (,interface))
2430 (else (for-each ,print-option
2431 (,interface #t)))))))
2432
2433 (make-enable (lambda (interface)
2434 `(lambda flags
2435 (,interface (append flags (,interface)))
2436 (,interface))))
2437
2438 (make-disable (lambda (interface)
2439 `(lambda flags
2440 (let ((options (,interface)))
2441 (for-each (lambda (flag)
2442 (set! options (delq! flag options)))
2443 flags)
2444 (,interface options)
2445 (,interface)))))
2446
2447 (make-set! (lambda (interface)
2448 `((name exp)
2449 (,'quasiquote
2450 (begin (,interface (append (,interface)
2451 (list '(,'unquote name)
2452 (,'unquote exp))))
2453 (,interface))))))
2454 )
2455 (procedure->macro
2456 (lambda (exp env)
2457 (cons 'begin
2458 (apply append
2459 (map (lambda (group)
2460 (let ((interface (car group)))
2461 (append (map (lambda (name constructor)
2462 `(define ,name
2463 ,(constructor interface)))
2464 (cadr group)
2465 (list make-options
2466 make-enable
2467 make-disable))
2468 (map (lambda (name constructor)
2469 `(defmacro ,name
2470 ,@(constructor interface)))
2471 (caddr group)
2472 (list make-set!)))))
2473 names)))))))
2474
2475 \f
2476
2477 ;;; {Running Repls}
2478 ;;;
2479
2480 (define (repl read evaler print)
2481 (let loop ((source (read (current-input-port))))
2482 (print (evaler source))
2483 (loop (read (current-input-port)))))
2484
2485 ;; A provisional repl that acts like the SCM repl:
2486 ;;
2487 (define scm-repl-silent #f)
2488 (define (assert-repl-silence v) (set! scm-repl-silent v))
2489
2490 (define *unspecified* (if #f #f))
2491 (define (unspecified? v) (eq? v *unspecified*))
2492
2493 (define scm-repl-print-unspecified #f)
2494 (define (assert-repl-print-unspecified v) (set! scm-repl-print-unspecified v))
2495
2496 (define scm-repl-verbose #f)
2497 (define (assert-repl-verbosity v) (set! scm-repl-verbose v))
2498
2499 (define scm-repl-prompt "guile> ")
2500
2501 (define (set-repl-prompt! v) (set! scm-repl-prompt v))
2502
2503 (define (default-lazy-handler key . args)
2504 (save-stack lazy-handler-dispatch)
2505 (apply throw key args))
2506
2507 (define enter-frame-handler default-lazy-handler)
2508 (define apply-frame-handler default-lazy-handler)
2509 (define exit-frame-handler default-lazy-handler)
2510
2511 (define (lazy-handler-dispatch key . args)
2512 (case key
2513 ((apply-frame)
2514 (apply apply-frame-handler key args))
2515 ((exit-frame)
2516 (apply exit-frame-handler key args))
2517 ((enter-frame)
2518 (apply enter-frame-handler key args))
2519 (else
2520 (apply default-lazy-handler key args))))
2521
2522 (define abort-hook (make-hook))
2523
2524 ;; these definitions are used if running a script.
2525 ;; otherwise redefined in error-catching-loop.
2526 (define (set-batch-mode?! arg) #t)
2527 (define (batch-mode?) #t)
2528
2529 (define (error-catching-loop thunk)
2530 (let ((status #f)
2531 (interactive #t))
2532 (define (loop first)
2533 (let ((next
2534 (catch #t
2535
2536 (lambda ()
2537 (lazy-catch #t
2538 (lambda ()
2539 (dynamic-wind
2540 (lambda () (unmask-signals))
2541 (lambda ()
2542 (with-traps
2543 (lambda ()
2544 (first)
2545
2546 ;; This line is needed because mark
2547 ;; doesn't do closures quite right.
2548 ;; Unreferenced locals should be
2549 ;; collected.
2550 ;;
2551 (set! first #f)
2552 (let loop ((v (thunk)))
2553 (loop (thunk)))
2554 #f)))
2555 (lambda () (mask-signals))))
2556
2557 lazy-handler-dispatch))
2558
2559 (lambda (key . args)
2560 (case key
2561 ((quit)
2562 (set! status args)
2563 #f)
2564
2565 ((switch-repl)
2566 (apply throw 'switch-repl args))
2567
2568 ((abort)
2569 ;; This is one of the closures that require
2570 ;; (set! first #f) above
2571 ;;
2572 (lambda ()
2573 (run-hook abort-hook)
2574 (force-output (current-output-port))
2575 (display "ABORT: " (current-error-port))
2576 (write args (current-error-port))
2577 (newline (current-error-port))
2578 (if interactive
2579 (begin
2580 (if (and
2581 (not has-shown-debugger-hint?)
2582 (not (memq 'backtrace
2583 (debug-options-interface)))
2584 (stack? (fluid-ref the-last-stack)))
2585 (begin
2586 (newline (current-error-port))
2587 (display
2588 "Type \"(backtrace)\" to get more information.\n"
2589 (current-error-port))
2590 (set! has-shown-debugger-hint? #t)))
2591 (force-output (current-error-port)))
2592 (begin
2593 (primitive-exit 1)))
2594 (set! stack-saved? #f)))
2595
2596 (else
2597 ;; This is the other cons-leak closure...
2598 (lambda ()
2599 (cond ((= (length args) 4)
2600 (apply handle-system-error key args))
2601 (else
2602 (apply bad-throw key args))))))))))
2603 (if next (loop next) status)))
2604 (set! set-batch-mode?! (lambda (arg)
2605 (cond (arg
2606 (set! interactive #f)
2607 (restore-signals))
2608 (#t
2609 (error "sorry, not implemented")))))
2610 (set! batch-mode? (lambda () (not interactive)))
2611 (loop (lambda () #t))))
2612
2613 ;;(define the-last-stack (make-fluid)) Defined by scm_init_backtrace ()
2614 (define stack-saved? #f)
2615
2616 (define (save-stack . narrowing)
2617 (or stack-saved?
2618 (cond ((not (memq 'debug (debug-options-interface)))
2619 (fluid-set! the-last-stack #f)
2620 (set! stack-saved? #t))
2621 (else
2622 (fluid-set!
2623 the-last-stack
2624 (case (stack-id #t)
2625 ((repl-stack)
2626 (apply make-stack #t save-stack eval #t 0 narrowing))
2627 ((load-stack)
2628 (apply make-stack #t save-stack 0 #t 0 narrowing))
2629 ((tk-stack)
2630 (apply make-stack #t save-stack tk-stack-mark #t 0 narrowing))
2631 ((#t)
2632 (apply make-stack #t save-stack 0 1 narrowing))
2633 (else
2634 (let ((id (stack-id #t)))
2635 (and (procedure? id)
2636 (apply make-stack #t save-stack id #t 0 narrowing))))))
2637 (set! stack-saved? #t)))))
2638
2639 (define before-error-hook (make-hook))
2640 (define after-error-hook (make-hook))
2641 (define before-backtrace-hook (make-hook))
2642 (define after-backtrace-hook (make-hook))
2643
2644 (define has-shown-debugger-hint? #f)
2645
2646 (define (handle-system-error key . args)
2647 (let ((cep (current-error-port)))
2648 (cond ((not (stack? (fluid-ref the-last-stack))))
2649 ((memq 'backtrace (debug-options-interface))
2650 (run-hook before-backtrace-hook)
2651 (newline cep)
2652 (display-backtrace (fluid-ref the-last-stack) cep)
2653 (newline cep)
2654 (run-hook after-backtrace-hook)))
2655 (run-hook before-error-hook)
2656 (apply display-error (fluid-ref the-last-stack) cep args)
2657 (run-hook after-error-hook)
2658 (force-output cep)
2659 (throw 'abort key)))
2660
2661 (define (quit . args)
2662 (apply throw 'quit args))
2663
2664 (define exit quit)
2665
2666 ;;(define has-shown-backtrace-hint? #f) Defined by scm_init_backtrace ()
2667
2668 ;; Replaced by C code:
2669 ;;(define (backtrace)
2670 ;; (if (fluid-ref the-last-stack)
2671 ;; (begin
2672 ;; (newline)
2673 ;; (display-backtrace (fluid-ref the-last-stack) (current-output-port))
2674 ;; (newline)
2675 ;; (if (and (not has-shown-backtrace-hint?)
2676 ;; (not (memq 'backtrace (debug-options-interface))))
2677 ;; (begin
2678 ;; (display
2679 ;;"Type \"(debug-enable 'backtrace)\" if you would like a backtrace
2680 ;;automatically if an error occurs in the future.\n")
2681 ;; (set! has-shown-backtrace-hint? #t))))
2682 ;; (display "No backtrace available.\n")))
2683
2684 (define (error-catching-repl r e p)
2685 (error-catching-loop (lambda () (p (e (r))))))
2686
2687 (define (gc-run-time)
2688 (cdr (assq 'gc-time-taken (gc-stats))))
2689
2690 (define before-read-hook (make-hook))
2691 (define after-read-hook (make-hook))
2692
2693 ;;; The default repl-reader function. We may override this if we've
2694 ;;; the readline library.
2695 (define repl-reader
2696 (lambda (prompt)
2697 (display prompt)
2698 (force-output)
2699 (run-hook before-read-hook)
2700 (read (current-input-port))))
2701
2702 (define (scm-style-repl)
2703 (letrec (
2704 (start-gc-rt #f)
2705 (start-rt #f)
2706 (repl-report-start-timing (lambda ()
2707 (set! start-gc-rt (gc-run-time))
2708 (set! start-rt (get-internal-run-time))))
2709 (repl-report (lambda ()
2710 (display ";;; ")
2711 (display (inexact->exact
2712 (* 1000 (/ (- (get-internal-run-time) start-rt)
2713 internal-time-units-per-second))))
2714 (display " msec (")
2715 (display (inexact->exact
2716 (* 1000 (/ (- (gc-run-time) start-gc-rt)
2717 internal-time-units-per-second))))
2718 (display " msec in gc)\n")))
2719
2720 (consume-trailing-whitespace
2721 (lambda ()
2722 (let ((ch (peek-char)))
2723 (cond
2724 ((eof-object? ch))
2725 ((or (char=? ch #\space) (char=? ch #\tab))
2726 (read-char)
2727 (consume-trailing-whitespace))
2728 ((char=? ch #\newline)
2729 (read-char))))))
2730 (-read (lambda ()
2731 (let ((val
2732 (let ((prompt (cond ((string? scm-repl-prompt)
2733 scm-repl-prompt)
2734 ((thunk? scm-repl-prompt)
2735 (scm-repl-prompt))
2736 (scm-repl-prompt "> ")
2737 (else ""))))
2738 (repl-reader prompt))))
2739
2740 ;; As described in R4RS, the READ procedure updates the
2741 ;; port to point to the first character past the end of
2742 ;; the external representation of the object. This
2743 ;; means that it doesn't consume the newline typically
2744 ;; found after an expression. This means that, when
2745 ;; debugging Guile with GDB, GDB gets the newline, which
2746 ;; it often interprets as a "continue" command, making
2747 ;; breakpoints kind of useless. So, consume any
2748 ;; trailing newline here, as well as any whitespace
2749 ;; before it.
2750 ;; But not if EOF, for control-D.
2751 (if (not (eof-object? val))
2752 (consume-trailing-whitespace))
2753 (run-hook after-read-hook)
2754 (if (eof-object? val)
2755 (begin
2756 (repl-report-start-timing)
2757 (if scm-repl-verbose
2758 (begin
2759 (newline)
2760 (display ";;; EOF -- quitting")
2761 (newline)))
2762 (quit 0)))
2763 val)))
2764
2765 (-eval (lambda (sourc)
2766 (repl-report-start-timing)
2767 (start-stack 'repl-stack (eval sourc))))
2768
2769 (-print (lambda (result)
2770 (if (not scm-repl-silent)
2771 (begin
2772 (if (or scm-repl-print-unspecified
2773 (not (unspecified? result)))
2774 (begin
2775 (write result)
2776 (newline)))
2777 (if scm-repl-verbose
2778 (repl-report))
2779 (force-output)))))
2780
2781 (-quit (lambda (args)
2782 (if scm-repl-verbose
2783 (begin
2784 (display ";;; QUIT executed, repl exitting")
2785 (newline)
2786 (repl-report)))
2787 args))
2788
2789 (-abort (lambda ()
2790 (if scm-repl-verbose
2791 (begin
2792 (display ";;; ABORT executed.")
2793 (newline)
2794 (repl-report)))
2795 (repl -read -eval -print))))
2796
2797 (let ((status (error-catching-repl -read
2798 -eval
2799 -print)))
2800 (-quit status))))
2801
2802
2803 \f
2804 ;;; {IOTA functions: generating lists of numbers}
2805
2806 (define (iota n)
2807 (let loop ((count (1- n)) (result '()))
2808 (if (< count 0) result
2809 (loop (1- count) (cons count result)))))
2810
2811 \f
2812 ;;; {While}
2813 ;;;
2814 ;;; with `continue' and `break'.
2815 ;;;
2816
2817 (defmacro while (cond . body)
2818 `(letrec ((continue (lambda () (or (not ,cond) (begin (begin ,@ body) (continue)))))
2819 (break (lambda val (apply throw 'break val))))
2820 (catch 'break
2821 (lambda () (continue))
2822 (lambda v (cadr v)))))
2823
2824 ;;; {collect}
2825 ;;;
2826 ;;; Similar to `begin' but returns a list of the results of all constituent
2827 ;;; forms instead of the result of the last form.
2828 ;;; (The definition relies on the current left-to-right
2829 ;;; order of evaluation of operands in applications.)
2830
2831 (defmacro collect forms
2832 (cons 'list forms))
2833
2834 ;;; {with-fluids}
2835
2836 ;; with-fluids is a convenience wrapper for the builtin procedure
2837 ;; `with-fluids*'. The syntax is just like `let':
2838 ;;
2839 ;; (with-fluids ((fluid val)
2840 ;; ...)
2841 ;; body)
2842
2843 (defmacro with-fluids (bindings . body)
2844 `(with-fluids* (list ,@(map car bindings)) (list ,@(map cadr bindings))
2845 (lambda () ,@body)))
2846
2847 ;;; Environments
2848
2849 (define the-environment
2850 (procedure->syntax
2851 (lambda (x e)
2852 e)))
2853
2854 (define (environment-module env)
2855 (let ((closure (and (pair? env) (car (last-pair env)))))
2856 (and closure (procedure-property closure 'module))))
2857
2858 \f
2859
2860 ;;; {Macros}
2861 ;;;
2862
2863 ;; actually....hobbit might be able to hack these with a little
2864 ;; coaxing
2865 ;;
2866
2867 (defmacro define-macro (first . rest)
2868 (let ((name (if (symbol? first) first (car first)))
2869 (transformer
2870 (if (symbol? first)
2871 (car rest)
2872 `(lambda ,(cdr first) ,@rest))))
2873 `(define ,name (defmacro:transformer ,transformer))))
2874
2875
2876 (defmacro define-syntax-macro (first . rest)
2877 (let ((name (if (symbol? first) first (car first)))
2878 (transformer
2879 (if (symbol? first)
2880 (car rest)
2881 `(lambda ,(cdr first) ,@rest))))
2882 `(define ,name (defmacro:syntax-transformer ,transformer))))
2883 \f
2884 ;;; {Module System Macros}
2885 ;;;
2886
2887 (defmacro define-module args
2888 `(let* ((process-define-module process-define-module)
2889 (set-current-module set-current-module)
2890 (module (process-define-module ',args)))
2891 (set-current-module module)
2892 module))
2893
2894 ;; the guts of the use-modules macro. add the interfaces of the named
2895 ;; modules to the use-list of the current module, in order
2896 (define (process-use-modules module-names)
2897 (for-each (lambda (module-name)
2898 (let ((mod-iface (resolve-interface module-name)))
2899 (or mod-iface
2900 (error "no such module" module-name))
2901 (module-use! (current-module) mod-iface)))
2902 (reverse module-names)))
2903
2904 (defmacro use-modules modules
2905 `(process-use-modules ',modules))
2906
2907 (defmacro use-syntax (spec)
2908 `(begin
2909 ,@(if (pair? spec)
2910 `((process-use-modules ',(list spec))
2911 (set-module-transformer! (current-module)
2912 ,(car (last-pair spec))))
2913 `((set-module-transformer! (current-module) ,spec)))
2914 (set! scm:eval-transformer (module-transformer (current-module)))))
2915
2916 (define define-private define)
2917
2918 (defmacro define-public args
2919 (define (syntax)
2920 (error "bad syntax" (list 'define-public args)))
2921 (define (defined-name n)
2922 (cond
2923 ((symbol? n) n)
2924 ((pair? n) (defined-name (car n)))
2925 (else (syntax))))
2926 (cond
2927 ((null? args) (syntax))
2928
2929 (#t (let ((name (defined-name (car args))))
2930 `(begin
2931 (let ((public-i (module-public-interface (current-module))))
2932 ;; Make sure there is a local variable:
2933 ;;
2934 (module-define! (current-module)
2935 ',name
2936 (module-ref (current-module) ',name #f))
2937
2938 ;; Make sure that local is exported:
2939 ;;
2940 (module-add! public-i ',name
2941 (module-variable (current-module) ',name)))
2942
2943 ;; Now (re)define the var normally. Bernard URBAN
2944 ;; suggests we use eval here to accomodate Hobbit; it lets
2945 ;; the interpreter handle the define-private form, which
2946 ;; Hobbit can't digest.
2947 (eval '(define-private ,@ args)))))))
2948
2949
2950
2951 (defmacro defmacro-public args
2952 (define (syntax)
2953 (error "bad syntax" (list 'defmacro-public args)))
2954 (define (defined-name n)
2955 (cond
2956 ((symbol? n) n)
2957 (else (syntax))))
2958 (cond
2959 ((null? args) (syntax))
2960
2961 (#t (let ((name (defined-name (car args))))
2962 `(begin
2963 (let ((public-i (module-public-interface (current-module))))
2964 ;; Make sure there is a local variable:
2965 ;;
2966 (module-define! (current-module)
2967 ',name
2968 (module-ref (current-module) ',name #f))
2969
2970 ;; Make sure that local is exported:
2971 ;;
2972 (module-add! public-i ',name (module-variable (current-module) ',name)))
2973
2974 ;; Now (re)define the var normally.
2975 ;;
2976 (defmacro ,@ args))))))
2977
2978
2979 (defmacro export names
2980 `(let* ((m (current-module))
2981 (public-i (module-public-interface m)))
2982 (for-each (lambda (name)
2983 ;; Make sure there is a local variable:
2984 (module-define! m name (module-ref m name #f))
2985 ;; Make sure that local is exported:
2986 (module-add! public-i name (module-variable m name)))
2987 ',names)))
2988
2989 (define export-syntax export)
2990
2991
2992
2993
2994 (define load load-module)
2995
2996
2997 \f
2998 ;;; {Load emacs interface support if emacs option is given.}
2999
3000 (define (load-emacs-interface)
3001 (if (memq 'debug-extensions *features*)
3002 (debug-enable 'backtrace))
3003 (define-module (guile-user) :use-module (ice-9 emacs)))
3004
3005 \f
3006 ;;; {I/O functions for Tcl channels (disabled)}
3007
3008 ;; (define in-ch (get-standard-channel TCL_STDIN))
3009 ;; (define out-ch (get-standard-channel TCL_STDOUT))
3010 ;; (define err-ch (get-standard-channel TCL_STDERR))
3011 ;;
3012 ;; (define inp (%make-channel-port in-ch "r"))
3013 ;; (define outp (%make-channel-port out-ch "w"))
3014 ;; (define errp (%make-channel-port err-ch "w"))
3015 ;;
3016 ;; (define %system-char-ready? char-ready?)
3017 ;;
3018 ;; (define (char-ready? p)
3019 ;; (if (not (channel-port? p))
3020 ;; (%system-char-ready? p)
3021 ;; (let* ((channel (%channel-port-channel p))
3022 ;; (old-blocking (channel-option-ref channel :blocking)))
3023 ;; (dynamic-wind
3024 ;; (lambda () (set-channel-option the-root-tcl-interpreter channel :blocking "0"))
3025 ;; (lambda () (not (eof-object? (peek-char p))))
3026 ;; (lambda () (set-channel-option the-root-tcl-interpreter channel :blocking old-blocking))))))
3027 ;;
3028 ;; (define (top-repl)
3029 ;; (with-input-from-port inp
3030 ;; (lambda ()
3031 ;; (with-output-to-port outp
3032 ;; (lambda ()
3033 ;; (with-error-to-port errp
3034 ;; (lambda ()
3035 ;; (scm-style-repl))))))))
3036 ;;
3037 ;; (set-current-input-port inp)
3038 ;; (set-current-output-port outp)
3039 ;; (set-current-error-port errp)
3040
3041 ;; this is just (scm-style-repl) with a wrapper to install and remove
3042 ;; signal handlers.
3043 (define (top-repl)
3044
3045 ;; Load emacs interface support if emacs option is given.
3046 (if (and (module-defined? the-root-module 'use-emacs-interface)
3047 use-emacs-interface)
3048 (load-emacs-interface))
3049
3050 ;; Place the user in the guile-user module.
3051 (define-module (guile-user))
3052
3053 (let ((old-handlers #f)
3054 (signals `((,SIGINT . "User interrupt")
3055 (,SIGFPE . "Arithmetic error")
3056 (,SIGBUS . "Bad memory access (bus error)")
3057 (,SIGSEGV . "Bad memory access (Segmentation violation)"))))
3058
3059 (dynamic-wind
3060
3061 ;; call at entry
3062 (lambda ()
3063 (let ((make-handler (lambda (msg)
3064 (lambda (sig)
3065 (save-stack %deliver-signals)
3066 (scm-error 'signal
3067 #f
3068 msg
3069 #f
3070 (list sig))))))
3071 (set! old-handlers
3072 (map (lambda (sig-msg)
3073 (sigaction (car sig-msg)
3074 (make-handler (cdr sig-msg))))
3075 signals))))
3076
3077 ;; the protected thunk.
3078 (lambda ()
3079
3080 ;; If we've got readline, use it to prompt the user. This is a
3081 ;; kludge, but we'll fix it soon. At least we only get
3082 ;; readline involved when we're actually running the repl.
3083 (if (and (memq 'readline *features*)
3084 (isatty? (current-input-port))
3085 (not (and (module-defined? the-root-module
3086 'use-emacs-interface)
3087 use-emacs-interface)))
3088 (let ((read-hook (lambda () (run-hook before-read-hook))))
3089 (set-current-input-port (readline-port))
3090 (set! repl-reader
3091 (lambda (prompt)
3092 (dynamic-wind
3093 (lambda ()
3094 (set-readline-prompt! prompt "... ")
3095 (set-readline-read-hook! read-hook))
3096 (lambda () (read))
3097 (lambda ()
3098 (set-readline-prompt! "" "")
3099 (set-readline-read-hook! #f)))))))
3100 (let ((status (scm-style-repl)))
3101 (run-hook exit-hook)
3102 status))
3103
3104 ;; call at exit.
3105 (lambda ()
3106 (map (lambda (sig-msg old-handler)
3107 (if (not (car old-handler))
3108 ;; restore original C handler.
3109 (sigaction (car sig-msg) #f)
3110 ;; restore Scheme handler, SIG_IGN or SIG_DFL.
3111 (sigaction (car sig-msg)
3112 (car old-handler)
3113 (cdr old-handler))))
3114 signals old-handlers)))))
3115
3116 (defmacro false-if-exception (expr)
3117 `(catch #t (lambda () ,expr)
3118 (lambda args #f)))
3119
3120 ;;; This hook is run at the very end of an interactive session.
3121 ;;;
3122 (define exit-hook (make-hook))
3123
3124 ;;; Load readline code into root module if readline primitives are available.
3125 ;;;
3126 ;;; Ideally, we wouldn't do this until we were sure we were actually
3127 ;;; going to enter the repl, but autoloading individual functions is
3128 ;;; clumsy at the moment.
3129 (if (and (memq 'readline *features*)
3130 (isatty? (current-input-port)))
3131 (begin
3132 (define-module (guile) :use-module (ice-9 readline))
3133 (define-module (guile-user) :use-module (ice-9 readline))))
3134
3135 \f
3136 ;;; {Load debug extension code into user module if debug extensions present.}
3137 ;;;
3138 ;;; *fixme* This is a temporary solution.
3139 ;;;
3140
3141 (if (memq 'debug-extensions *features*)
3142 (define-module (guile-user) :use-module (ice-9 debug)))
3143
3144 \f
3145 ;;; {Load session support into user module if present.}
3146 ;;;
3147 ;;; *fixme* This is a temporary solution.
3148 ;;;
3149
3150 (if (%search-load-path "ice-9/session.scm")
3151 (define-module (guile-user) :use-module (ice-9 session)))
3152
3153 ;;; {Load thread code into user module if threads are present.}
3154 ;;;
3155 ;;; *fixme* This is a temporary solution.
3156 ;;;
3157
3158 (if (memq 'threads *features*)
3159 (define-module (guile-user) :use-module (ice-9 threads)))
3160
3161 \f
3162 ;;; {Load regexp code if regexp primitives are available.}
3163
3164 (if (memq 'regex *features*)
3165 (define-module (guile-user) :use-module (ice-9 regex)))
3166
3167 \f
3168 (define-module (guile))
3169
3170 ;;; {Check that the interpreter and scheme code match up.}
3171
3172 (let ((show-line
3173 (lambda args
3174 (with-output-to-port (current-error-port)
3175 (lambda ()
3176 (display (car (command-line)))
3177 (display ": ")
3178 (for-each (lambda (string) (display string))
3179 args)
3180 (newline))))))
3181
3182 (load-from-path "ice-9/version.scm")
3183
3184 (if (not (string=?
3185 (libguile-config-stamp) ; from the interprpreter
3186 (ice-9-config-stamp))) ; from the Scheme code
3187 (begin
3188 (show-line "warning: different versions of libguile and ice-9:")
3189 (show-line "libguile: configured on " (libguile-config-stamp))
3190 (show-line "ice-9: configured on " (ice-9-config-stamp)))))
3191
3192 (append! %load-path (cons "." ()))
3193