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