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