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