* guile-config.in: Add copyright notice.
[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
c6775c40
MD
1667(define (load-module filename)
1668 (save-module-excursion
1669 (lambda ()
1670 (let ((oldname (and (current-load-port)
1671 (port-filename (current-load-port)))))
1672 (basic-load (if (and oldname
1673 (> (string-length filename) 0)
1674 (not (char=? (string-ref filename 0) #\/))
1675 (not (string=? (dirname oldname) ".")))
1676 (string-append (dirname oldname) "/" filename)
1677 filename))))))
0f2d19dd
JB
1678
1679
1680\f
44cf1f0f 1681;;; {MODULE-REF -- exported}
0f2d19dd
JB
1682;;
1683;; Returns the value of a variable called NAME in MODULE or any of its
1684;; used modules. If there is no such variable, then if the optional third
1685;; argument DEFAULT is present, it is returned; otherwise an error is signaled.
1686;;
1687(define (module-ref module name . rest)
1688 (let ((variable (module-variable module name)))
1689 (if (and variable (variable-bound? variable))
1690 (variable-ref variable)
1691 (if (null? rest)
1692 (error "No variable named" name 'in module)
1693 (car rest) ; default value
1694 ))))
1695
1696;; MODULE-SET! -- exported
1697;;
1698;; Sets the variable called NAME in MODULE (or in a module that MODULE uses)
1699;; to VALUE; if there is no such variable, an error is signaled.
1700;;
1701(define (module-set! module name value)
1702 (let ((variable (module-variable module name)))
1703 (if variable
1704 (variable-set! variable value)
1705 (error "No variable named" name 'in module))))
1706
1707;; MODULE-DEFINE! -- exported
1708;;
1709;; Sets the variable called NAME in MODULE to VALUE; if there is no such
1710;; variable, it is added first.
1711;;
1712(define (module-define! module name value)
1713 (let ((variable (module-local-variable module name)))
1714 (if variable
1715 (variable-set! variable value)
1716 (module-add! module name (make-variable value name)))))
1717
ed218d98
MV
1718;; MODULE-DEFINED? -- exported
1719;;
1720;; Return #t iff NAME is defined in MODULE (or in a module that MODULE
1721;; uses)
1722;;
1723(define (module-defined? module name)
1724 (let ((variable (module-variable module name)))
1725 (and variable (variable-bound? variable))))
1726
0f2d19dd
JB
1727;; MODULE-USE! module interface
1728;;
1729;; Add INTERFACE to the list of interfaces used by MODULE.
1730;;
1731(define (module-use! module interface)
1732 (set-module-uses! module
7a0ff2f8 1733 (cons interface (delq! interface (module-uses module)))))
0f2d19dd
JB
1734
1735\f
0f2d19dd
JB
1736;;; {Recursive Namespaces}
1737;;;
1738;;;
1739;;; A hierarchical namespace emerges if we consider some module to be
1740;;; root, and variables bound to modules as nested namespaces.
1741;;;
1742;;; The routines in this file manage variable names in hierarchical namespace.
1743;;; Each variable name is a list of elements, looked up in successively nested
1744;;; modules.
1745;;;
0dd5491c 1746;;; (nested-ref some-root-module '(foo bar baz))
0f2d19dd
JB
1747;;; => <value of a variable named baz in the module bound to bar in
1748;;; the module bound to foo in some-root-module>
1749;;;
1750;;;
1751;;; There are:
1752;;;
1753;;; ;; a-root is a module
1754;;; ;; name is a list of symbols
1755;;;
0dd5491c
MD
1756;;; nested-ref a-root name
1757;;; nested-set! a-root name val
1758;;; nested-define! a-root name val
1759;;; nested-remove! a-root name
0f2d19dd
JB
1760;;;
1761;;;
1762;;; (current-module) is a natural choice for a-root so for convenience there are
1763;;; also:
1764;;;
0dd5491c
MD
1765;;; local-ref name == nested-ref (current-module) name
1766;;; local-set! name val == nested-set! (current-module) name val
1767;;; local-define! name val == nested-define! (current-module) name val
1768;;; local-remove! name == nested-remove! (current-module) name
0f2d19dd
JB
1769;;;
1770
1771
0dd5491c 1772(define (nested-ref root names)
0f2d19dd
JB
1773 (let loop ((cur root)
1774 (elts names))
1775 (cond
1776 ((null? elts) cur)
1777 ((not (module? cur)) #f)
1778 (else (loop (module-ref cur (car elts) #f) (cdr elts))))))
1779
0dd5491c 1780(define (nested-set! root names val)
0f2d19dd
JB
1781 (let loop ((cur root)
1782 (elts names))
1783 (if (null? (cdr elts))
1784 (module-set! cur (car elts) val)
1785 (loop (module-ref cur (car elts)) (cdr elts)))))
1786
0dd5491c 1787(define (nested-define! root names val)
0f2d19dd
JB
1788 (let loop ((cur root)
1789 (elts names))
1790 (if (null? (cdr elts))
1791 (module-define! cur (car elts) val)
1792 (loop (module-ref cur (car elts)) (cdr elts)))))
1793
0dd5491c 1794(define (nested-remove! root names)
0f2d19dd
JB
1795 (let loop ((cur root)
1796 (elts names))
1797 (if (null? (cdr elts))
1798 (module-remove! cur (car elts))
1799 (loop (module-ref cur (car elts)) (cdr elts)))))
1800
0dd5491c
MD
1801(define (local-ref names) (nested-ref (current-module) names))
1802(define (local-set! names val) (nested-set! (current-module) names val))
1803(define (local-define names val) (nested-define! (current-module) names val))
1804(define (local-remove names) (nested-remove! (current-module) names))
0f2d19dd
JB
1805
1806
1807\f
8bb7330c 1808;;; {The (app) module}
0f2d19dd
JB
1809;;;
1810;;; The root of conventionally named objects not directly in the top level.
1811;;;
8bb7330c
JB
1812;;; (app modules)
1813;;; (app modules guile)
0f2d19dd
JB
1814;;;
1815;;; The directory of all modules and the standard root module.
1816;;;
1817
1818(define (module-public-interface m) (module-ref m '%module-public-interface #f))
1819(define (set-module-public-interface! m i) (module-define! m '%module-public-interface i))
1820(define the-root-module (make-root-module))
1821(define the-scm-module (make-scm-module))
1822(set-module-public-interface! the-root-module the-scm-module)
1823(set-module-name! the-root-module 'the-root-module)
1824(set-module-name! the-scm-module 'the-scm-module)
1825
1826(set-current-module the-root-module)
1827
1828(define app (make-module 31))
0dd5491c
MD
1829(local-define '(app modules) (make-module 31))
1830(local-define '(app modules guile) the-root-module)
0f2d19dd
JB
1831
1832;; (define-special-value '(app modules new-ws) (lambda () (make-scm-module)))
1833
0209ca9a 1834(define (resolve-module name . maybe-autoload)
0f2d19dd 1835 (let ((full-name (append '(app modules) name)))
0dd5491c 1836 (let ((already (local-ref full-name)))
0f2d19dd
JB
1837 (or already
1838 (begin
0209ca9a 1839 (if (or (null? maybe-autoload) (car maybe-autoload))
a4f9b1f6
MD
1840 (or (try-module-linked name)
1841 (try-module-autoload name)
d0cbd20c 1842 (try-module-dynamic-link name)))
0f2d19dd
JB
1843 (make-modules-in (current-module) full-name))))))
1844
1845(define (beautify-user-module! module)
1846 (if (not (module-public-interface module))
1847 (let ((interface (make-module 31)))
1848 (set-module-name! interface (module-name module))
1849 (set-module-kind! interface 'interface)
1850 (set-module-public-interface! module interface)))
cc7f066c
MD
1851 (if (and (not (memq the-scm-module (module-uses module)))
1852 (not (eq? module the-root-module)))
0f2d19dd
JB
1853 (set-module-uses! module (append (module-uses module) (list the-scm-module)))))
1854
1855(define (make-modules-in module name)
1856 (if (null? name)
1857 module
1858 (cond
1859 ((module-ref module (car name) #f) => (lambda (m) (make-modules-in m (cdr name))))
1860 (else (let ((m (make-module 31)))
1861 (set-module-kind! m 'directory)
1862 (set-module-name! m (car name))
1863 (module-define! module (car name) m)
1864 (make-modules-in m (cdr name)))))))
1865
1866(define (resolve-interface name)
1867 (let ((module (resolve-module name)))
1868 (and module (module-public-interface module))))
1869
1870
1871(define %autoloader-developer-mode #t)
1872
cf266109
MD
1873(define (internal-use-syntax transformer)
1874 (set-module-transformer! (current-module) transformer)
1875 (set! scm:eval-transformer transformer))
1876
0f2d19dd
JB
1877(define (process-define-module args)
1878 (let* ((module-id (car args))
0209ca9a 1879 (module (resolve-module module-id #f))
0f2d19dd
JB
1880 (kws (cdr args)))
1881 (beautify-user-module! module)
0209ca9a
MV
1882 (let loop ((kws kws)
1883 (reversed-interfaces '()))
1884 (if (null? kws)
1885 (for-each (lambda (interface)
1886 (module-use! module interface))
1887 reversed-interfaces)
f714ca8e
MD
1888 (let ((keyword (cond ((keyword? (car kws))
1889 (keyword->symbol (car kws)))
1890 ((and (symbol? (car kws))
1891 (eq? (string-ref (car kws) 0) #\:))
1892 (string->symbol (substring (car kws) 1)))
1893 (else #f))))
1894 (case keyword
1895 ((use-module use-syntax)
1896 (if (not (pair? (cdr kws)))
1897 (error "unrecognized defmodule argument" kws))
1898 (let* ((used-name (cadr kws))
1899 (used-module (resolve-module used-name)))
1900 (if (not (module-ref used-module '%module-public-interface #f))
1901 (begin
1902 ((if %autoloader-developer-mode warn error)
1903 "no code for module" (module-name used-module))
1904 (beautify-user-module! used-module)))
1905 (let ((interface (module-public-interface used-module)))
1906 (if (not interface)
1907 (error "missing interface for use-module" used-module))
1908 (if (eq? keyword 'use-syntax)
cf266109
MD
1909 (internal-use-syntax
1910 (module-ref interface (car (last-pair used-name))
1911 #f)))
f714ca8e
MD
1912 (loop (cddr kws) (cons interface reversed-interfaces)))))
1913 (else
1914 (error "unrecognized defmodule argument" kws))))))
0f2d19dd
JB
1915 module))
1916\f
44cf1f0f 1917;;; {Autoloading modules}
0f2d19dd
JB
1918
1919(define autoloads-in-progress '())
1920
1921(define (try-module-autoload module-name)
6fa8995c 1922
0f2d19dd
JB
1923 (define (sfx name) (string-append name (scheme-file-suffix)))
1924 (let* ((reverse-name (reverse module-name))
1925 (name (car reverse-name))
1926 (dir-hint-module-name (reverse (cdr reverse-name)))
1927 (dir-hint (apply symbol-append (map (lambda (elt) (symbol-append elt "/")) dir-hint-module-name))))
0209ca9a 1928 (resolve-module dir-hint-module-name #f)
0f2d19dd
JB
1929 (and (not (autoload-done-or-in-progress? dir-hint name))
1930 (let ((didit #f))
1931 (dynamic-wind
1932 (lambda () (autoload-in-progress! dir-hint name))
1933 (lambda ()
1934 (let loop ((dirs %load-path))
1935 (and (not (null? dirs))
1936 (or
1937 (let ((d (car dirs))
1938 (trys (list
1939 dir-hint
1940 (sfx dir-hint)
1941 (in-vicinity dir-hint name)
1942 (in-vicinity dir-hint (sfx name)))))
1943 (and (or-map (lambda (f)
1944 (let ((full (in-vicinity d f)))
1945 full
6fa8995c
GH
1946 (and (file-exists? full)
1947 (not (file-is-directory? full))
0f2d19dd
JB
1948 (begin
1949 (save-module-excursion
1950 (lambda ()
5552355a
GH
1951 (load (string-append
1952 d "/" f))))
0f2d19dd
JB
1953 #t))))
1954 trys)
1955 (begin
1956 (set! didit #t)
1957 #t)))
1958 (loop (cdr dirs))))))
1959 (lambda () (set-autoloaded! dir-hint name didit)))
1960 didit))))
1961
d0cbd20c
MV
1962;;; Dynamic linking of modules
1963
1964;; Initializing a module that is written in C is a two step process.
1965;; First the module's `module init' function is called. This function
1966;; is expected to call `scm_register_module_xxx' to register the `real
1967;; init' function. Later, when the module is referenced for the first
1968;; time, this real init function is called in the right context. See
1969;; gtcltk-lib/gtcltk-module.c for an example.
1970;;
1971;; The code for the module can be in a regular shared library (so that
1972;; the `module init' function will be called when libguile is
1973;; initialized). Or it can be dynamically linked.
1974;;
1975;; You can safely call `scm_register_module_xxx' before libguile
1976;; itself is initialized. You could call it from an C++ constructor
1977;; of a static object, for example.
1978;;
1979;; To make your Guile extension into a dynamic linkable module, follow
1980;; these easy steps:
1981;;
8bb7330c 1982;; - Find a name for your module, like (ice-9 gtcltk)
d0cbd20c
MV
1983;; - Write a function with a name like
1984;;
1985;; scm_init_ice_9_gtcltk_module
1986;;
1987;; This is your `module init' function. It should call
1988;;
1989;; scm_register_module_xxx ("ice-9 gtcltk", scm_init_gtcltk);
1990;;
1991;; "ice-9 gtcltk" is the C version of the module name. Slashes are
1992;; replaced by spaces, the rest is untouched. `scm_init_gtcltk' is
ed218d98 1993;; the real init function that executes the usual initializations
d0cbd20c
MV
1994;; like making new smobs, etc.
1995;;
1996;; - Make a shared library with your code and a name like
1997;;
1998;; ice-9/libgtcltk.so
1999;;
2000;; and put it somewhere in %load-path.
2001;;
8bb7330c 2002;; - Then you can simply write `:use-module (ice-9 gtcltk)' and it
d0cbd20c
MV
2003;; will be linked automatically.
2004;;
2005;; This is all very experimental.
2006
2007(define (split-c-module-name str)
2008 (let loop ((rev '())
2009 (start 0)
2010 (pos 0)
2011 (end (string-length str)))
2012 (cond
2013 ((= pos end)
2014 (reverse (cons (string->symbol (substring str start pos)) rev)))
2015 ((eq? (string-ref str pos) #\space)
2016 (loop (cons (string->symbol (substring str start pos)) rev)
2017 (+ pos 1)
2018 (+ pos 1)
2019 end))
2020 (else
2021 (loop rev start (+ pos 1) end)))))
2022
2023(define (convert-c-registered-modules dynobj)
2024 (let ((res (map (lambda (c)
2025 (list (split-c-module-name (car c)) (cdr c) dynobj))
2026 (c-registered-modules))))
2027 (c-clear-registered-modules)
2028 res))
2029
2030(define registered-modules (convert-c-registered-modules #f))
2031
2032(define (init-dynamic-module modname)
2033 (or-map (lambda (modinfo)
2034 (if (equal? (car modinfo) modname)
2035 (let ((mod (resolve-module modname #f)))
2036 (save-module-excursion
2037 (lambda ()
2038 (set-current-module mod)
2039 (dynamic-call (cadr modinfo) (caddr modinfo))
2040 (set-module-public-interface! mod mod)))
2041 (set! registered-modules (delq! modinfo registered-modules))
2042 #t)
2043 #f))
2044 registered-modules))
2045
2046(define (dynamic-maybe-call name dynobj)
2047 (catch #t ; could use false-if-exception here
2048 (lambda ()
2049 (dynamic-call name dynobj))
2050 (lambda args
2051 #f)))
2052
ed218d98
MV
2053(define (dynamic-maybe-link filename)
2054 (catch #t ; could use false-if-exception here
2055 (lambda ()
2056 (dynamic-link filename))
2057 (lambda args
2058 #f)))
2059
d0cbd20c
MV
2060(define (find-and-link-dynamic-module module-name)
2061 (define (make-init-name mod-name)
2062 (string-append 'scm_init
2063 (list->string (map (lambda (c)
2064 (if (or (char-alphabetic? c)
2065 (char-numeric? c))
2066 c
2067 #\_))
2068 (string->list mod-name)))
2069 '_module))
ebd79f62
TP
2070
2071 ;; Put the subdirectory for this module in the car of SUBDIR-AND-LIBNAME,
2072 ;; and the `libname' (the name of the module prepended by `lib') in the cdr
2073 ;; field. For example, if MODULE-NAME is the list (inet tcp-ip udp), then
2074 ;; SUBDIR-AND-LIBNAME will be the pair ("inet/tcp-ip" . "libudp").
2075 (let ((subdir-and-libname
d0cbd20c
MV
2076 (let loop ((dirs "")
2077 (syms module-name))
ebd79f62
TP
2078 (if (null? (cdr syms))
2079 (cons dirs (string-append "lib" (car syms)))
2080 (loop (string-append dirs (car syms) "/") (cdr syms)))))
d0cbd20c
MV
2081 (init (make-init-name (apply string-append
2082 (map (lambda (s)
2083 (string-append "_" s))
2084 module-name)))))
ebd79f62
TP
2085 (let ((subdir (car subdir-and-libname))
2086 (libname (cdr subdir-and-libname)))
2087
2088 ;; Now look in each dir in %LOAD-PATH for `subdir/libfoo.la'. If that
2089 ;; file exists, fetch the dlname from that file and attempt to link
2090 ;; against it. If `subdir/libfoo.la' does not exist, or does not seem
2091 ;; to name any shared library, look for `subdir/libfoo.so' instead and
2092 ;; link against that.
2093 (let check-dirs ((dir-list %load-path))
2094 (if (null? dir-list)
2095 #f
2096 (let* ((dir (in-vicinity (car dir-list) subdir))
2097 (sharlib-full
2098 (or (try-using-libtool-name dir libname)
2099 (try-using-sharlib-name dir libname))))
2100 (if (and sharlib-full (file-exists? sharlib-full))
2101 (link-dynamic-module sharlib-full init)
2102 (check-dirs (cdr dir-list)))))))))
2103
2104(define (try-using-libtool-name libdir libname)
ebd79f62
TP
2105 (let ((libtool-filename (in-vicinity libdir
2106 (string-append libname ".la"))))
2107 (and (file-exists? libtool-filename)
5ef4ef4e
MD
2108 (with-input-from-file libtool-filename
2109 (lambda ()
2110 (let loop ((ln (read-line)))
2111 (cond ((eof-object? ln) #f)
2112 ((and (>= (string-length ln) 8)
2113 (string=? "dlname='" (substring ln 0 8))
2114 (string-index ln #\' 8))
2115 =>
2116 (lambda (end)
2117 (in-vicinity libdir (substring ln 8 end))))
2118 (else (loop (read-line))))))))))
ebd79f62
TP
2119
2120(define (try-using-sharlib-name libdir libname)
2121 (in-vicinity libdir (string-append libname ".so")))
d0cbd20c
MV
2122
2123(define (link-dynamic-module filename initname)
6b856182
MV
2124 (let ((dynobj (dynamic-link filename)))
2125 (dynamic-call initname dynobj)
2126 (set! registered-modules
2127 (append! (convert-c-registered-modules dynobj)
2128 registered-modules))))
a4f9b1f6
MD
2129
2130(define (try-module-linked module-name)
2131 (init-dynamic-module module-name))
2132
d0cbd20c 2133(define (try-module-dynamic-link module-name)
a4f9b1f6
MD
2134 (and (find-and-link-dynamic-module module-name)
2135 (init-dynamic-module module-name)))
d0cbd20c 2136
ed218d98
MV
2137
2138
0f2d19dd
JB
2139(define autoloads-done '((guile . guile)))
2140
2141(define (autoload-done-or-in-progress? p m)
2142 (let ((n (cons p m)))
2143 (->bool (or (member n autoloads-done)
2144 (member n autoloads-in-progress)))))
2145
2146(define (autoload-done! p m)
2147 (let ((n (cons p m)))
2148 (set! autoloads-in-progress
2149 (delete! n autoloads-in-progress))
2150 (or (member n autoloads-done)
2151 (set! autoloads-done (cons n autoloads-done)))))
2152
2153(define (autoload-in-progress! p m)
2154 (let ((n (cons p m)))
2155 (set! autoloads-done
2156 (delete! n autoloads-done))
2157 (set! autoloads-in-progress (cons n autoloads-in-progress))))
2158
2159(define (set-autoloaded! p m done?)
2160 (if done?
2161 (autoload-done! p m)
2162 (let ((n (cons p m)))
2163 (set! autoloads-done (delete! n autoloads-done))
2164 (set! autoloads-in-progress (delete! n autoloads-in-progress)))))
2165
2166
2167
2168
2169\f
2170;;; {Macros}
2171;;;
2172
7a0ff2f8
MD
2173(define (primitive-macro? m)
2174 (and (macro? m)
2175 (not (macro-transformer m))))
2176
2177;;; {Defmacros}
2178;;;
9591db87
MD
2179(define macro-table (make-weak-key-hash-table 523))
2180(define xformer-table (make-weak-key-hash-table 523))
0f2d19dd
JB
2181
2182(define (defmacro? m) (hashq-ref macro-table m))
2183(define (assert-defmacro?! m) (hashq-set! macro-table m #t))
2184(define (defmacro-transformer m) (hashq-ref xformer-table m))
2185(define (set-defmacro-transformer! m t) (hashq-set! xformer-table m t))
2186
2187(define defmacro:transformer
2188 (lambda (f)
2189 (let* ((xform (lambda (exp env)
2190 (copy-tree (apply f (cdr exp)))))
2191 (a (procedure->memoizing-macro xform)))
2192 (assert-defmacro?! a)
2193 (set-defmacro-transformer! a f)
2194 a)))
2195
2196
2197(define defmacro
2198 (let ((defmacro-transformer
2199 (lambda (name parms . body)
2200 (let ((transformer `(lambda ,parms ,@body)))
2201 `(define ,name
2202 (,(lambda (transformer)
2203 (defmacro:transformer transformer))
2204 ,transformer))))))
2205 (defmacro:transformer defmacro-transformer)))
2206
2207(define defmacro:syntax-transformer
2208 (lambda (f)
2209 (procedure->syntax
2210 (lambda (exp env)
2211 (copy-tree (apply f (cdr exp)))))))
2212
ed218d98
MV
2213
2214;; XXX - should the definition of the car really be looked up in the
2215;; current module?
2216
0f2d19dd
JB
2217(define (macroexpand-1 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 (apply (defmacro-transformer val) (cdr e))
2223 e)))
2224 (#t e)))
2225
2226(define (macroexpand e)
2227 (cond
2228 ((pair? e) (let* ((a (car e))
ed218d98 2229 (val (and (symbol? a) (local-ref (list a)))))
0f2d19dd
JB
2230 (if (defmacro? val)
2231 (macroexpand (apply (defmacro-transformer val) (cdr e)))
2232 e)))
2233 (#t e)))
2234
e672f1b5
MD
2235(define (gentemp)
2236 (gensym "scm:G"))
0f2d19dd 2237
534a0099 2238(provide 'defmacro)
0f2d19dd
JB
2239
2240\f
2241
83b38198
MD
2242;;; {Run-time options}
2243
16b8ebbe
MD
2244((let* ((names '((eval-options-interface
2245 (eval-options eval-enable eval-disable)
2246 (eval-set!))
2247
2248 (debug-options-interface
83b38198
MD
2249 (debug-options debug-enable debug-disable)
2250 (debug-set!))
2251
2252 (evaluator-traps-interface
2253 (traps trap-enable trap-disable)
2254 (trap-set!))
2255
2256 (read-options-interface
2257 (read-options read-enable read-disable)
2258 (read-set!))
2259
2260 (print-options-interface
2261 (print-options print-enable print-disable)
2262 (print-set!))
2263 ))
2264 (option-name car)
2265 (option-value cadr)
2266 (option-documentation caddr)
2267
2268 (print-option (lambda (option)
2269 (display (option-name option))
2270 (if (< (string-length
2271 (symbol->string (option-name option)))
2272 8)
2273 (display #\tab))
2274 (display #\tab)
2275 (display (option-value option))
2276 (display #\tab)
2277 (display (option-documentation option))
2278 (newline)))
2279
2280 ;; Below follows the macros defining the run-time option interfaces.
2281
2282 (make-options (lambda (interface)
2283 `(lambda args
2284 (cond ((null? args) (,interface))
45456413 2285 ((list? (car args))
83b38198 2286 (,interface (car args)) (,interface))
2f110c3c 2287 (else (for-each ,print-option
83b38198
MD
2288 (,interface #t)))))))
2289
2290 (make-enable (lambda (interface)
2291 `(lambda flags
2292 (,interface (append flags (,interface)))
2293 (,interface))))
2294
2295 (make-disable (lambda (interface)
2296 `(lambda flags
2297 (let ((options (,interface)))
2298 (for-each (lambda (flag)
2299 (set! options (delq! flag options)))
2300 flags)
2301 (,interface options)
2302 (,interface)))))
2303
2304 (make-set! (lambda (interface)
2305 `((name exp)
2306 (,'quasiquote
2307 (begin (,interface (append (,interface)
2308 (list '(,'unquote name)
2309 (,'unquote exp))))
2310 (,interface))))))
2311 )
2312 (procedure->macro
2313 (lambda (exp env)
2314 (cons 'begin
2315 (apply append
2316 (map (lambda (group)
2317 (let ((interface (car group)))
2318 (append (map (lambda (name constructor)
2319 `(define ,name
2320 ,(constructor interface)))
2321 (cadr group)
2322 (list make-options
2323 make-enable
2324 make-disable))
2325 (map (lambda (name constructor)
2326 `(defmacro ,name
2327 ,@(constructor interface)))
2328 (caddr group)
2329 (list make-set!)))))
2330 names)))))))
2331
2332\f
2333
0f2d19dd
JB
2334;;; {Running Repls}
2335;;;
2336
2337(define (repl read evaler print)
75a97b92 2338 (let loop ((source (read (current-input-port))))
0f2d19dd 2339 (print (evaler source))
75a97b92 2340 (loop (read (current-input-port)))))
0f2d19dd
JB
2341
2342;; A provisional repl that acts like the SCM repl:
2343;;
2344(define scm-repl-silent #f)
2345(define (assert-repl-silence v) (set! scm-repl-silent v))
2346
21ed9efe
MD
2347(define *unspecified* (if #f #f))
2348(define (unspecified? v) (eq? v *unspecified*))
2349
2350(define scm-repl-print-unspecified #f)
2351(define (assert-repl-print-unspecified v) (set! scm-repl-print-unspecified v))
2352
79451588 2353(define scm-repl-verbose #f)
0f2d19dd
JB
2354(define (assert-repl-verbosity v) (set! scm-repl-verbose v))
2355
e6875011 2356(define scm-repl-prompt "guile> ")
0f2d19dd 2357
e6875011
MD
2358(define (set-repl-prompt! v) (set! scm-repl-prompt v))
2359
d5d34fa1
MD
2360(define (default-lazy-handler key . args)
2361 (save-stack lazy-handler-dispatch)
2362 (apply throw key args))
2363
45456413 2364(define enter-frame-handler default-lazy-handler)
d5d34fa1
MD
2365(define apply-frame-handler default-lazy-handler)
2366(define exit-frame-handler default-lazy-handler)
2367
2368(define (lazy-handler-dispatch key . args)
2369 (case key
2370 ((apply-frame)
2371 (apply apply-frame-handler key args))
2372 ((exit-frame)
2373 (apply exit-frame-handler key args))
45456413
MD
2374 ((enter-frame)
2375 (apply enter-frame-handler key args))
d5d34fa1
MD
2376 (else
2377 (apply default-lazy-handler key args))))
0f2d19dd 2378
59e1116d
MD
2379(define abort-hook '())
2380
28d8ab3c
GH
2381;; these definitions are used if running a script.
2382;; otherwise redefined in error-catching-loop.
2383(define (set-batch-mode?! arg) #t)
2384(define (batch-mode?) #t)
4bbbcd5c 2385
0f2d19dd 2386(define (error-catching-loop thunk)
4bbbcd5c
GH
2387 (let ((status #f)
2388 (interactive #t))
2389 (set! set-batch-mode?! (lambda (arg)
2390 (cond (arg
2391 (set! interactive #f)
2392 (restore-signals))
2393 (#t
2394 (error "sorry, not implemented")))))
2395 (set! batch-mode? (lambda () (not interactive)))
8e44e7a0
GH
2396 (define (loop first)
2397 (let ((next
2398 (catch #t
9a0d70e2 2399
8e44e7a0
GH
2400 (lambda ()
2401 (lazy-catch #t
2402 (lambda ()
2403 (dynamic-wind
2404 (lambda () (unmask-signals))
2405 (lambda ()
45456413
MD
2406 (with-traps
2407 (lambda ()
2408 (first)
8e44e7a0 2409
45456413
MD
2410 ;; This line is needed because mark
2411 ;; doesn't do closures quite right.
2412 ;; Unreferenced locals should be
2413 ;; collected.
2414 ;;
2415 (set! first #f)
2416 (let loop ((v (thunk)))
2417 (loop (thunk)))
2418 #f)))
8e44e7a0
GH
2419 (lambda () (mask-signals))))
2420
2421 lazy-handler-dispatch))
2422
2423 (lambda (key . args)
2424 (case key
2425 ((quit)
8e44e7a0
GH
2426 (force-output)
2427 (set! status args)
2428 #f)
2429
2430 ((switch-repl)
2431 (apply throw 'switch-repl args))
2432
2433 ((abort)
2434 ;; This is one of the closures that require
2435 ;; (set! first #f) above
2436 ;;
2437 (lambda ()
2438 (run-hooks abort-hook)
2439 (force-output)
2440 (display "ABORT: " (current-error-port))
2441 (write args (current-error-port))
2442 (newline (current-error-port))
4bbbcd5c
GH
2443 (if interactive
2444 (if (and (not has-shown-debugger-hint?)
2445 (not (memq 'backtrace
2446 (debug-options-interface)))
8bb7f646 2447 (stack? (fluid-ref the-last-stack)))
4bbbcd5c
GH
2448 (begin
2449 (newline (current-error-port))
2450 (display
2451 "Type \"(backtrace)\" to get more information.\n"
2452 (current-error-port))
2453 (set! has-shown-debugger-hint? #t)))
2454 (primitive-exit 1))
8e44e7a0
GH
2455 (set! stack-saved? #f)))
2456
2457 (else
2458 ;; This is the other cons-leak closure...
2459 (lambda ()
2460 (cond ((= (length args) 4)
2461 (apply handle-system-error key args))
2462 (else
2463 (apply bad-throw key args))))))))))
2464 (if next (loop next) status)))
2465 (loop (lambda () #t))))
0f2d19dd 2466
8bb7f646 2467;;(define the-last-stack (make-fluid)) Defined by scm_init_backtrace ()
21ed9efe
MD
2468(define stack-saved? #f)
2469
2470(define (save-stack . narrowing)
2471 (cond (stack-saved?)
2472 ((not (memq 'debug (debug-options-interface)))
8bb7f646 2473 (fluid-set! the-last-stack #f)
21ed9efe
MD
2474 (set! stack-saved? #t))
2475 (else
8bb7f646
MD
2476 (fluid-set!
2477 the-last-stack
2478 (case (stack-id #t)
2479 ((repl-stack)
2480 (apply make-stack #t save-stack eval narrowing))
2481 ((load-stack)
2482 (apply make-stack #t save-stack 0 narrowing))
2483 ((tk-stack)
2484 (apply make-stack #t save-stack tk-stack-mark narrowing))
2485 ((#t)
2486 (apply make-stack #t save-stack 0 1 narrowing))
2487 (else (let ((id (stack-id #t)))
2488 (and (procedure? id)
2489 (apply make-stack #t save-stack id narrowing))))))
21ed9efe 2490 (set! stack-saved? #t))))
1c6cd8e8 2491
59e1116d
MD
2492(define before-error-hook '())
2493(define after-error-hook '())
2494(define before-backtrace-hook '())
2495(define after-backtrace-hook '())
1c6cd8e8 2496
21ed9efe
MD
2497(define has-shown-debugger-hint? #f)
2498
35c5db87
GH
2499(define (handle-system-error key . args)
2500 (let ((cep (current-error-port)))
8bb7f646 2501 (cond ((not (stack? (fluid-ref the-last-stack))))
21ed9efe 2502 ((memq 'backtrace (debug-options-interface))
59e1116d 2503 (run-hooks before-backtrace-hook)
21ed9efe 2504 (newline cep)
8bb7f646 2505 (display-backtrace (fluid-ref the-last-stack) cep)
21ed9efe 2506 (newline cep)
59e1116d
MD
2507 (run-hooks after-backtrace-hook)))
2508 (run-hooks before-error-hook)
8bb7f646 2509 (apply display-error (fluid-ref the-last-stack) cep args)
59e1116d 2510 (run-hooks after-error-hook)
35c5db87
GH
2511 (force-output cep)
2512 (throw 'abort key)))
21ed9efe 2513
0f2d19dd
JB
2514(define (quit . args)
2515 (apply throw 'quit args))
2516
7950df7c
GH
2517(define exit quit)
2518
d590bbf6
MD
2519;;(define has-shown-backtrace-hint? #f) Defined by scm_init_backtrace ()
2520
2521;; Replaced by C code:
2522;;(define (backtrace)
8bb7f646 2523;; (if (fluid-ref the-last-stack)
d590bbf6
MD
2524;; (begin
2525;; (newline)
8bb7f646 2526;; (display-backtrace (fluid-ref the-last-stack) (current-output-port))
d590bbf6
MD
2527;; (newline)
2528;; (if (and (not has-shown-backtrace-hint?)
2529;; (not (memq 'backtrace (debug-options-interface))))
2530;; (begin
2531;; (display
2532;;"Type \"(debug-enable 'backtrace)\" if you would like a backtrace
2533;;automatically if an error occurs in the future.\n")
2534;; (set! has-shown-backtrace-hint? #t))))
2535;; (display "No backtrace available.\n")))
21ed9efe 2536
0f2d19dd
JB
2537(define (error-catching-repl r e p)
2538 (error-catching-loop (lambda () (p (e (r))))))
2539
2540(define (gc-run-time)
2541 (cdr (assq 'gc-time-taken (gc-stats))))
2542
59e1116d
MD
2543(define before-read-hook '())
2544(define after-read-hook '())
1c6cd8e8 2545
dc5c2038
MD
2546;;; The default repl-reader function. We may override this if we've
2547;;; the readline library.
2548(define repl-reader
2549 (lambda (prompt)
2550 (display prompt)
2551 (force-output)
2552 (run-hooks before-read-hook)
2553 (read (current-input-port))))
2554
0f2d19dd
JB
2555(define (scm-style-repl)
2556 (letrec (
2557 (start-gc-rt #f)
2558 (start-rt #f)
0f2d19dd
JB
2559 (repl-report-start-timing (lambda ()
2560 (set! start-gc-rt (gc-run-time))
2561 (set! start-rt (get-internal-run-time))))
2562 (repl-report (lambda ()
2563 (display ";;; ")
2564 (display (inexact->exact
2565 (* 1000 (/ (- (get-internal-run-time) start-rt)
2566 internal-time-units-per-second))))
2567 (display " msec (")
2568 (display (inexact->exact
2569 (* 1000 (/ (- (gc-run-time) start-gc-rt)
2570 internal-time-units-per-second))))
2571 (display " msec in gc)\n")))
480977d0
JB
2572
2573 (consume-trailing-whitespace
2574 (lambda ()
2575 (let ((ch (peek-char)))
2576 (cond
2577 ((eof-object? ch))
2578 ((or (char=? ch #\space) (char=? ch #\tab))
2579 (read-char)
2580 (consume-trailing-whitespace))
2581 ((char=? ch #\newline)
2582 (read-char))))))
0f2d19dd 2583 (-read (lambda ()
dc5c2038
MD
2584 (let ((val
2585 (let ((prompt (cond ((string? scm-repl-prompt)
2586 scm-repl-prompt)
2587 ((thunk? scm-repl-prompt)
2588 (scm-repl-prompt))
2589 (scm-repl-prompt "> ")
2590 (else ""))))
2591 (repl-reader prompt))))
2592
480977d0
JB
2593 ;; As described in R4RS, the READ procedure updates the
2594 ;; port to point to the first characetr past the end of
2595 ;; the external representation of the object. This
2596 ;; means that it doesn't consume the newline typically
2597 ;; found after an expression. This means that, when
2598 ;; debugging Guile with GDB, GDB gets the newline, which
2599 ;; it often interprets as a "continue" command, making
2600 ;; breakpoints kind of useless. So, consume any
2601 ;; trailing newline here, as well as any whitespace
2602 ;; before it.
2603 (consume-trailing-whitespace)
59e1116d 2604 (run-hooks after-read-hook)
0f2d19dd
JB
2605 (if (eof-object? val)
2606 (begin
7950df7c 2607 (repl-report-start-timing)
0f2d19dd
JB
2608 (if scm-repl-verbose
2609 (begin
2610 (newline)
2611 (display ";;; EOF -- quitting")
2612 (newline)))
2613 (quit 0)))
2614 val)))
2615
2616 (-eval (lambda (sourc)
2617 (repl-report-start-timing)
4cdee789 2618 (start-stack 'repl-stack (eval sourc))))
0f2d19dd
JB
2619
2620 (-print (lambda (result)
2621 (if (not scm-repl-silent)
2622 (begin
21ed9efe
MD
2623 (if (or scm-repl-print-unspecified
2624 (not (unspecified? result)))
2625 (begin
2626 (write result)
2627 (newline)))
0f2d19dd
JB
2628 (if scm-repl-verbose
2629 (repl-report))
2630 (force-output)))))
2631
8e44e7a0 2632 (-quit (lambda (args)
0f2d19dd
JB
2633 (if scm-repl-verbose
2634 (begin
2635 (display ";;; QUIT executed, repl exitting")
2636 (newline)
2637 (repl-report)))
8e44e7a0 2638 args))
0f2d19dd
JB
2639
2640 (-abort (lambda ()
2641 (if scm-repl-verbose
2642 (begin
2643 (display ";;; ABORT executed.")
2644 (newline)
2645 (repl-report)))
2646 (repl -read -eval -print))))
2647
8e44e7a0
GH
2648 (let ((status (error-catching-repl -read
2649 -eval
2650 -print)))
2651 (-quit status))))
2652
0f2d19dd 2653
0f2d19dd 2654\f
44cf1f0f 2655;;; {IOTA functions: generating lists of numbers}
0f2d19dd
JB
2656
2657(define (reverse-iota n) (if (> n 0) (cons (1- n) (reverse-iota (1- n))) '()))
24b2aac7 2658(define (iota n) (reverse! (reverse-iota n)))
0f2d19dd
JB
2659
2660\f
2661;;; {While}
2662;;;
2663;;; with `continue' and `break'.
2664;;;
2665
2666(defmacro while (cond . body)
2667 `(letrec ((continue (lambda () (or (not ,cond) (begin (begin ,@ body) (continue)))))
2668 (break (lambda val (apply throw 'break val))))
2669 (catch 'break
2670 (lambda () (continue))
2671 (lambda v (cadr v)))))
2672
2673
8a6a8671
MV
2674;;; {with-fluids}
2675
2676;; with-fluids is a convenience wrapper for the builtin procedure
2677;; `with-fluids*'. The syntax is just like `let':
2678;;
2679;; (with-fluids ((fluid val)
2680;; ...)
2681;; body)
2682
2683(defmacro with-fluids (bindings . body)
2684 `(with-fluids* (list ,@(map car bindings)) (list ,@(map cadr bindings))
2685 (lambda () ,@body)))
2686
0f2d19dd
JB
2687\f
2688
2689;;; {Macros}
2690;;;
2691
2692;; actually....hobbit might be able to hack these with a little
2693;; coaxing
2694;;
2695
2696(defmacro define-macro (first . rest)
2697 (let ((name (if (symbol? first) first (car first)))
2698 (transformer
2699 (if (symbol? first)
2700 (car rest)
2701 `(lambda ,(cdr first) ,@rest))))
2702 `(define ,name (defmacro:transformer ,transformer))))
2703
2704
2705(defmacro define-syntax-macro (first . rest)
2706 (let ((name (if (symbol? first) first (car first)))
2707 (transformer
2708 (if (symbol? first)
2709 (car rest)
2710 `(lambda ,(cdr first) ,@rest))))
2711 `(define ,name (defmacro:syntax-transformer ,transformer))))
2712\f
2713;;; {Module System Macros}
2714;;;
2715
2716(defmacro define-module args
2717 `(let* ((process-define-module process-define-module)
2718 (set-current-module set-current-module)
2719 (module (process-define-module ',args)))
2720 (set-current-module module)
2721 module))
2722
89da9036
MV
2723;; the guts of the use-modules macro. add the interfaces of the named
2724;; modules to the use-list of the current module, in order
2725(define (process-use-modules module-names)
2726 (for-each (lambda (module-name)
2727 (let ((mod-iface (resolve-interface module-name)))
2728 (or mod-iface
2729 (error "no such module" module-name))
2730 (module-use! (current-module) mod-iface)))
2731 (reverse module-names)))
2732
33cf699f 2733(defmacro use-modules modules
89da9036 2734 `(process-use-modules ',modules))
33cf699f 2735
cf266109
MD
2736(defmacro use-syntax (spec)
2737 (if (pair? spec)
2738 `(begin
2739 (process-use-modules ',(list spec))
2740 (internal-use-syntax ,(car (last-pair spec))))
2741 `(internal-use-syntax ,spec)))
7a0ff2f8 2742
0f2d19dd
JB
2743(define define-private define)
2744
2745(defmacro define-public args
2746 (define (syntax)
2747 (error "bad syntax" (list 'define-public args)))
2748 (define (defined-name n)
2749 (cond
3c5af9ef
JB
2750 ((symbol? n) n)
2751 ((pair? n) (defined-name (car n)))
2752 (else (syntax))))
0f2d19dd 2753 (cond
3c5af9ef
JB
2754 ((null? args) (syntax))
2755
2756 (#t (let ((name (defined-name (car args))))
2757 `(begin
2758 (let ((public-i (module-public-interface (current-module))))
2759 ;; Make sure there is a local variable:
2760 ;;
2761 (module-define! (current-module)
2762 ',name
2763 (module-ref (current-module) ',name #f))
0f2d19dd 2764
3c5af9ef
JB
2765 ;; Make sure that local is exported:
2766 ;;
2767 (module-add! public-i ',name
2768 (module-variable (current-module) ',name)))
0f2d19dd 2769
3c5af9ef
JB
2770 ;; Now (re)define the var normally. Bernard URBAN
2771 ;; suggests we use eval here to accomodate Hobbit; it lets
2772 ;; the interpreter handle the define-private form, which
2773 ;; Hobbit can't digest.
2774 (eval '(define-private ,@ args)))))))
0f2d19dd
JB
2775
2776
2777
2778(defmacro defmacro-public args
2779 (define (syntax)
2780 (error "bad syntax" (list 'defmacro-public args)))
2781 (define (defined-name n)
2782 (cond
2783 ((symbol? n) n)
2784 (else (syntax))))
2785 (cond
2786 ((null? args) (syntax))
2787
2788 (#t (let ((name (defined-name (car args))))
2789 `(begin
2790 (let ((public-i (module-public-interface (current-module))))
2791 ;; Make sure there is a local variable:
2792 ;;
2793 (module-define! (current-module)
2794 ',name
2795 (module-ref (current-module) ',name #f))
2796
2797 ;; Make sure that local is exported:
2798 ;;
2799 (module-add! public-i ',name (module-variable (current-module) ',name)))
2800
2801 ;; Now (re)define the var normally.
2802 ;;
2803 (defmacro ,@ args))))))
2804
2805
a0cc0a01
MD
2806(defmacro export names
2807 `(let* ((m (current-module))
2808 (public-i (module-public-interface m)))
2809 (for-each (lambda (name)
2810 ;; Make sure there is a local variable:
2811 (module-define! m name (module-ref m name #f))
2812 ;; Make sure that local is exported:
2813 (module-add! public-i name (module-variable m name)))
2814 ',names)))
2815
2816(define export-syntax export)
2817
2818
0f2d19dd
JB
2819
2820
0f2d19dd
JB
2821(define load load-module)
2822
2823
2824\f
44cf1f0f 2825;;; {I/O functions for Tcl channels (disabled)}
0f2d19dd
JB
2826
2827;; (define in-ch (get-standard-channel TCL_STDIN))
2828;; (define out-ch (get-standard-channel TCL_STDOUT))
2829;; (define err-ch (get-standard-channel TCL_STDERR))
2830;;
2831;; (define inp (%make-channel-port in-ch "r"))
2832;; (define outp (%make-channel-port out-ch "w"))
2833;; (define errp (%make-channel-port err-ch "w"))
2834;;
2835;; (define %system-char-ready? char-ready?)
2836;;
2837;; (define (char-ready? p)
2838;; (if (not (channel-port? p))
2839;; (%system-char-ready? p)
2840;; (let* ((channel (%channel-port-channel p))
2841;; (old-blocking (channel-option-ref channel :blocking)))
2842;; (dynamic-wind
2843;; (lambda () (set-channel-option the-root-tcl-interpreter channel :blocking "0"))
2844;; (lambda () (not (eof-object? (peek-char p))))
2845;; (lambda () (set-channel-option the-root-tcl-interpreter channel :blocking old-blocking))))))
2846;;
2847;; (define (top-repl)
2848;; (with-input-from-port inp
2849;; (lambda ()
2850;; (with-output-to-port outp
2851;; (lambda ()
2852;; (with-error-to-port errp
2853;; (lambda ()
2854;; (scm-style-repl))))))))
2855;;
2856;; (set-current-input-port inp)
2857;; (set-current-output-port outp)
2858;; (set-current-error-port errp)
2859
e1a191a8
GH
2860;; this is just (scm-style-repl) with a wrapper to install and remove
2861;; signal handlers.
8e44e7a0 2862(define (top-repl)
e1a191a8
GH
2863 (let ((old-handlers #f)
2864 (signals `((,SIGINT . "User interrupt")
2865 (,SIGFPE . "Arithmetic error")
2866 (,SIGBUS . "Bad memory access (bus error)")
2867 (,SIGSEGV . "Bad memory access (Segmentation violation)"))))
2868
2869 (dynamic-wind
2870
2871 ;; call at entry
2872 (lambda ()
2873 (let ((make-handler (lambda (msg)
2874 (lambda (sig)
096d5f90 2875 (save-stack %deliver-signals)
e1a191a8
GH
2876 (scm-error 'signal
2877 #f
2878 msg
2879 #f
2880 (list sig))))))
2881 (set! old-handlers
2882 (map (lambda (sig-msg)
2883 (sigaction (car sig-msg)
2884 (make-handler (cdr sig-msg))))
2885 signals))))
2886
2887 ;; the protected thunk.
2888 (lambda ()
dc5c2038
MD
2889
2890 ;; If we've got readline, use it to prompt the user. This is a
2891 ;; kludge, but we'll fix it soon. At least we only get
2892 ;; readline involved when we're actually running the repl.
2893 (if (and (memq 'readline *features*)
279ba8c0 2894 (isatty? (current-input-port))
dc5c2038
MD
2895 (not (and (module-defined? the-root-module
2896 'use-emacs-interface)
2897 use-emacs-interface)))
2898 (let ((read-hook (lambda () (run-hooks before-read-hook))))
2899 (set-current-input-port (readline-port))
2900 (set! repl-reader
2901 (lambda (prompt)
2902 (dynamic-wind
2903 (lambda ()
2904 (set-readline-prompt! prompt)
2905 (set-readline-read-hook! read-hook))
2906 (lambda () (read))
2907 (lambda ()
2908 (set-readline-prompt! "")
2909 (set-readline-read-hook! #f)))))))
e1a191a8
GH
2910 (scm-style-repl))
2911
2912 ;; call at exit.
2913 (lambda ()
2914 (map (lambda (sig-msg old-handler)
2915 (if (not (car old-handler))
2916 ;; restore original C handler.
2917 (sigaction (car sig-msg) #f)
2918 ;; restore Scheme handler, SIG_IGN or SIG_DFL.
2919 (sigaction (car sig-msg)
2920 (car old-handler)
2921 (cdr old-handler))))
2922 signals old-handlers)))))
0f2d19dd 2923
02b754d3
GH
2924(defmacro false-if-exception (expr)
2925 `(catch #t (lambda () ,expr)
2926 (lambda args #f)))
2927
13e341bb
MD
2928;;; Load readline code into root module if readline primitives are available.
2929;;;
2930;;; Ideally, we wouldn't do this until we were sure we were actually
2931;;; going to enter the repl, but autoloading individual functions is
2932;;; clumsy at the moment.
2933(if (and (memq 'readline *features*)
2934 (isatty? (current-input-port)))
2935 (begin
2936 (define-module (guile) :use-module (ice-9 readline))
39bc9948 2937 (define-module (guile-user) :use-module (ice-9 readline))))
13e341bb
MD
2938
2939\f
2940;;; {Load debug extension code into user module if debug extensions present.}
c56634ba
MD
2941;;;
2942;;; *fixme* This is a temporary solution.
2943;;;
0f2d19dd 2944
c56634ba 2945(if (memq 'debug-extensions *features*)
39bc9948 2946 (define-module (guile-user) :use-module (ice-9 debug)))
90895e5c
MD
2947
2948\f
13e341bb 2949;;; {Load session support into user module if present.}
90d5e280
MD
2950;;;
2951;;; *fixme* This is a temporary solution.
2952;;;
2953
2954(if (%search-load-path "ice-9/session.scm")
39bc9948 2955 (define-module (guile-user) :use-module (ice-9 session)))
f246e585 2956
13e341bb 2957;;; {Load thread code into user module if threads are present.}
90895e5c
MD
2958;;;
2959;;; *fixme* This is a temporary solution.
2960;;;
2961
2962(if (memq 'threads *features*)
39bc9948 2963 (define-module (guile-user) :use-module (ice-9 threads)))
90895e5c 2964
21ed9efe
MD
2965\f
2966;;; {Load emacs interface support if emacs option is given.}
2967;;;
2968;;; *fixme* This is a temporary solution.
2969;;;
2970
2e3fbd8d
MD
2971(if (and (module-defined? the-root-module 'use-emacs-interface)
2972 use-emacs-interface)
8309a10d
MD
2973 (begin
2974 (if (memq 'debug-extensions *features*)
2975 (debug-enable 'backtrace))
39bc9948 2976 (define-module (guile-user) :use-module (ice-9 emacs))))
21ed9efe
MD
2977
2978\f
05817d9e
JB
2979;;; {Load regexp code if regexp primitives are available.}
2980
2981(if (memq 'regex *features*)
5ef4ef4e 2982 (define-module (guile-user) :use-module (ice-9 regex)))
05817d9e
JB
2983
2984\f
13e341bb
MD
2985(define-module (guile))
2986
9946dd45
JB
2987;;; {Check that the interpreter and scheme code match up.}
2988
2989(let ((show-line
2990 (lambda args
2991 (with-output-to-port (current-error-port)
2992 (lambda ()
2993 (display (car (command-line)))
2994 (display ": ")
2995 (for-each (lambda (string) (display string))
2996 args)
2997 (newline))))))
2998
2999 (load-from-path "ice-9/version.scm")
3000
3001 (if (not (string=?
3002 (libguile-config-stamp) ; from the interprpreter
3003 (ice-9-config-stamp))) ; from the Scheme code
3004 (begin
3005 (show-line "warning: different versions of libguile and ice-9:")
3006 (show-line "libguile: configured on " (libguile-config-stamp))
3007 (show-line "ice-9: configured on " (ice-9-config-stamp)))))
3008
13e341bb 3009(append! %load-path (cons "." ()))
21ed9efe 3010
13e341bb 3011\f
6fa8995c 3012
39bc9948 3013(define-module (guile-user))