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