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