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