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