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