*** empty log message ***
[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
cf266109
MD
1973(define (internal-use-syntax transformer)
1974 (set-module-transformer! (current-module) transformer)
1975 (set! scm:eval-transformer transformer))
1976
0f2d19dd
JB
1977(define (process-define-module args)
1978 (let* ((module-id (car args))
0209ca9a 1979 (module (resolve-module module-id #f))
0f2d19dd
JB
1980 (kws (cdr args)))
1981 (beautify-user-module! module)
0209ca9a
MV
1982 (let loop ((kws kws)
1983 (reversed-interfaces '()))
1984 (if (null? kws)
1985 (for-each (lambda (interface)
1986 (module-use! module interface))
1987 reversed-interfaces)
f714ca8e
MD
1988 (let ((keyword (cond ((keyword? (car kws))
1989 (keyword->symbol (car kws)))
1990 ((and (symbol? (car kws))
1991 (eq? (string-ref (car kws) 0) #\:))
1992 (string->symbol (substring (car kws) 1)))
1993 (else #f))))
1994 (case keyword
1995 ((use-module use-syntax)
1996 (if (not (pair? (cdr kws)))
1997 (error "unrecognized defmodule argument" kws))
1998 (let* ((used-name (cadr kws))
1999 (used-module (resolve-module used-name)))
45a02a29
MD
2000 (if (not (module-ref used-module
2001 '%module-public-interface
2002 #f))
3e3cec45 2003 (begin
45a02a29
MD
2004 ((if %autoloader-developer-mode warn error)
2005 "no code for module" (module-name used-module))
2006 (beautify-user-module! used-module)))
2007 (let ((interface (module-public-interface used-module)))
2008 (if (not interface)
2009 (error "missing interface for use-module"
2010 used-module))
2011 (if (eq? keyword 'use-syntax)
2012 (internal-use-syntax
2013 (module-ref interface (car (last-pair used-name))
2014 #f)))
2015 (loop (cddr kws)
2016 (cons interface reversed-interfaces)))))
71225060
MD
2017 ((autoload)
2018 (if (not (and (pair? (cdr kws)) (pair? (cddr kws))))
2019 (error "unrecognized defmodule argument" kws))
2020 (loop (cdddr kws)
2021 (cons (make-autoload-interface module
2022 (cadr kws)
2023 (caddr kws))
2024 reversed-interfaces)))
edc185c7
MD
2025 ((no-backtrace)
2026 (set-system-module! module #t)
2027 (loop (cdr kws) reversed-interfaces))
f714ca8e
MD
2028 (else
2029 (error "unrecognized defmodule argument" kws))))))
0f2d19dd 2030 module))
71225060
MD
2031
2032;;; {Autoload}
2033
2034(define (make-autoload-interface module name bindings)
2035 (let ((b (lambda (a sym definep)
2036 (and (memq sym bindings)
2037 (let ((i (module-public-interface (resolve-module name))))
2038 (if (not i)
2039 (error "missing interface for module" name))
2040 ;; Replace autoload-interface with interface
2041 (set-car! (memq a (module-uses module)) i)
2042 (module-local-variable i sym))))))
2043 (module-constructor #() #f b #f #f name 'autoload)))
2044
0f2d19dd 2045\f
44cf1f0f 2046;;; {Autoloading modules}
0f2d19dd
JB
2047
2048(define autoloads-in-progress '())
2049
2050(define (try-module-autoload module-name)
6fa8995c 2051
0f2d19dd
JB
2052 (define (sfx name) (string-append name (scheme-file-suffix)))
2053 (let* ((reverse-name (reverse module-name))
2054 (name (car reverse-name))
2055 (dir-hint-module-name (reverse (cdr reverse-name)))
2056 (dir-hint (apply symbol-append (map (lambda (elt) (symbol-append elt "/")) dir-hint-module-name))))
0209ca9a 2057 (resolve-module dir-hint-module-name #f)
0f2d19dd
JB
2058 (and (not (autoload-done-or-in-progress? dir-hint name))
2059 (let ((didit #f))
2060 (dynamic-wind
2061 (lambda () (autoload-in-progress! dir-hint name))
2062 (lambda ()
2063 (let loop ((dirs %load-path))
2064 (and (not (null? dirs))
2065 (or
2066 (let ((d (car dirs))
2067 (trys (list
2068 dir-hint
2069 (sfx dir-hint)
2070 (in-vicinity dir-hint name)
2071 (in-vicinity dir-hint (sfx name)))))
2072 (and (or-map (lambda (f)
2073 (let ((full (in-vicinity d f)))
2074 full
6fa8995c
GH
2075 (and (file-exists? full)
2076 (not (file-is-directory? full))
0f2d19dd
JB
2077 (begin
2078 (save-module-excursion
2079 (lambda ()
5552355a
GH
2080 (load (string-append
2081 d "/" f))))
0f2d19dd
JB
2082 #t))))
2083 trys)
2084 (begin
2085 (set! didit #t)
2086 #t)))
2087 (loop (cdr dirs))))))
2088 (lambda () (set-autoloaded! dir-hint name didit)))
2089 didit))))
2090
71225060 2091\f
d0cbd20c
MV
2092;;; Dynamic linking of modules
2093
2094;; Initializing a module that is written in C is a two step process.
2095;; First the module's `module init' function is called. This function
2096;; is expected to call `scm_register_module_xxx' to register the `real
2097;; init' function. Later, when the module is referenced for the first
2098;; time, this real init function is called in the right context. See
2099;; gtcltk-lib/gtcltk-module.c for an example.
2100;;
2101;; The code for the module can be in a regular shared library (so that
2102;; the `module init' function will be called when libguile is
2103;; initialized). Or it can be dynamically linked.
2104;;
2105;; You can safely call `scm_register_module_xxx' before libguile
2106;; itself is initialized. You could call it from an C++ constructor
2107;; of a static object, for example.
2108;;
2109;; To make your Guile extension into a dynamic linkable module, follow
2110;; these easy steps:
2111;;
8bb7330c 2112;; - Find a name for your module, like (ice-9 gtcltk)
d0cbd20c
MV
2113;; - Write a function with a name like
2114;;
2115;; scm_init_ice_9_gtcltk_module
2116;;
2117;; This is your `module init' function. It should call
2118;;
2119;; scm_register_module_xxx ("ice-9 gtcltk", scm_init_gtcltk);
2120;;
2121;; "ice-9 gtcltk" is the C version of the module name. Slashes are
2122;; replaced by spaces, the rest is untouched. `scm_init_gtcltk' is
ed218d98 2123;; the real init function that executes the usual initializations
d0cbd20c
MV
2124;; like making new smobs, etc.
2125;;
2126;; - Make a shared library with your code and a name like
2127;;
2128;; ice-9/libgtcltk.so
2129;;
2130;; and put it somewhere in %load-path.
2131;;
8bb7330c 2132;; - Then you can simply write `:use-module (ice-9 gtcltk)' and it
d0cbd20c
MV
2133;; will be linked automatically.
2134;;
2135;; This is all very experimental.
2136
2137(define (split-c-module-name str)
2138 (let loop ((rev '())
2139 (start 0)
2140 (pos 0)
2141 (end (string-length str)))
2142 (cond
2143 ((= pos end)
2144 (reverse (cons (string->symbol (substring str start pos)) rev)))
2145 ((eq? (string-ref str pos) #\space)
2146 (loop (cons (string->symbol (substring str start pos)) rev)
2147 (+ pos 1)
2148 (+ pos 1)
2149 end))
2150 (else
2151 (loop rev start (+ pos 1) end)))))
2152
2153(define (convert-c-registered-modules dynobj)
2154 (let ((res (map (lambda (c)
2155 (list (split-c-module-name (car c)) (cdr c) dynobj))
2156 (c-registered-modules))))
2157 (c-clear-registered-modules)
2158 res))
2159
3e3cec45
MD
2160(define registered-modules '())
2161
2162(define (register-modules dynobj)
2163 (set! registered-modules
2164 (append! (convert-c-registered-modules dynobj)
2165 registered-modules)))
2166
d0cbd20c 2167(define (init-dynamic-module modname)
3e3cec45
MD
2168 ;; Register any linked modules which has been registered on the C level
2169 (register-modules #f)
d0cbd20c
MV
2170 (or-map (lambda (modinfo)
2171 (if (equal? (car modinfo) modname)
c04e89c7
MD
2172 (begin
2173 (set! registered-modules (delq! modinfo registered-modules))
2174 (let ((mod (resolve-module modname #f)))
2175 (save-module-excursion
2176 (lambda ()
2177 (set-current-module mod)
2178 (set-module-public-interface! mod mod)
2179 (dynamic-call (cadr modinfo) (caddr modinfo))
2180 ))
2181 #t))
d0cbd20c
MV
2182 #f))
2183 registered-modules))
2184
2185(define (dynamic-maybe-call name dynobj)
2186 (catch #t ; could use false-if-exception here
2187 (lambda ()
2188 (dynamic-call name dynobj))
2189 (lambda args
2190 #f)))
2191
ed218d98
MV
2192(define (dynamic-maybe-link filename)
2193 (catch #t ; could use false-if-exception here
2194 (lambda ()
2195 (dynamic-link filename))
2196 (lambda args
2197 #f)))
2198
d0cbd20c
MV
2199(define (find-and-link-dynamic-module module-name)
2200 (define (make-init-name mod-name)
2201 (string-append 'scm_init
2202 (list->string (map (lambda (c)
2203 (if (or (char-alphabetic? c)
2204 (char-numeric? c))
2205 c
2206 #\_))
2207 (string->list mod-name)))
2208 '_module))
ebd79f62
TP
2209
2210 ;; Put the subdirectory for this module in the car of SUBDIR-AND-LIBNAME,
2211 ;; and the `libname' (the name of the module prepended by `lib') in the cdr
2212 ;; field. For example, if MODULE-NAME is the list (inet tcp-ip udp), then
2213 ;; SUBDIR-AND-LIBNAME will be the pair ("inet/tcp-ip" . "libudp").
2214 (let ((subdir-and-libname
d0cbd20c
MV
2215 (let loop ((dirs "")
2216 (syms module-name))
ebd79f62
TP
2217 (if (null? (cdr syms))
2218 (cons dirs (string-append "lib" (car syms)))
2219 (loop (string-append dirs (car syms) "/") (cdr syms)))))
d0cbd20c
MV
2220 (init (make-init-name (apply string-append
2221 (map (lambda (s)
2222 (string-append "_" s))
2223 module-name)))))
ebd79f62
TP
2224 (let ((subdir (car subdir-and-libname))
2225 (libname (cdr subdir-and-libname)))
2226
2227 ;; Now look in each dir in %LOAD-PATH for `subdir/libfoo.la'. If that
2228 ;; file exists, fetch the dlname from that file and attempt to link
2229 ;; against it. If `subdir/libfoo.la' does not exist, or does not seem
2230 ;; to name any shared library, look for `subdir/libfoo.so' instead and
2231 ;; link against that.
2232 (let check-dirs ((dir-list %load-path))
2233 (if (null? dir-list)
2234 #f
2235 (let* ((dir (in-vicinity (car dir-list) subdir))
2236 (sharlib-full
2237 (or (try-using-libtool-name dir libname)
2238 (try-using-sharlib-name dir libname))))
2239 (if (and sharlib-full (file-exists? sharlib-full))
2240 (link-dynamic-module sharlib-full init)
2241 (check-dirs (cdr dir-list)))))))))
2242
2243(define (try-using-libtool-name libdir libname)
ebd79f62
TP
2244 (let ((libtool-filename (in-vicinity libdir
2245 (string-append libname ".la"))))
2246 (and (file-exists? libtool-filename)
5ef4ef4e
MD
2247 (with-input-from-file libtool-filename
2248 (lambda ()
2249 (let loop ((ln (read-line)))
2250 (cond ((eof-object? ln) #f)
49e5d550 2251 ((and (> (string-length ln) 9)
5ef4ef4e
MD
2252 (string=? "dlname='" (substring ln 0 8))
2253 (string-index ln #\' 8))
2254 =>
2255 (lambda (end)
2256 (in-vicinity libdir (substring ln 8 end))))
2257 (else (loop (read-line))))))))))
ebd79f62
TP
2258
2259(define (try-using-sharlib-name libdir libname)
2260 (in-vicinity libdir (string-append libname ".so")))
d0cbd20c
MV
2261
2262(define (link-dynamic-module filename initname)
3e3cec45
MD
2263 ;; Register any linked modules which has been registered on the C level
2264 (register-modules #f)
6b856182
MV
2265 (let ((dynobj (dynamic-link filename)))
2266 (dynamic-call initname dynobj)
3e3cec45 2267 (register-modules dynobj)))
a4f9b1f6
MD
2268
2269(define (try-module-linked module-name)
2270 (init-dynamic-module module-name))
2271
d0cbd20c 2272(define (try-module-dynamic-link module-name)
a4f9b1f6
MD
2273 (and (find-and-link-dynamic-module module-name)
2274 (init-dynamic-module module-name)))
d0cbd20c 2275
ed218d98
MV
2276
2277
0f2d19dd
JB
2278(define autoloads-done '((guile . guile)))
2279
2280(define (autoload-done-or-in-progress? p m)
2281 (let ((n (cons p m)))
2282 (->bool (or (member n autoloads-done)
2283 (member n autoloads-in-progress)))))
2284
2285(define (autoload-done! p m)
2286 (let ((n (cons p m)))
2287 (set! autoloads-in-progress
2288 (delete! n autoloads-in-progress))
2289 (or (member n autoloads-done)
2290 (set! autoloads-done (cons n autoloads-done)))))
2291
2292(define (autoload-in-progress! p m)
2293 (let ((n (cons p m)))
2294 (set! autoloads-done
2295 (delete! n autoloads-done))
2296 (set! autoloads-in-progress (cons n autoloads-in-progress))))
2297
2298(define (set-autoloaded! p m done?)
2299 (if done?
2300 (autoload-done! p m)
2301 (let ((n (cons p m)))
2302 (set! autoloads-done (delete! n autoloads-done))
2303 (set! autoloads-in-progress (delete! n autoloads-in-progress)))))
2304
2305
2306
2307
2308\f
2309;;; {Macros}
2310;;;
2311
7a0ff2f8
MD
2312(define (primitive-macro? m)
2313 (and (macro? m)
2314 (not (macro-transformer m))))
2315
2316;;; {Defmacros}
2317;;;
9591db87
MD
2318(define macro-table (make-weak-key-hash-table 523))
2319(define xformer-table (make-weak-key-hash-table 523))
0f2d19dd
JB
2320
2321(define (defmacro? m) (hashq-ref macro-table m))
2322(define (assert-defmacro?! m) (hashq-set! macro-table m #t))
2323(define (defmacro-transformer m) (hashq-ref xformer-table m))
2324(define (set-defmacro-transformer! m t) (hashq-set! xformer-table m t))
2325
2326(define defmacro:transformer
2327 (lambda (f)
2328 (let* ((xform (lambda (exp env)
2329 (copy-tree (apply f (cdr exp)))))
2330 (a (procedure->memoizing-macro xform)))
2331 (assert-defmacro?! a)
2332 (set-defmacro-transformer! a f)
2333 a)))
2334
2335
2336(define defmacro
2337 (let ((defmacro-transformer
2338 (lambda (name parms . body)
2339 (let ((transformer `(lambda ,parms ,@body)))
2340 `(define ,name
2341 (,(lambda (transformer)
2342 (defmacro:transformer transformer))
2343 ,transformer))))))
2344 (defmacro:transformer defmacro-transformer)))
2345
2346(define defmacro:syntax-transformer
2347 (lambda (f)
2348 (procedure->syntax
2349 (lambda (exp env)
2350 (copy-tree (apply f (cdr exp)))))))
2351
ed218d98
MV
2352
2353;; XXX - should the definition of the car really be looked up in the
2354;; current module?
2355
0f2d19dd
JB
2356(define (macroexpand-1 e)
2357 (cond
2358 ((pair? e) (let* ((a (car e))
ed218d98 2359 (val (and (symbol? a) (local-ref (list a)))))
0f2d19dd
JB
2360 (if (defmacro? val)
2361 (apply (defmacro-transformer val) (cdr e))
2362 e)))
2363 (#t e)))
2364
2365(define (macroexpand e)
2366 (cond
2367 ((pair? e) (let* ((a (car e))
ed218d98 2368 (val (and (symbol? a) (local-ref (list a)))))
0f2d19dd
JB
2369 (if (defmacro? val)
2370 (macroexpand (apply (defmacro-transformer val) (cdr e)))
2371 e)))
2372 (#t e)))
2373
e672f1b5
MD
2374(define (gentemp)
2375 (gensym "scm:G"))
0f2d19dd 2376
534a0099 2377(provide 'defmacro)
0f2d19dd
JB
2378
2379\f
2380
83b38198
MD
2381;;; {Run-time options}
2382
16b8ebbe
MD
2383((let* ((names '((eval-options-interface
2384 (eval-options eval-enable eval-disable)
2385 (eval-set!))
2386
2387 (debug-options-interface
83b38198
MD
2388 (debug-options debug-enable debug-disable)
2389 (debug-set!))
2390
2391 (evaluator-traps-interface
2392 (traps trap-enable trap-disable)
2393 (trap-set!))
2394
2395 (read-options-interface
2396 (read-options read-enable read-disable)
2397 (read-set!))
2398
2399 (print-options-interface
2400 (print-options print-enable print-disable)
2401 (print-set!))
e586be78
MD
2402
2403 (readline-options-interface
2404 (readline-options readline-enable readline-disable)
2405 (readline-set!))
83b38198
MD
2406 ))
2407 (option-name car)
2408 (option-value cadr)
2409 (option-documentation caddr)
2410
2411 (print-option (lambda (option)
2412 (display (option-name option))
2413 (if (< (string-length
2414 (symbol->string (option-name option)))
2415 8)
2416 (display #\tab))
2417 (display #\tab)
2418 (display (option-value option))
2419 (display #\tab)
2420 (display (option-documentation option))
2421 (newline)))
2422
2423 ;; Below follows the macros defining the run-time option interfaces.
2424
2425 (make-options (lambda (interface)
2426 `(lambda args
2427 (cond ((null? args) (,interface))
45456413 2428 ((list? (car args))
83b38198 2429 (,interface (car args)) (,interface))
2f110c3c 2430 (else (for-each ,print-option
83b38198
MD
2431 (,interface #t)))))))
2432
2433 (make-enable (lambda (interface)
2434 `(lambda flags
2435 (,interface (append flags (,interface)))
2436 (,interface))))
2437
2438 (make-disable (lambda (interface)
2439 `(lambda flags
2440 (let ((options (,interface)))
2441 (for-each (lambda (flag)
2442 (set! options (delq! flag options)))
2443 flags)
2444 (,interface options)
2445 (,interface)))))
2446
2447 (make-set! (lambda (interface)
2448 `((name exp)
2449 (,'quasiquote
2450 (begin (,interface (append (,interface)
2451 (list '(,'unquote name)
2452 (,'unquote exp))))
2453 (,interface))))))
2454 )
2455 (procedure->macro
2456 (lambda (exp env)
2457 (cons 'begin
2458 (apply append
2459 (map (lambda (group)
2460 (let ((interface (car group)))
2461 (append (map (lambda (name constructor)
2462 `(define ,name
2463 ,(constructor interface)))
2464 (cadr group)
2465 (list make-options
2466 make-enable
2467 make-disable))
2468 (map (lambda (name constructor)
2469 `(defmacro ,name
2470 ,@(constructor interface)))
2471 (caddr group)
2472 (list make-set!)))))
2473 names)))))))
2474
2475\f
2476
0f2d19dd
JB
2477;;; {Running Repls}
2478;;;
2479
2480(define (repl read evaler print)
75a97b92 2481 (let loop ((source (read (current-input-port))))
0f2d19dd 2482 (print (evaler source))
75a97b92 2483 (loop (read (current-input-port)))))
0f2d19dd
JB
2484
2485;; A provisional repl that acts like the SCM repl:
2486;;
2487(define scm-repl-silent #f)
2488(define (assert-repl-silence v) (set! scm-repl-silent v))
2489
21ed9efe
MD
2490(define *unspecified* (if #f #f))
2491(define (unspecified? v) (eq? v *unspecified*))
2492
2493(define scm-repl-print-unspecified #f)
2494(define (assert-repl-print-unspecified v) (set! scm-repl-print-unspecified v))
2495
79451588 2496(define scm-repl-verbose #f)
0f2d19dd
JB
2497(define (assert-repl-verbosity v) (set! scm-repl-verbose v))
2498
e6875011 2499(define scm-repl-prompt "guile> ")
0f2d19dd 2500
e6875011
MD
2501(define (set-repl-prompt! v) (set! scm-repl-prompt v))
2502
d5d34fa1
MD
2503(define (default-lazy-handler key . args)
2504 (save-stack lazy-handler-dispatch)
2505 (apply throw key args))
2506
45456413 2507(define enter-frame-handler default-lazy-handler)
d5d34fa1
MD
2508(define apply-frame-handler default-lazy-handler)
2509(define exit-frame-handler default-lazy-handler)
2510
2511(define (lazy-handler-dispatch key . args)
2512 (case key
2513 ((apply-frame)
2514 (apply apply-frame-handler key args))
2515 ((exit-frame)
2516 (apply exit-frame-handler key args))
45456413
MD
2517 ((enter-frame)
2518 (apply enter-frame-handler key args))
d5d34fa1
MD
2519 (else
2520 (apply default-lazy-handler key args))))
0f2d19dd 2521
3e3cec45 2522(define abort-hook (make-hook))
59e1116d 2523
28d8ab3c
GH
2524;; these definitions are used if running a script.
2525;; otherwise redefined in error-catching-loop.
2526(define (set-batch-mode?! arg) #t)
2527(define (batch-mode?) #t)
4bbbcd5c 2528
0f2d19dd 2529(define (error-catching-loop thunk)
4bbbcd5c
GH
2530 (let ((status #f)
2531 (interactive #t))
2532 (set! set-batch-mode?! (lambda (arg)
2533 (cond (arg
2534 (set! interactive #f)
2535 (restore-signals))
2536 (#t
2537 (error "sorry, not implemented")))))
2538 (set! batch-mode? (lambda () (not interactive)))
8e44e7a0
GH
2539 (define (loop first)
2540 (let ((next
2541 (catch #t
9a0d70e2 2542
8e44e7a0
GH
2543 (lambda ()
2544 (lazy-catch #t
2545 (lambda ()
2546 (dynamic-wind
2547 (lambda () (unmask-signals))
2548 (lambda ()
45456413
MD
2549 (with-traps
2550 (lambda ()
2551 (first)
8e44e7a0 2552
45456413
MD
2553 ;; This line is needed because mark
2554 ;; doesn't do closures quite right.
2555 ;; Unreferenced locals should be
2556 ;; collected.
2557 ;;
2558 (set! first #f)
2559 (let loop ((v (thunk)))
2560 (loop (thunk)))
2561 #f)))
8e44e7a0
GH
2562 (lambda () (mask-signals))))
2563
2564 lazy-handler-dispatch))
2565
2566 (lambda (key . args)
2567 (case key
2568 ((quit)
8e44e7a0
GH
2569 (force-output)
2570 (set! status args)
2571 #f)
2572
2573 ((switch-repl)
2574 (apply throw 'switch-repl args))
2575
2576 ((abort)
2577 ;; This is one of the closures that require
2578 ;; (set! first #f) above
2579 ;;
2580 (lambda ()
04efd24d 2581 (run-hook abort-hook)
8e44e7a0
GH
2582 (force-output)
2583 (display "ABORT: " (current-error-port))
2584 (write args (current-error-port))
2585 (newline (current-error-port))
4bbbcd5c
GH
2586 (if interactive
2587 (if (and (not has-shown-debugger-hint?)
2588 (not (memq 'backtrace
2589 (debug-options-interface)))
8bb7f646 2590 (stack? (fluid-ref the-last-stack)))
4bbbcd5c
GH
2591 (begin
2592 (newline (current-error-port))
2593 (display
2594 "Type \"(backtrace)\" to get more information.\n"
2595 (current-error-port))
2596 (set! has-shown-debugger-hint? #t)))
2597 (primitive-exit 1))
8e44e7a0
GH
2598 (set! stack-saved? #f)))
2599
2600 (else
2601 ;; This is the other cons-leak closure...
2602 (lambda ()
2603 (cond ((= (length args) 4)
2604 (apply handle-system-error key args))
2605 (else
2606 (apply bad-throw key args))))))))))
2607 (if next (loop next) status)))
2608 (loop (lambda () #t))))
0f2d19dd 2609
8bb7f646 2610;;(define the-last-stack (make-fluid)) Defined by scm_init_backtrace ()
21ed9efe
MD
2611(define stack-saved? #f)
2612
2613(define (save-stack . narrowing)
edc185c7
MD
2614 (or stack-saved?
2615 (cond ((not (memq 'debug (debug-options-interface)))
2616 (fluid-set! the-last-stack #f)
2617 (set! stack-saved? #t))
2618 (else
2619 (fluid-set!
2620 the-last-stack
2621 (case (stack-id #t)
2622 ((repl-stack)
2623 (apply make-stack #t save-stack eval #t 0 narrowing))
2624 ((load-stack)
2625 (apply make-stack #t save-stack 0 #t 0 narrowing))
2626 ((tk-stack)
2627 (apply make-stack #t save-stack tk-stack-mark #t 0 narrowing))
2628 ((#t)
2629 (apply make-stack #t save-stack 0 1 narrowing))
2630 (else
2631 (let ((id (stack-id #t)))
2632 (and (procedure? id)
2633 (apply make-stack #t save-stack id #t 0 narrowing))))))
2634 (set! stack-saved? #t)))))
1c6cd8e8 2635
3e3cec45
MD
2636(define before-error-hook (make-hook))
2637(define after-error-hook (make-hook))
2638(define before-backtrace-hook (make-hook))
2639(define after-backtrace-hook (make-hook))
1c6cd8e8 2640
21ed9efe
MD
2641(define has-shown-debugger-hint? #f)
2642
35c5db87
GH
2643(define (handle-system-error key . args)
2644 (let ((cep (current-error-port)))
8bb7f646 2645 (cond ((not (stack? (fluid-ref the-last-stack))))
21ed9efe 2646 ((memq 'backtrace (debug-options-interface))
04efd24d 2647 (run-hook before-backtrace-hook)
21ed9efe 2648 (newline cep)
8bb7f646 2649 (display-backtrace (fluid-ref the-last-stack) cep)
21ed9efe 2650 (newline cep)
04efd24d
MD
2651 (run-hook after-backtrace-hook)))
2652 (run-hook before-error-hook)
8bb7f646 2653 (apply display-error (fluid-ref the-last-stack) cep args)
04efd24d 2654 (run-hook after-error-hook)
35c5db87
GH
2655 (force-output cep)
2656 (throw 'abort key)))
21ed9efe 2657
0f2d19dd
JB
2658(define (quit . args)
2659 (apply throw 'quit args))
2660
7950df7c
GH
2661(define exit quit)
2662
d590bbf6
MD
2663;;(define has-shown-backtrace-hint? #f) Defined by scm_init_backtrace ()
2664
2665;; Replaced by C code:
2666;;(define (backtrace)
8bb7f646 2667;; (if (fluid-ref the-last-stack)
d590bbf6
MD
2668;; (begin
2669;; (newline)
8bb7f646 2670;; (display-backtrace (fluid-ref the-last-stack) (current-output-port))
d590bbf6
MD
2671;; (newline)
2672;; (if (and (not has-shown-backtrace-hint?)
2673;; (not (memq 'backtrace (debug-options-interface))))
2674;; (begin
2675;; (display
2676;;"Type \"(debug-enable 'backtrace)\" if you would like a backtrace
2677;;automatically if an error occurs in the future.\n")
2678;; (set! has-shown-backtrace-hint? #t))))
2679;; (display "No backtrace available.\n")))
21ed9efe 2680
0f2d19dd
JB
2681(define (error-catching-repl r e p)
2682 (error-catching-loop (lambda () (p (e (r))))))
2683
2684(define (gc-run-time)
2685 (cdr (assq 'gc-time-taken (gc-stats))))
2686
3e3cec45
MD
2687(define before-read-hook (make-hook))
2688(define after-read-hook (make-hook))
1c6cd8e8 2689
dc5c2038
MD
2690;;; The default repl-reader function. We may override this if we've
2691;;; the readline library.
2692(define repl-reader
2693 (lambda (prompt)
2694 (display prompt)
2695 (force-output)
04efd24d 2696 (run-hook before-read-hook)
dc5c2038
MD
2697 (read (current-input-port))))
2698
0f2d19dd
JB
2699(define (scm-style-repl)
2700 (letrec (
2701 (start-gc-rt #f)
2702 (start-rt #f)
0f2d19dd
JB
2703 (repl-report-start-timing (lambda ()
2704 (set! start-gc-rt (gc-run-time))
2705 (set! start-rt (get-internal-run-time))))
2706 (repl-report (lambda ()
2707 (display ";;; ")
2708 (display (inexact->exact
2709 (* 1000 (/ (- (get-internal-run-time) start-rt)
2710 internal-time-units-per-second))))
2711 (display " msec (")
2712 (display (inexact->exact
2713 (* 1000 (/ (- (gc-run-time) start-gc-rt)
2714 internal-time-units-per-second))))
2715 (display " msec in gc)\n")))
480977d0
JB
2716
2717 (consume-trailing-whitespace
2718 (lambda ()
2719 (let ((ch (peek-char)))
2720 (cond
2721 ((eof-object? ch))
2722 ((or (char=? ch #\space) (char=? ch #\tab))
2723 (read-char)
2724 (consume-trailing-whitespace))
2725 ((char=? ch #\newline)
2726 (read-char))))))
0f2d19dd 2727 (-read (lambda ()
dc5c2038
MD
2728 (let ((val
2729 (let ((prompt (cond ((string? scm-repl-prompt)
2730 scm-repl-prompt)
2731 ((thunk? scm-repl-prompt)
2732 (scm-repl-prompt))
2733 (scm-repl-prompt "> ")
2734 (else ""))))
2735 (repl-reader prompt))))
2736
480977d0
JB
2737 ;; As described in R4RS, the READ procedure updates the
2738 ;; port to point to the first characetr past the end of
2739 ;; the external representation of the object. This
2740 ;; means that it doesn't consume the newline typically
2741 ;; found after an expression. This means that, when
2742 ;; debugging Guile with GDB, GDB gets the newline, which
2743 ;; it often interprets as a "continue" command, making
2744 ;; breakpoints kind of useless. So, consume any
2745 ;; trailing newline here, as well as any whitespace
2746 ;; before it.
2747 (consume-trailing-whitespace)
04efd24d 2748 (run-hook after-read-hook)
0f2d19dd
JB
2749 (if (eof-object? val)
2750 (begin
7950df7c 2751 (repl-report-start-timing)
0f2d19dd
JB
2752 (if scm-repl-verbose
2753 (begin
2754 (newline)
2755 (display ";;; EOF -- quitting")
2756 (newline)))
2757 (quit 0)))
2758 val)))
2759
2760 (-eval (lambda (sourc)
2761 (repl-report-start-timing)
4cdee789 2762 (start-stack 'repl-stack (eval sourc))))
0f2d19dd
JB
2763
2764 (-print (lambda (result)
2765 (if (not scm-repl-silent)
2766 (begin
21ed9efe
MD
2767 (if (or scm-repl-print-unspecified
2768 (not (unspecified? result)))
2769 (begin
2770 (write result)
2771 (newline)))
0f2d19dd
JB
2772 (if scm-repl-verbose
2773 (repl-report))
2774 (force-output)))))
2775
8e44e7a0 2776 (-quit (lambda (args)
0f2d19dd
JB
2777 (if scm-repl-verbose
2778 (begin
2779 (display ";;; QUIT executed, repl exitting")
2780 (newline)
2781 (repl-report)))
8e44e7a0 2782 args))
0f2d19dd
JB
2783
2784 (-abort (lambda ()
2785 (if scm-repl-verbose
2786 (begin
2787 (display ";;; ABORT executed.")
2788 (newline)
2789 (repl-report)))
2790 (repl -read -eval -print))))
2791
8e44e7a0
GH
2792 (let ((status (error-catching-repl -read
2793 -eval
2794 -print)))
2795 (-quit status))))
2796
0f2d19dd 2797
0f2d19dd 2798\f
44cf1f0f 2799;;; {IOTA functions: generating lists of numbers}
0f2d19dd
JB
2800
2801(define (reverse-iota n) (if (> n 0) (cons (1- n) (reverse-iota (1- n))) '()))
24b2aac7 2802(define (iota n) (reverse! (reverse-iota n)))
0f2d19dd
JB
2803
2804\f
2805;;; {While}
2806;;;
2807;;; with `continue' and `break'.
2808;;;
2809
2810(defmacro while (cond . body)
2811 `(letrec ((continue (lambda () (or (not ,cond) (begin (begin ,@ body) (continue)))))
2812 (break (lambda val (apply throw 'break val))))
2813 (catch 'break
2814 (lambda () (continue))
2815 (lambda v (cadr v)))))
2816
7398c2c2
MD
2817;;; {collect}
2818;;;
2819;;; Similar to `begin' but returns a list of the results of all constituent
2820;;; forms instead of the result of the last form.
2821;;; (The definition relies on the current left-to-right
2822;;; order of evaluation of operands in applications.)
2823
2824(defmacro collect forms
2825 (cons 'list forms))
0f2d19dd 2826
8a6a8671
MV
2827;;; {with-fluids}
2828
2829;; with-fluids is a convenience wrapper for the builtin procedure
2830;; `with-fluids*'. The syntax is just like `let':
2831;;
2832;; (with-fluids ((fluid val)
2833;; ...)
2834;; body)
2835
2836(defmacro with-fluids (bindings . body)
2837 `(with-fluids* (list ,@(map car bindings)) (list ,@(map cadr bindings))
2838 (lambda () ,@body)))
2839
dc61592f
MD
2840;;; Environments
2841
2842(define the-environment
2843 (procedure->syntax
2844 (lambda (x e)
2845 e)))
2846
9705d5c2 2847(define (environment-module env)
baa47a94 2848 (let ((closure (and (pair? env) (car (last-pair env)))))
edc185c7 2849 (and closure (procedure-property closure 'module))))
bf3c93d1 2850
0f2d19dd
JB
2851\f
2852
2853;;; {Macros}
2854;;;
2855
2856;; actually....hobbit might be able to hack these with a little
2857;; coaxing
2858;;
2859
2860(defmacro define-macro (first . rest)
2861 (let ((name (if (symbol? first) first (car first)))
2862 (transformer
2863 (if (symbol? first)
2864 (car rest)
2865 `(lambda ,(cdr first) ,@rest))))
2866 `(define ,name (defmacro:transformer ,transformer))))
2867
2868
2869(defmacro define-syntax-macro (first . rest)
2870 (let ((name (if (symbol? first) first (car first)))
2871 (transformer
2872 (if (symbol? first)
2873 (car rest)
2874 `(lambda ,(cdr first) ,@rest))))
2875 `(define ,name (defmacro:syntax-transformer ,transformer))))
2876\f
2877;;; {Module System Macros}
2878;;;
2879
2880(defmacro define-module args
2881 `(let* ((process-define-module process-define-module)
2882 (set-current-module set-current-module)
2883 (module (process-define-module ',args)))
2884 (set-current-module module)
2885 module))
2886
89da9036
MV
2887;; the guts of the use-modules macro. add the interfaces of the named
2888;; modules to the use-list of the current module, in order
2889(define (process-use-modules module-names)
2890 (for-each (lambda (module-name)
2891 (let ((mod-iface (resolve-interface module-name)))
2892 (or mod-iface
2893 (error "no such module" module-name))
2894 (module-use! (current-module) mod-iface)))
2895 (reverse module-names)))
2896
33cf699f 2897(defmacro use-modules modules
89da9036 2898 `(process-use-modules ',modules))
33cf699f 2899
cf266109
MD
2900(defmacro use-syntax (spec)
2901 (if (pair? spec)
2902 `(begin
2903 (process-use-modules ',(list spec))
2904 (internal-use-syntax ,(car (last-pair spec))))
2905 `(internal-use-syntax ,spec)))
7a0ff2f8 2906
0f2d19dd
JB
2907(define define-private define)
2908
2909(defmacro define-public args
2910 (define (syntax)
2911 (error "bad syntax" (list 'define-public args)))
2912 (define (defined-name n)
2913 (cond
3c5af9ef
JB
2914 ((symbol? n) n)
2915 ((pair? n) (defined-name (car n)))
2916 (else (syntax))))
0f2d19dd 2917 (cond
3c5af9ef
JB
2918 ((null? args) (syntax))
2919
2920 (#t (let ((name (defined-name (car args))))
2921 `(begin
2922 (let ((public-i (module-public-interface (current-module))))
2923 ;; Make sure there is a local variable:
2924 ;;
2925 (module-define! (current-module)
2926 ',name
2927 (module-ref (current-module) ',name #f))
0f2d19dd 2928
3c5af9ef
JB
2929 ;; Make sure that local is exported:
2930 ;;
2931 (module-add! public-i ',name
2932 (module-variable (current-module) ',name)))
0f2d19dd 2933
3c5af9ef
JB
2934 ;; Now (re)define the var normally. Bernard URBAN
2935 ;; suggests we use eval here to accomodate Hobbit; it lets
2936 ;; the interpreter handle the define-private form, which
2937 ;; Hobbit can't digest.
2938 (eval '(define-private ,@ args)))))))
0f2d19dd
JB
2939
2940
2941
2942(defmacro defmacro-public args
2943 (define (syntax)
2944 (error "bad syntax" (list 'defmacro-public args)))
2945 (define (defined-name n)
2946 (cond
2947 ((symbol? n) n)
2948 (else (syntax))))
2949 (cond
2950 ((null? args) (syntax))
2951
2952 (#t (let ((name (defined-name (car args))))
2953 `(begin
2954 (let ((public-i (module-public-interface (current-module))))
2955 ;; Make sure there is a local variable:
2956 ;;
2957 (module-define! (current-module)
2958 ',name
2959 (module-ref (current-module) ',name #f))
2960
2961 ;; Make sure that local is exported:
2962 ;;
2963 (module-add! public-i ',name (module-variable (current-module) ',name)))
2964
2965 ;; Now (re)define the var normally.
2966 ;;
2967 (defmacro ,@ args))))))
2968
2969
a0cc0a01
MD
2970(defmacro export names
2971 `(let* ((m (current-module))
2972 (public-i (module-public-interface m)))
2973 (for-each (lambda (name)
2974 ;; Make sure there is a local variable:
2975 (module-define! m name (module-ref m name #f))
2976 ;; Make sure that local is exported:
2977 (module-add! public-i name (module-variable m name)))
2978 ',names)))
2979
2980(define export-syntax export)
2981
2982
0f2d19dd
JB
2983
2984
0f2d19dd
JB
2985(define load load-module)
2986
2987
2988\f
9aca88c3
JB
2989;;; {Load emacs interface support if emacs option is given.}
2990
2991(define (load-emacs-interface)
2992 (if (memq 'debug-extensions *features*)
2993 (debug-enable 'backtrace))
2994 (define-module (guile-user) :use-module (ice-9 emacs)))
2995
2996\f
44cf1f0f 2997;;; {I/O functions for Tcl channels (disabled)}
0f2d19dd
JB
2998
2999;; (define in-ch (get-standard-channel TCL_STDIN))
3000;; (define out-ch (get-standard-channel TCL_STDOUT))
3001;; (define err-ch (get-standard-channel TCL_STDERR))
3002;;
3003;; (define inp (%make-channel-port in-ch "r"))
3004;; (define outp (%make-channel-port out-ch "w"))
3005;; (define errp (%make-channel-port err-ch "w"))
3006;;
3007;; (define %system-char-ready? char-ready?)
3008;;
3009;; (define (char-ready? p)
3010;; (if (not (channel-port? p))
3011;; (%system-char-ready? p)
3012;; (let* ((channel (%channel-port-channel p))
3013;; (old-blocking (channel-option-ref channel :blocking)))
3014;; (dynamic-wind
3015;; (lambda () (set-channel-option the-root-tcl-interpreter channel :blocking "0"))
3016;; (lambda () (not (eof-object? (peek-char p))))
3017;; (lambda () (set-channel-option the-root-tcl-interpreter channel :blocking old-blocking))))))
3018;;
3019;; (define (top-repl)
3020;; (with-input-from-port inp
3021;; (lambda ()
3022;; (with-output-to-port outp
3023;; (lambda ()
3024;; (with-error-to-port errp
3025;; (lambda ()
3026;; (scm-style-repl))))))))
3027;;
3028;; (set-current-input-port inp)
3029;; (set-current-output-port outp)
3030;; (set-current-error-port errp)
3031
e1a191a8
GH
3032;; this is just (scm-style-repl) with a wrapper to install and remove
3033;; signal handlers.
8e44e7a0 3034(define (top-repl)
9aca88c3
JB
3035
3036 ;; Load emacs interface support if emacs option is given.
3037 (if (and (module-defined? the-root-module 'use-emacs-interface)
3038 use-emacs-interface)
3039 (load-emacs-interface))
3040
4fdf8b2c
MD
3041 ;; Place the user in the guile-user module.
3042 (define-module (guile-user))
3043
e1a191a8
GH
3044 (let ((old-handlers #f)
3045 (signals `((,SIGINT . "User interrupt")
3046 (,SIGFPE . "Arithmetic error")
3047 (,SIGBUS . "Bad memory access (bus error)")
3048 (,SIGSEGV . "Bad memory access (Segmentation violation)"))))
3049
3050 (dynamic-wind
3051
3052 ;; call at entry
3053 (lambda ()
3054 (let ((make-handler (lambda (msg)
3055 (lambda (sig)
096d5f90 3056 (save-stack %deliver-signals)
e1a191a8
GH
3057 (scm-error 'signal
3058 #f
3059 msg
3060 #f
3061 (list sig))))))
3062 (set! old-handlers
3063 (map (lambda (sig-msg)
3064 (sigaction (car sig-msg)
3065 (make-handler (cdr sig-msg))))
3066 signals))))
3067
3068 ;; the protected thunk.
3069 (lambda ()
dc5c2038
MD
3070
3071 ;; If we've got readline, use it to prompt the user. This is a
3072 ;; kludge, but we'll fix it soon. At least we only get
3073 ;; readline involved when we're actually running the repl.
3074 (if (and (memq 'readline *features*)
279ba8c0 3075 (isatty? (current-input-port))
dc5c2038
MD
3076 (not (and (module-defined? the-root-module
3077 'use-emacs-interface)
3078 use-emacs-interface)))
04efd24d 3079 (let ((read-hook (lambda () (run-hook before-read-hook))))
dc5c2038
MD
3080 (set-current-input-port (readline-port))
3081 (set! repl-reader
3082 (lambda (prompt)
3083 (dynamic-wind
3084 (lambda ()
3085 (set-readline-prompt! prompt)
3086 (set-readline-read-hook! read-hook))
3087 (lambda () (read))
3088 (lambda ()
3089 (set-readline-prompt! "")
3090 (set-readline-read-hook! #f)))))))
2055a1bc 3091 (let ((status (scm-style-repl)))
04efd24d 3092 (run-hook exit-hook)
2055a1bc 3093 status))
e1a191a8
GH
3094
3095 ;; call at exit.
3096 (lambda ()
3097 (map (lambda (sig-msg old-handler)
3098 (if (not (car old-handler))
3099 ;; restore original C handler.
3100 (sigaction (car sig-msg) #f)
3101 ;; restore Scheme handler, SIG_IGN or SIG_DFL.
3102 (sigaction (car sig-msg)
3103 (car old-handler)
3104 (cdr old-handler))))
3105 signals old-handlers)))))
0f2d19dd 3106
02b754d3
GH
3107(defmacro false-if-exception (expr)
3108 `(catch #t (lambda () ,expr)
3109 (lambda args #f)))
3110
2055a1bc
MD
3111;;; This hook is run at the very end of an interactive session.
3112;;;
3e3cec45 3113(define exit-hook (make-hook))
2055a1bc 3114
13e341bb
MD
3115;;; Load readline code into root module if readline primitives are available.
3116;;;
3117;;; Ideally, we wouldn't do this until we were sure we were actually
3118;;; going to enter the repl, but autoloading individual functions is
3119;;; clumsy at the moment.
3120(if (and (memq 'readline *features*)
3121 (isatty? (current-input-port)))
3122 (begin
3123 (define-module (guile) :use-module (ice-9 readline))
39bc9948 3124 (define-module (guile-user) :use-module (ice-9 readline))))
13e341bb
MD
3125
3126\f
3127;;; {Load debug extension code into user module if debug extensions present.}
c56634ba
MD
3128;;;
3129;;; *fixme* This is a temporary solution.
3130;;;
0f2d19dd 3131
c56634ba 3132(if (memq 'debug-extensions *features*)
39bc9948 3133 (define-module (guile-user) :use-module (ice-9 debug)))
90895e5c
MD
3134
3135\f
13e341bb 3136;;; {Load session support into user module if present.}
90d5e280
MD
3137;;;
3138;;; *fixme* This is a temporary solution.
3139;;;
3140
3141(if (%search-load-path "ice-9/session.scm")
39bc9948 3142 (define-module (guile-user) :use-module (ice-9 session)))
f246e585 3143
13e341bb 3144;;; {Load thread code into user module if threads are present.}
90895e5c
MD
3145;;;
3146;;; *fixme* This is a temporary solution.
3147;;;
3148
3149(if (memq 'threads *features*)
39bc9948 3150 (define-module (guile-user) :use-module (ice-9 threads)))
90895e5c 3151
21ed9efe 3152\f
05817d9e
JB
3153;;; {Load regexp code if regexp primitives are available.}
3154
3155(if (memq 'regex *features*)
5ef4ef4e 3156 (define-module (guile-user) :use-module (ice-9 regex)))
05817d9e
JB
3157
3158\f
13e341bb
MD
3159(define-module (guile))
3160
9946dd45
JB
3161;;; {Check that the interpreter and scheme code match up.}
3162
3163(let ((show-line
3164 (lambda args
3165 (with-output-to-port (current-error-port)
3166 (lambda ()
3167 (display (car (command-line)))
3168 (display ": ")
3169 (for-each (lambda (string) (display string))
3170 args)
3171 (newline))))))
3172
3173 (load-from-path "ice-9/version.scm")
3174
3175 (if (not (string=?
3176 (libguile-config-stamp) ; from the interprpreter
3177 (ice-9-config-stamp))) ; from the Scheme code
3178 (begin
3179 (show-line "warning: different versions of libguile and ice-9:")
3180 (show-line "libguile: configured on " (libguile-config-stamp))
3181 (show-line "ice-9: configured on " (ice-9-config-stamp)))))
3182
13e341bb 3183(append! %load-path (cons "." ()))
21ed9efe 3184