* coop.c (coop_condition_variable_wait): Removed
[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
0f2d19dd
JB
522;;; {and-map, or-map, and map-in-order}
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
555;; map-in-order
556;;
557;; Like map, but guaranteed to process the list in order.
558;;
559(define (map-in-order fn l)
560 (if (null? l)
561 '()
562 (cons (fn (car l))
563 (map-in-order fn (cdr l)))))
564
565\f
59e1116d
MD
566;;; {Hooks}
567(define (run-hooks hook)
568 (for-each (lambda (thunk) (thunk)) hook))
569
570(define add-hook!
571 (procedure->macro
572 (lambda (exp env)
573 `(let ((thunk ,(caddr exp)))
574 (if (not (memq thunk ,(cadr exp)))
575 (set! ,(cadr exp)
576 (cons thunk ,(cadr exp))))))))
577
abf06c12
MD
578(define remove-hook!
579 (procedure->macro
580 (lambda (exp env)
581 `(let ((thunk ,(caddr exp)))
dc5c2038
MD
582 (if (memq thunk ,(cadr exp))
583 (set! ,(cadr exp)
584 (delq! thunk ,(cadr exp))))))))
abf06c12 585
59e1116d 586\f
0f2d19dd 587;;; {Files}
0f2d19dd 588;;;
249cdba6
TP
589;;; If no one can explain this comment to me by 31 Jan 1998, I will
590;;; assume it is meaningless and remove it. -twp
591;;; !!!! these should be implemented using Tcl commands, not fports.
0f2d19dd 592
6fa8995c
GH
593(define (feature? feature)
594 (and (memq feature *features*) #t))
595
3afb28ce
GH
596;; Using the vector returned by stat directly is probably not a good
597;; idea (it could just as well be a record). Hence some accessors.
598(define (stat:dev f) (vector-ref f 0))
599(define (stat:ino f) (vector-ref f 1))
600(define (stat:mode f) (vector-ref f 2))
601(define (stat:nlink f) (vector-ref f 3))
602(define (stat:uid f) (vector-ref f 4))
603(define (stat:gid f) (vector-ref f 5))
604(define (stat:rdev f) (vector-ref f 6))
605(define (stat:size f) (vector-ref f 7))
606(define (stat:atime f) (vector-ref f 8))
607(define (stat:mtime f) (vector-ref f 9))
608(define (stat:ctime f) (vector-ref f 10))
609(define (stat:blksize f) (vector-ref f 11))
610(define (stat:blocks f) (vector-ref f 12))
611
612;; derived from stat mode.
613(define (stat:type f) (vector-ref f 13))
614(define (stat:perms f) (vector-ref f 14))
615
6fa8995c
GH
616(define file-exists?
617 (if (feature? 'posix)
618 (lambda (str)
619 (access? str F_OK))
620 (lambda (str)
621 (let ((port (catch 'system-error (lambda () (open-file str OPEN_READ))
622 (lambda args #f))))
623 (if port (begin (close-port port) #t)
624 #f)))))
625
626(define file-is-directory?
627 (if (feature? 'i/o-extensions)
628 (lambda (str)
3afb28ce 629 (eq? (stat:type (stat str)) 'directory))
6fa8995c
GH
630 (lambda (str)
631 (display str)
632 (newline)
633 (let ((port (catch 'system-error
634 (lambda () (open-file (string-append str "/.")
635 OPEN_READ))
636 (lambda args #f))))
637 (if port (begin (close-port port) #t)
638 #f)))))
0f2d19dd
JB
639
640(define (has-suffix? str suffix)
641 (let ((sufl (string-length suffix))
642 (sl (string-length str)))
643 (and (> sl sufl)
644 (string=? (substring str (- sl sufl) sl) suffix))))
645
0f2d19dd
JB
646\f
647;;; {Error Handling}
648;;;
649
0f2d19dd 650(define (error . args)
21ed9efe 651 (save-stack)
2194b6f0 652 (if (null? args)
5552355a 653 (scm-error 'misc-error #f "?" #f #f)
2194b6f0
GH
654 (let loop ((msg "%s")
655 (rest (cdr args)))
656 (if (not (null? rest))
657 (loop (string-append msg " %S")
658 (cdr rest))
5552355a 659 (scm-error 'misc-error #f msg args #f)))))
be2d2c70 660
1349bd53 661;; bad-throw is the hook that is called upon a throw to a an unhandled
9a0d70e2
GH
662;; key (unless the throw has four arguments, in which case
663;; it's usually interpreted as an error throw.)
664;; If the key has a default handler (a throw-handler-default property),
0f2d19dd
JB
665;; it is applied to the throw.
666;;
1349bd53 667(define (bad-throw key . args)
0f2d19dd
JB
668 (let ((default (symbol-property key 'throw-handler-default)))
669 (or (and default (apply default key args))
2194b6f0 670 (apply error "unhandled-exception:" key args))))
0f2d19dd 671
0f2d19dd 672\f
44cf1f0f
JB
673;;; {Non-polymorphic versions of POSIX functions}
674
02b754d3
GH
675(define (getgrnam name) (getgr name))
676(define (getgrgid id) (getgr id))
677(define (gethostbyaddr addr) (gethost addr))
678(define (gethostbyname name) (gethost name))
679(define (getnetbyaddr addr) (getnet addr))
680(define (getnetbyname name) (getnet name))
681(define (getprotobyname name) (getproto name))
682(define (getprotobynumber addr) (getproto addr))
683(define (getpwnam name) (getpw name))
684(define (getpwuid uid) (getpw uid))
920235cc
GH
685(define (getservbyname name proto) (getserv name proto))
686(define (getservbyport port proto) (getserv port proto))
0f2d19dd
JB
687(define (endgrent) (setgr))
688(define (endhostent) (sethost))
689(define (endnetent) (setnet))
690(define (endprotoent) (setproto))
691(define (endpwent) (setpw))
692(define (endservent) (setserv))
02b754d3
GH
693(define (getgrent) (getgr))
694(define (gethostent) (gethost))
695(define (getnetent) (getnet))
696(define (getprotoent) (getproto))
697(define (getpwent) (getpw))
698(define (getservent) (getserv))
0f2d19dd 699(define (reopen-file . args) (apply freopen args))
bce074ee
GH
700(define (setgrent) (setgr #f))
701(define (sethostent) (sethost #t))
702(define (setnetent) (setnet #t))
703(define (setprotoent) (setproto #t))
704(define (setpwent) (setpw #t))
705(define (setservent) (setserv #t))
706
707(define (passwd:name obj) (vector-ref obj 0))
708(define (passwd:passwd obj) (vector-ref obj 1))
709(define (passwd:uid obj) (vector-ref obj 2))
710(define (passwd:gid obj) (vector-ref obj 3))
711(define (passwd:gecos obj) (vector-ref obj 4))
712(define (passwd:dir obj) (vector-ref obj 5))
713(define (passwd:shell obj) (vector-ref obj 6))
714
715(define (group:name obj) (vector-ref obj 0))
716(define (group:passwd obj) (vector-ref obj 1))
717(define (group:gid obj) (vector-ref obj 2))
718(define (group:mem obj) (vector-ref obj 3))
719
720(define (hostent:name obj) (vector-ref obj 0))
721(define (hostent:aliases obj) (vector-ref obj 1))
722(define (hostent:addrtype obj) (vector-ref obj 2))
723(define (hostent:length obj) (vector-ref obj 3))
724(define (hostent:addr-list obj) (vector-ref obj 4))
725
726(define (netent:name obj) (vector-ref obj 0))
727(define (netent:aliases obj) (vector-ref obj 1))
9337637f
GH
728(define (netent:addrtype obj) (vector-ref obj 2))
729(define (netent:net obj) (vector-ref obj 3))
bce074ee
GH
730
731(define (protoent:name obj) (vector-ref obj 0))
732(define (protoent:aliases obj) (vector-ref obj 1))
733(define (protoent:proto obj) (vector-ref obj 2))
734
735(define (servent:name obj) (vector-ref obj 0))
736(define (servent:aliases obj) (vector-ref obj 1))
9337637f
GH
737(define (servent:port obj) (vector-ref obj 2))
738(define (servent:proto obj) (vector-ref obj 3))
739
740(define (sockaddr:fam obj) (vector-ref obj 0))
741(define (sockaddr:path obj) (vector-ref obj 1))
742(define (sockaddr:addr obj) (vector-ref obj 1))
743(define (sockaddr:port obj) (vector-ref obj 2))
744
745(define (utsname:sysname obj) (vector-ref obj 0))
746(define (utsname:nodename obj) (vector-ref obj 1))
747(define (utsname:release obj) (vector-ref obj 2))
748(define (utsname:version obj) (vector-ref obj 3))
749(define (utsname:machine obj) (vector-ref obj 4))
bce074ee 750
708bf0f3
GH
751(define (tm:sec obj) (vector-ref obj 0))
752(define (tm:min obj) (vector-ref obj 1))
753(define (tm:hour obj) (vector-ref obj 2))
754(define (tm:mday obj) (vector-ref obj 3))
755(define (tm:mon obj) (vector-ref obj 4))
756(define (tm:year obj) (vector-ref obj 5))
757(define (tm:wday obj) (vector-ref obj 6))
758(define (tm:yday obj) (vector-ref obj 7))
759(define (tm:isdst obj) (vector-ref obj 8))
760(define (tm:gmtoff obj) (vector-ref obj 9))
761(define (tm:zone obj) (vector-ref obj 10))
762
763(define (set-tm:sec obj val) (vector-set! obj 0 val))
764(define (set-tm:min obj val) (vector-set! obj 1 val))
765(define (set-tm:hour obj val) (vector-set! obj 2 val))
766(define (set-tm:mday obj val) (vector-set! obj 3 val))
767(define (set-tm:mon obj val) (vector-set! obj 4 val))
768(define (set-tm:year obj val) (vector-set! obj 5 val))
769(define (set-tm:wday obj val) (vector-set! obj 6 val))
770(define (set-tm:yday obj val) (vector-set! obj 7 val))
771(define (set-tm:isdst obj val) (vector-set! obj 8 val))
772(define (set-tm:gmtoff obj val) (vector-set! obj 9 val))
773(define (set-tm:zone obj val) (vector-set! obj 10 val))
774
6afcd3b2
GH
775(define (tms:clock obj) (vector-ref obj 0))
776(define (tms:utime obj) (vector-ref obj 1))
777(define (tms:stime obj) (vector-ref obj 2))
778(define (tms:cutime obj) (vector-ref obj 3))
779(define (tms:cstime obj) (vector-ref obj 4))
780
bce074ee
GH
781(define (file-position . args) (apply ftell args))
782(define (file-set-position . args) (apply fseek args))
8b13c6b3 783
708bf0f3
GH
784(define (open-input-pipe command) (open-pipe command OPEN_READ))
785(define (open-output-pipe command) (open-pipe command OPEN_WRITE))
786
e38303a2
GH
787(define (move->fdes fd/port fd)
788 (cond ((integer? fd/port)
7a6f1ffa 789 (dup->fdes fd/port fd)
e38303a2
GH
790 (close fd/port)
791 fd)
792 (else
793 (primitive-move->fdes fd/port fd)
794 (set-port-revealed! fd/port 1)
795 fd/port)))
8b13c6b3
GH
796
797(define (release-port-handle port)
798 (let ((revealed (port-revealed port)))
799 (if (> revealed 0)
800 (set-port-revealed! port (- revealed 1)))))
0f2d19dd 801
e38303a2 802(define (dup->port port/fd mode . maybe-fd)
7a6f1ffa 803 (let ((port (fdopen (apply dup->fdes port/fd maybe-fd)
e38303a2
GH
804 mode)))
805 (if (pair? maybe-fd)
806 (set-port-revealed! port 1))
807 port))
808
809(define (dup->inport port/fd . maybe-fd)
810 (apply dup->port port/fd "r" maybe-fd))
811
812(define (dup->outport port/fd . maybe-fd)
813 (apply dup->port port/fd "w" maybe-fd))
814
e38303a2
GH
815(define (dup port/fd . maybe-fd)
816 (if (integer? port/fd)
817 (apply dup->fdes port/fd maybe-fd)
818 (apply dup->port port/fd (port-mode port/fd) maybe-fd)))
819
820(define (duplicate-port port modes)
821 (dup->port port modes))
822
823(define (fdes->inport fdes)
824 (let loop ((rest-ports (fdes->ports fdes)))
825 (cond ((null? rest-ports)
826 (let ((result (fdopen fdes "r")))
827 (set-port-revealed! result 1)
828 result))
829 ((input-port? (car rest-ports))
830 (set-port-revealed! (car rest-ports)
831 (+ (port-revealed (car rest-ports)) 1))
832 (car rest-ports))
833 (else
834 (loop (cdr rest-ports))))))
835
836(define (fdes->outport fdes)
837 (let loop ((rest-ports (fdes->ports fdes)))
838 (cond ((null? rest-ports)
839 (let ((result (fdopen fdes "w")))
840 (set-port-revealed! result 1)
841 result))
842 ((output-port? (car rest-ports))
843 (set-port-revealed! (car rest-ports)
844 (+ (port-revealed (car rest-ports)) 1))
845 (car rest-ports))
846 (else
847 (loop (cdr rest-ports))))))
848
849(define (port->fdes port)
850 (set-port-revealed! port (+ (port-revealed port) 1))
851 (fileno port))
852
956055a9
GH
853(define (setenv name value)
854 (if value
855 (putenv (string-append name "=" value))
856 (putenv name)))
857
0f2d19dd
JB
858\f
859;;; {Load Paths}
860;;;
861
0f2d19dd
JB
862;;; Here for backward compatability
863;;
864(define scheme-file-suffix (lambda () ".scm"))
865
3cab8392
JB
866(define (in-vicinity vicinity file)
867 (let ((tail (let ((len (string-length vicinity)))
534a0099
MD
868 (if (zero? len)
869 #f
3cab8392
JB
870 (string-ref vicinity (- len 1))))))
871 (string-append vicinity
534a0099
MD
872 (if (or (not tail)
873 (eq? tail #\/))
874 ""
875 "/")
3cab8392 876 file)))
02ceadb8 877
0f2d19dd 878\f
ef00e7f4
JB
879;;; {Help for scm_shell}
880;;; The argument-processing code used by Guile-based shells generates
881;;; Scheme code based on the argument list. This page contains help
882;;; functions for the code it generates.
883
ef00e7f4
JB
884(define (command-line) (program-arguments))
885
5aa7fe69
JB
886;; This is mostly for the internal use of the code generated by
887;; scm_compile_shell_switches.
ef00e7f4
JB
888(define (load-user-init)
889 (define (has-init? dir)
890 (let ((path (in-vicinity dir ".guile")))
891 (catch 'system-error
892 (lambda ()
893 (let ((stats (stat path)))
894 (if (not (eq? (stat:type stats) 'directory))
895 path)))
896 (lambda dummy #f))))
4cd2a3e6
JB
897 (let ((path (or (has-init? (or (getenv "HOME") "/"))
898 (has-init? (passwd:dir (getpw (getuid)))))))
ef00e7f4
JB
899 (if path (primitive-load path))))
900
901\f
a06181a2
JB
902;;; {Loading by paths}
903
904;;; Load a Scheme source file named NAME, searching for it in the
905;;; directories listed in %load-path, and applying each of the file
906;;; name extensions listed in %load-extensions.
907(define (load-from-path name)
908 (start-stack 'load-stack
75a97b92 909 (primitive-load-path name)))
0f2d19dd 910
5552355a 911
0f2d19dd 912\f
0f2d19dd
JB
913;;; {Transcendental Functions}
914;;;
915;;; Derived from "Transcen.scm", Complex trancendental functions for SCM.
0543c9b7 916;;; Written by Jerry D. Hedden, (C) FSF.
0f2d19dd
JB
917;;; See the file `COPYING' for terms applying to this program.
918;;;
919
920(define (exp z)
921 (if (real? z) ($exp z)
922 (make-polar ($exp (real-part z)) (imag-part z))))
923
924(define (log z)
925 (if (and (real? z) (>= z 0))
926 ($log z)
927 (make-rectangular ($log (magnitude z)) (angle z))))
928
929(define (sqrt z)
930 (if (real? z)
931 (if (negative? z) (make-rectangular 0 ($sqrt (- z)))
932 ($sqrt z))
933 (make-polar ($sqrt (magnitude z)) (/ (angle z) 2))))
934
935(define expt
936 (let ((integer-expt integer-expt))
937 (lambda (z1 z2)
938 (cond ((exact? z2)
939 (integer-expt z1 z2))
940 ((and (real? z2) (real? z1) (>= z1 0))
941 ($expt z1 z2))
942 (else
943 (exp (* z2 (log z1))))))))
944
945(define (sinh z)
946 (if (real? z) ($sinh z)
947 (let ((x (real-part z)) (y (imag-part z)))
948 (make-rectangular (* ($sinh x) ($cos y))
949 (* ($cosh x) ($sin y))))))
950(define (cosh z)
951 (if (real? z) ($cosh z)
952 (let ((x (real-part z)) (y (imag-part z)))
953 (make-rectangular (* ($cosh x) ($cos y))
954 (* ($sinh x) ($sin y))))))
955(define (tanh z)
956 (if (real? z) ($tanh z)
957 (let* ((x (* 2 (real-part z)))
958 (y (* 2 (imag-part z)))
959 (w (+ ($cosh x) ($cos y))))
960 (make-rectangular (/ ($sinh x) w) (/ ($sin y) w)))))
961
962(define (asinh z)
963 (if (real? z) ($asinh z)
964 (log (+ z (sqrt (+ (* z z) 1))))))
965
966(define (acosh z)
967 (if (and (real? z) (>= z 1))
968 ($acosh z)
969 (log (+ z (sqrt (- (* z z) 1))))))
970
971(define (atanh z)
972 (if (and (real? z) (> z -1) (< z 1))
973 ($atanh z)
974 (/ (log (/ (+ 1 z) (- 1 z))) 2)))
975
976(define (sin z)
977 (if (real? z) ($sin z)
978 (let ((x (real-part z)) (y (imag-part z)))
979 (make-rectangular (* ($sin x) ($cosh y))
980 (* ($cos x) ($sinh y))))))
981(define (cos z)
982 (if (real? z) ($cos z)
983 (let ((x (real-part z)) (y (imag-part z)))
984 (make-rectangular (* ($cos x) ($cosh y))
985 (- (* ($sin x) ($sinh y)))))))
986(define (tan z)
987 (if (real? z) ($tan z)
988 (let* ((x (* 2 (real-part z)))
989 (y (* 2 (imag-part z)))
990 (w (+ ($cos x) ($cosh y))))
991 (make-rectangular (/ ($sin x) w) (/ ($sinh y) w)))))
992
993(define (asin z)
994 (if (and (real? z) (>= z -1) (<= z 1))
995 ($asin z)
996 (* -i (asinh (* +i z)))))
997
998(define (acos z)
999 (if (and (real? z) (>= z -1) (<= z 1))
1000 ($acos z)
1001 (+ (/ (angle -1) 2) (* +i (asinh (* +i z))))))
1002
1003(define (atan z . y)
1004 (if (null? y)
1005 (if (real? z) ($atan z)
1006 (/ (log (/ (- +i z) (+ +i z))) +2i))
1007 ($atan2 z (car y))))
1008
1009(set! abs magnitude)
1010
65495221
GH
1011(define (log10 arg)
1012 (/ (log arg) (log 10)))
1013
0f2d19dd 1014\f
0f2d19dd
JB
1015
1016;;; {Reader Extensions}
1017;;;
1018
1019;;; Reader code for various "#c" forms.
1020;;;
1021
fb6d1065
JB
1022;;; Parse the portion of a #/ list that comes after the first slash.
1023(define (read-path-list-notation slash port)
1024 (letrec
1025
1026 ;; Is C a delimiter?
1027 ((delimiter? (lambda (c) (or (eof-object? c)
1028 (char-whitespace? c)
1029 (string-index "()\";" c))))
1030
1031 ;; Read and return one component of a path list.
1032 (read-component
1033 (lambda ()
1034 (let loop ((reversed-chars '()))
1035 (let ((c (peek-char port)))
1036 (if (or (delimiter? c)
1037 (char=? c #\/))
1038 (string->symbol (list->string (reverse reversed-chars)))
1039 (loop (cons (read-char port) reversed-chars))))))))
1040
1041 ;; Read and return a path list.
1042 (let loop ((reversed-path (list (read-component))))
1043 (let ((c (peek-char port)))
1044 (if (and (char? c) (char=? c #\/))
1045 (begin
1046 (read-char port)
1047 (loop (cons (read-component) reversed-path)))
1048 (reverse reversed-path))))))
0f2d19dd 1049
bf7bc911
JB
1050(define (read-path-list-notation-warning slash port)
1051 (if (not (getenv "GUILE_HUSH"))
1052 (begin
1053 (display "warning: obsolete `#/' list notation read from "
1054 (current-error-port))
1055 (display (port-filename port) (current-error-port))
1056 (display "; see guile-core/NEWS." (current-error-port))
1057 (newline (current-error-port))
1058 (display " Set the GUILE_HUSH environment variable to disable this warning."
1059 (current-error-port))
1060 (newline (current-error-port))))
1061 (read-hash-extend #\/ read-path-list-notation)
1062 (read-path-list-notation slash port))
1063
1064
75a97b92
GH
1065(read-hash-extend #\' (lambda (c port)
1066 (read port)))
1067(read-hash-extend #\. (lambda (c port)
1068 (eval (read port))))
1069
1070(if (feature? 'array)
1071 (begin
1072 (let ((make-array-proc (lambda (template)
1073 (lambda (c port)
1074 (read:uniform-vector template port)))))
1075 (for-each (lambda (char template)
1076 (read-hash-extend char
1077 (make-array-proc template)))
c8f11b97
MD
1078 '(#\b #\a #\u #\e #\s #\i #\c #\y #\h)
1079 '(#t #\a 1 -1 1.0 1/3 0+i #\nul s)))
75a97b92
GH
1080 (let ((array-proc (lambda (c port)
1081 (read:array c port))))
1082 (for-each (lambda (char) (read-hash-extend char array-proc))
1083 '(#\0 #\1 #\2 #\3 #\4 #\5 #\6 #\7 #\8 #\9)))))
1084
00c34e45
GH
1085;; pushed to the beginning of the alist since it's used more than the
1086;; others at present.
bf7bc911 1087(read-hash-extend #\/ read-path-list-notation-warning)
00c34e45 1088
0f2d19dd
JB
1089(define (read:array digit port)
1090 (define chr0 (char->integer #\0))
1091 (let ((rank (let readnum ((val (- (char->integer digit) chr0)))
1092 (if (char-numeric? (peek-char port))
1093 (readnum (+ (* 10 val)
1094 (- (char->integer (read-char port)) chr0)))
1095 val)))
1096 (prot (if (eq? #\( (peek-char port))
1097 '()
1098 (let ((c (read-char port)))
1099 (case c ((#\b) #t)
1100 ((#\a) #\a)
1101 ((#\u) 1)
1102 ((#\e) -1)
1103 ((#\s) 1.0)
1104 ((#\i) 1/3)
1105 ((#\c) 0+i)
1106 (else (error "read:array unknown option " c)))))))
1107 (if (eq? (peek-char port) #\()
75a97b92 1108 (list->uniform-array rank prot (read port))
0f2d19dd
JB
1109 (error "read:array list not found"))))
1110
1111(define (read:uniform-vector proto port)
1112 (if (eq? #\( (peek-char port))
75a97b92 1113 (list->uniform-array 1 proto (read port))
0f2d19dd
JB
1114 (error "read:uniform-vector list not found")))
1115
0f2d19dd
JB
1116\f
1117;;; {Command Line Options}
1118;;;
1119
1120(define (get-option argv kw-opts kw-args return)
1121 (cond
1122 ((null? argv)
1123 (return #f #f argv))
1124
1125 ((or (not (eq? #\- (string-ref (car argv) 0)))
1126 (eq? (string-length (car argv)) 1))
1127 (return 'normal-arg (car argv) (cdr argv)))
1128
1129 ((eq? #\- (string-ref (car argv) 1))
1130 (let* ((kw-arg-pos (or (string-index (car argv) #\=)
1131 (string-length (car argv))))
1132 (kw (symbol->keyword (substring (car argv) 2 kw-arg-pos)))
1133 (kw-opt? (member kw kw-opts))
1134 (kw-arg? (member kw kw-args))
1135 (arg (or (and (not (eq? kw-arg-pos (string-length (car argv))))
1136 (substring (car argv)
1137 (+ kw-arg-pos 1)
1138 (string-length (car argv))))
1139 (and kw-arg?
1140 (begin (set! argv (cdr argv)) (car argv))))))
1141 (if (or kw-opt? kw-arg?)
1142 (return kw arg (cdr argv))
1143 (return 'usage-error kw (cdr argv)))))
1144
1145 (else
1146 (let* ((char (substring (car argv) 1 2))
1147 (kw (symbol->keyword char)))
1148 (cond
1149
1150 ((member kw kw-opts)
1151 (let* ((rest-car (substring (car argv) 2 (string-length (car argv))))
1152 (new-argv (if (= 0 (string-length rest-car))
1153 (cdr argv)
1154 (cons (string-append "-" rest-car) (cdr argv)))))
1155 (return kw #f new-argv)))
1156
1157 ((member kw kw-args)
1158 (let* ((rest-car (substring (car argv) 2 (string-length (car argv))))
1159 (arg (if (= 0 (string-length rest-car))
1160 (cadr argv)
1161 rest-car))
1162 (new-argv (if (= 0 (string-length rest-car))
1163 (cddr argv)
1164 (cdr argv))))
1165 (return kw arg new-argv)))
1166
1167 (else (return 'usage-error kw argv)))))))
1168
1169(define (for-next-option proc argv kw-opts kw-args)
1170 (let loop ((argv argv))
1171 (get-option argv kw-opts kw-args
1172 (lambda (opt opt-arg argv)
1173 (and opt (proc opt opt-arg argv loop))))))
1174
1175(define (display-usage-report kw-desc)
1176 (for-each
1177 (lambda (kw)
1178 (or (eq? (car kw) #t)
1179 (eq? (car kw) 'else)
1180 (let* ((opt-desc kw)
1181 (help (cadr opt-desc))
1182 (opts (car opt-desc))
1183 (opts-proper (if (string? (car opts)) (cdr opts) opts))
1184 (arg-name (if (string? (car opts))
1185 (string-append "<" (car opts) ">")
1186 ""))
1187 (left-part (string-append
1188 (with-output-to-string
1189 (lambda ()
1190 (map (lambda (x) (display (keyword-symbol x)) (display " "))
1191 opts-proper)))
1192 arg-name))
11b05261
MD
1193 (middle-part (if (and (< (string-length left-part) 30)
1194 (< (string-length help) 40))
1195 (make-string (- 30 (string-length left-part)) #\ )
0f2d19dd
JB
1196 "\n\t")))
1197 (display left-part)
1198 (display middle-part)
1199 (display help)
1200 (newline))))
1201 kw-desc))
1202
1203
1204
0f2d19dd
JB
1205(define (transform-usage-lambda cases)
1206 (let* ((raw-usage (delq! 'else (map car cases)))
1207 (usage-sans-specials (map (lambda (x)
1208 (or (and (not (list? x)) x)
1209 (and (symbol? (car x)) #t)
1210 (and (boolean? (car x)) #t)
1211 x))
1212 raw-usage))
ed440df5 1213 (usage-desc (delq! #t usage-sans-specials))
0f2d19dd
JB
1214 (kw-desc (map car usage-desc))
1215 (kw-opts (apply append (map (lambda (x) (and (not (string? (car x))) x)) kw-desc)))
1216 (kw-args (apply append (map (lambda (x) (and (string? (car x)) (cdr x))) kw-desc)))
1217 (transmogrified-cases (map (lambda (case)
1218 (cons (let ((opts (car case)))
1219 (if (or (boolean? opts) (eq? 'else opts))
1220 opts
1221 (cond
1222 ((symbol? (car opts)) opts)
1223 ((boolean? (car opts)) opts)
1224 ((string? (caar opts)) (cdar opts))
1225 (else (car opts)))))
1226 (cdr case)))
1227 cases)))
1228 `(let ((%display-usage (lambda () (display-usage-report ',usage-desc))))
1229 (lambda (%argv)
1230 (let %next-arg ((%argv %argv))
1231 (get-option %argv
1232 ',kw-opts
1233 ',kw-args
1234 (lambda (%opt %arg %new-argv)
1235 (case %opt
1236 ,@ transmogrified-cases))))))))
1237
1238
1239\f
1240
1241;;; {Low Level Modules}
1242;;;
1243;;; These are the low level data structures for modules.
1244;;;
1245;;; !!! warning: The interface to lazy binder procedures is going
1246;;; to be changed in an incompatible way to permit all the basic
1247;;; module ops to be virtualized.
1248;;;
1249;;; (make-module size use-list lazy-binding-proc) => module
1250;;; module-{obarray,uses,binder}[|-set!]
1251;;; (module? obj) => [#t|#f]
1252;;; (module-locally-bound? module symbol) => [#t|#f]
1253;;; (module-bound? module symbol) => [#t|#f]
1254;;; (module-symbol-locally-interned? module symbol) => [#t|#f]
1255;;; (module-symbol-interned? module symbol) => [#t|#f]
1256;;; (module-local-variable module symbol) => [#<variable ...> | #f]
1257;;; (module-variable module symbol) => [#<variable ...> | #f]
1258;;; (module-symbol-binding module symbol opt-value)
1259;;; => [ <obj> | opt-value | an error occurs ]
1260;;; (module-make-local-var! module symbol) => #<variable...>
1261;;; (module-add! module symbol var) => unspecified
1262;;; (module-remove! module symbol) => unspecified
1263;;; (module-for-each proc module) => unspecified
1264;;; (make-scm-module) => module ; a lazy copy of the symhash module
1265;;; (set-current-module module) => unspecified
1266;;; (current-module) => #<module...>
1267;;;
1268;;;
1269
1270\f
44cf1f0f
JB
1271;;; {Printing Modules}
1272;; This is how modules are printed. You can re-define it.
fa7e9274
MV
1273;; (Redefining is actually more complicated than simply redefining
1274;; %print-module because that would only change the binding and not
1275;; the value stored in the vtable that determines how record are
1276;; printed. Sigh.)
1277
1278(define (%print-module mod port) ; unused args: depth length style table)
0f2d19dd
JB
1279 (display "#<" port)
1280 (display (or (module-kind mod) "module") port)
1281 (let ((name (module-name mod)))
1282 (if name
1283 (begin
1284 (display " " port)
1285 (display name port))))
1286 (display " " port)
1287 (display (number->string (object-address mod) 16) port)
1288 (display ">" port))
1289
1290;; module-type
1291;;
1292;; A module is characterized by an obarray in which local symbols
1293;; are interned, a list of modules, "uses", from which non-local
1294;; bindings can be inherited, and an optional lazy-binder which
31d50456 1295;; is a (CLOSURE module symbol) which, as a last resort, can provide
0f2d19dd
JB
1296;; bindings that would otherwise not be found locally in the module.
1297;;
1298(define module-type
7a0ff2f8
MD
1299 (make-record-type 'module
1300 '(obarray uses binder eval-closure transformer name kind)
8b718458 1301 %print-module))
0f2d19dd 1302
8b718458 1303;; make-module &opt size uses binder
0f2d19dd 1304;;
8b718458
JB
1305;; Create a new module, perhaps with a particular size of obarray,
1306;; initial uses list, or binding procedure.
0f2d19dd 1307;;
0f2d19dd
JB
1308(define make-module
1309 (lambda args
0f2d19dd 1310
8b718458
JB
1311 (define (parse-arg index default)
1312 (if (> (length args) index)
1313 (list-ref args index)
1314 default))
1315
1316 (if (> (length args) 3)
1317 (error "Too many args to make-module." args))
0f2d19dd 1318
8b718458
JB
1319 (let ((size (parse-arg 0 1021))
1320 (uses (parse-arg 1 '()))
1321 (binder (parse-arg 2 #f)))
0f2d19dd 1322
8b718458
JB
1323 (if (not (integer? size))
1324 (error "Illegal size to make-module." size))
1325 (if (not (and (list? uses)
1326 (and-map module? uses)))
1327 (error "Incorrect use list." uses))
0f2d19dd
JB
1328 (if (and binder (not (procedure? binder)))
1329 (error
1330 "Lazy-binder expected to be a procedure or #f." binder))
1331
8b718458 1332 (let ((module (module-constructor (make-vector size '())
7a0ff2f8 1333 uses binder #f #f #f #f)))
8b718458
JB
1334
1335 ;; We can't pass this as an argument to module-constructor,
1336 ;; because we need it to close over a pointer to the module
1337 ;; itself.
31d50456 1338 (set-module-eval-closure! module
8b718458
JB
1339 (lambda (symbol define?)
1340 (if define?
1341 (module-make-local-var! module symbol)
1342 (module-variable module symbol))))
1343
1344 module))))
0f2d19dd 1345
8b718458 1346(define module-constructor (record-constructor module-type))
0f2d19dd
JB
1347(define module-obarray (record-accessor module-type 'obarray))
1348(define set-module-obarray! (record-modifier module-type 'obarray))
1349(define module-uses (record-accessor module-type 'uses))
1350(define set-module-uses! (record-modifier module-type 'uses))
1351(define module-binder (record-accessor module-type 'binder))
1352(define set-module-binder! (record-modifier module-type 'binder))
31d50456
JB
1353(define module-eval-closure (record-accessor module-type 'eval-closure))
1354(define set-module-eval-closure! (record-modifier module-type 'eval-closure))
7a0ff2f8
MD
1355(define module-transformer (record-accessor module-type 'transformer))
1356(define set-module-transformer! (record-modifier module-type 'transformer))
0f2d19dd
JB
1357(define module-name (record-accessor module-type 'name))
1358(define set-module-name! (record-modifier module-type 'name))
1359(define module-kind (record-accessor module-type 'kind))
1360(define set-module-kind! (record-modifier module-type 'kind))
1361(define module? (record-predicate module-type))
1362
8b718458 1363
0f2d19dd 1364(define (eval-in-module exp module)
31d50456 1365 (eval2 exp (module-eval-closure module)))
0f2d19dd
JB
1366
1367\f
1368;;; {Module Searching in General}
1369;;;
1370;;; We sometimes want to look for properties of a symbol
1371;;; just within the obarray of one module. If the property
1372;;; holds, then it is said to hold ``locally'' as in, ``The symbol
1373;;; DISPLAY is locally rebound in the module `safe-guile'.''
1374;;;
1375;;;
1376;;; Other times, we want to test for a symbol property in the obarray
1377;;; of M and, if it is not found there, try each of the modules in the
1378;;; uses list of M. This is the normal way of testing for some
1379;;; property, so we state these properties without qualification as
1380;;; in: ``The symbol 'fnord is interned in module M because it is
1381;;; interned locally in module M2 which is a member of the uses list
1382;;; of M.''
1383;;;
1384
1385;; module-search fn m
1386;;
1387;; return the first non-#f result of FN applied to M and then to
1388;; the modules in the uses of m, and so on recursively. If all applications
1389;; return #f, then so does this function.
1390;;
1391(define (module-search fn m v)
1392 (define (loop pos)
1393 (and (pair? pos)
1394 (or (module-search fn (car pos) v)
1395 (loop (cdr pos)))))
1396 (or (fn m v)
1397 (loop (module-uses m))))
1398
1399
1400;;; {Is a symbol bound in a module?}
1401;;;
1402;;; Symbol S in Module M is bound if S is interned in M and if the binding
1403;;; of S in M has been set to some well-defined value.
1404;;;
1405
1406;; module-locally-bound? module symbol
1407;;
1408;; Is a symbol bound (interned and defined) locally in a given module?
1409;;
1410(define (module-locally-bound? m v)
1411 (let ((var (module-local-variable m v)))
1412 (and var
1413 (variable-bound? var))))
1414
1415;; module-bound? module symbol
1416;;
1417;; Is a symbol bound (interned and defined) anywhere in a given module
1418;; or its uses?
1419;;
1420(define (module-bound? m v)
1421 (module-search module-locally-bound? m v))
1422
1423;;; {Is a symbol interned in a module?}
1424;;;
1425;;; Symbol S in Module M is interned if S occurs in
1426;;; of S in M has been set to some well-defined value.
1427;;;
1428;;; It is possible to intern a symbol in a module without providing
1429;;; an initial binding for the corresponding variable. This is done
1430;;; with:
1431;;; (module-add! module symbol (make-undefined-variable))
1432;;;
1433;;; In that case, the symbol is interned in the module, but not
1434;;; bound there. The unbound symbol shadows any binding for that
1435;;; symbol that might otherwise be inherited from a member of the uses list.
1436;;;
1437
1438(define (module-obarray-get-handle ob key)
1439 ((if (symbol? key) hashq-get-handle hash-get-handle) ob key))
1440
1441(define (module-obarray-ref ob key)
1442 ((if (symbol? key) hashq-ref hash-ref) ob key))
1443
1444(define (module-obarray-set! ob key val)
1445 ((if (symbol? key) hashq-set! hash-set!) ob key val))
1446
1447(define (module-obarray-remove! ob key)
1448 ((if (symbol? key) hashq-remove! hash-remove!) ob key))
1449
1450;; module-symbol-locally-interned? module symbol
1451;;
1452;; is a symbol interned (not neccessarily defined) locally in a given module
1453;; or its uses? Interned symbols shadow inherited bindings even if
1454;; they are not themselves bound to a defined value.
1455;;
1456(define (module-symbol-locally-interned? m v)
1457 (not (not (module-obarray-get-handle (module-obarray m) v))))
1458
1459;; module-symbol-interned? module symbol
1460;;
1461;; is a symbol interned (not neccessarily defined) anywhere in a given module
1462;; or its uses? Interned symbols shadow inherited bindings even if
1463;; they are not themselves bound to a defined value.
1464;;
1465(define (module-symbol-interned? m v)
1466 (module-search module-symbol-locally-interned? m v))
1467
1468
1469;;; {Mapping modules x symbols --> variables}
1470;;;
1471
1472;; module-local-variable module symbol
1473;; return the local variable associated with a MODULE and SYMBOL.
1474;;
1475;;; This function is very important. It is the only function that can
1476;;; return a variable from a module other than the mutators that store
1477;;; new variables in modules. Therefore, this function is the location
1478;;; of the "lazy binder" hack.
1479;;;
1480;;; If symbol is defined in MODULE, and if the definition binds symbol
1481;;; to a variable, return that variable object.
1482;;;
1483;;; If the symbols is not found at first, but the module has a lazy binder,
1484;;; then try the binder.
1485;;;
1486;;; If the symbol is not found at all, return #f.
1487;;;
1488(define (module-local-variable m v)
6fa8995c
GH
1489; (caddr
1490; (list m v
0f2d19dd
JB
1491 (let ((b (module-obarray-ref (module-obarray m) v)))
1492 (or (and (variable? b) b)
1493 (and (module-binder m)
6fa8995c
GH
1494 ((module-binder m) m v #f)))))
1495;))
0f2d19dd
JB
1496
1497;; module-variable module symbol
1498;;
1499;; like module-local-variable, except search the uses in the
1500;; case V is not found in M.
1501;;
1502(define (module-variable m v)
1503 (module-search module-local-variable m v))
1504
1505
1506;;; {Mapping modules x symbols --> bindings}
1507;;;
1508;;; These are similar to the mapping to variables, except that the
1509;;; variable is dereferenced.
1510;;;
1511
1512;; module-symbol-binding module symbol opt-value
1513;;
1514;; return the binding of a variable specified by name within
1515;; a given module, signalling an error if the variable is unbound.
1516;; If the OPT-VALUE is passed, then instead of signalling an error,
1517;; return OPT-VALUE.
1518;;
1519(define (module-symbol-local-binding m v . opt-val)
1520 (let ((var (module-local-variable m v)))
1521 (if var
1522 (variable-ref var)
1523 (if (not (null? opt-val))
1524 (car opt-val)
1525 (error "Locally unbound variable." v)))))
1526
1527;; module-symbol-binding module symbol opt-value
1528;;
1529;; return the binding of a variable specified by name within
1530;; a given module, signalling an error if the variable is unbound.
1531;; If the OPT-VALUE is passed, then instead of signalling an error,
1532;; return OPT-VALUE.
1533;;
1534(define (module-symbol-binding m v . opt-val)
1535 (let ((var (module-variable m v)))
1536 (if var
1537 (variable-ref var)
1538 (if (not (null? opt-val))
1539 (car opt-val)
1540 (error "Unbound variable." v)))))
1541
1542
1543\f
1544;;; {Adding Variables to Modules}
1545;;;
1546;;;
1547
1548
1549;; module-make-local-var! module symbol
1550;;
1551;; ensure a variable for V in the local namespace of M.
1552;; If no variable was already there, then create a new and uninitialzied
1553;; variable.
1554;;
1555(define (module-make-local-var! m v)
1556 (or (let ((b (module-obarray-ref (module-obarray m) v)))
1557 (and (variable? b) b))
1558 (and (module-binder m)
1559 ((module-binder m) m v #t))
1560 (begin
1561 (let ((answer (make-undefined-variable v)))
1562 (module-obarray-set! (module-obarray m) v answer)
1563 answer))))
1564
1565;; module-add! module symbol var
1566;;
1567;; ensure a particular variable for V in the local namespace of M.
1568;;
1569(define (module-add! m v var)
1570 (if (not (variable? var))
1571 (error "Bad variable to module-add!" var))
1572 (module-obarray-set! (module-obarray m) v var))
1573
1574;; module-remove!
1575;;
1576;; make sure that a symbol is undefined in the local namespace of M.
1577;;
1578(define (module-remove! m v)
1579 (module-obarray-remove! (module-obarray m) v))
1580
1581(define (module-clear! m)
1582 (vector-fill! (module-obarray m) '()))
1583
1584;; MODULE-FOR-EACH -- exported
1585;;
1586;; Call PROC on each symbol in MODULE, with arguments of (SYMBOL VARIABLE).
1587;;
1588(define (module-for-each proc module)
1589 (let ((obarray (module-obarray module)))
1590 (do ((index 0 (+ index 1))
1591 (end (vector-length obarray)))
1592 ((= index end))
1593 (for-each
1594 (lambda (bucket)
1595 (proc (car bucket) (cdr bucket)))
1596 (vector-ref obarray index)))))
1597
1598
1599(define (module-map proc module)
1600 (let* ((obarray (module-obarray module))
1601 (end (vector-length obarray)))
1602
1603 (let loop ((i 0)
1604 (answer '()))
1605 (if (= i end)
1606 answer
1607 (loop (+ 1 i)
1608 (append!
1609 (map (lambda (bucket)
1610 (proc (car bucket) (cdr bucket)))
1611 (vector-ref obarray i))
1612 answer))))))
1613\f
1614
1615;;; {Low Level Bootstrapping}
1616;;;
1617
1618;; make-root-module
1619
21ed9efe 1620;; A root module uses the symhash table (the system's privileged
0f2d19dd
JB
1621;; obarray). Being inside a root module is like using SCM without
1622;; any module system.
1623;;
1624
1625
31d50456 1626(define (root-module-closure m s define?)
0f2d19dd
JB
1627 (let ((bi (and (symbol-interned? #f s)
1628 (builtin-variable s))))
1629 (and bi
1630 (or define? (variable-bound? bi))
1631 (begin
1632 (module-add! m s bi)
1633 bi))))
1634
1635(define (make-root-module)
31d50456 1636 (make-module 1019 '() root-module-closure))
0f2d19dd
JB
1637
1638
1639;; make-scm-module
1640
1641;; An scm module is a module into which the lazy binder copies
1642;; variable bindings from the system symhash table. The mapping is
1643;; one way only; newly introduced bindings in an scm module are not
1644;; copied back into the system symhash table (and can be used to override
1645;; bindings from the symhash table).
1646;;
1647
1648(define (make-scm-module)
8b718458 1649 (make-module 1019 '()
0f2d19dd
JB
1650 (lambda (m s define?)
1651 (let ((bi (and (symbol-interned? #f s)
1652 (builtin-variable s))))
1653 (and bi
1654 (variable-bound? bi)
1655 (begin
1656 (module-add! m s bi)
1657 bi))))))
1658
1659
1660
1661
1662;; the-module
1663;;
1664(define the-module #f)
1665
7a0ff2f8 1666;; scm:eval-transformer
d43f8c97 1667;;
7a0ff2f8 1668(define scm:eval-transformer #f)
d43f8c97 1669
0f2d19dd
JB
1670;; set-current-module module
1671;;
1672;; set the current module as viewed by the normalizer.
1673;;
1674(define (set-current-module m)
7a0ff2f8
MD
1675 (set! the-module m)
1676 (if m
1677 (begin
1678 (set! *top-level-lookup-closure* (module-eval-closure the-module))
1679 (set! scm:eval-transformer (module-transformer the-module)))
1680 (set! *top-level-lookup-closure* #f)))
0f2d19dd
JB
1681
1682
1683;; current-module
1684;;
1685;; return the current module as viewed by the normalizer.
1686;;
1687(define (current-module) the-module)
1688\f
1689;;; {Module-based Loading}
1690;;;
1691
1692(define (save-module-excursion thunk)
1693 (let ((inner-module (current-module))
1694 (outer-module #f))
1695 (dynamic-wind (lambda ()
1696 (set! outer-module (current-module))
1697 (set-current-module inner-module)
1698 (set! inner-module #f))
1699 thunk
1700 (lambda ()
1701 (set! inner-module (current-module))
1702 (set-current-module outer-module)
1703 (set! outer-module #f)))))
1704
0f2d19dd
JB
1705(define basic-load load)
1706
c6775c40
MD
1707(define (load-module filename)
1708 (save-module-excursion
1709 (lambda ()
1710 (let ((oldname (and (current-load-port)
1711 (port-filename (current-load-port)))))
1712 (basic-load (if (and oldname
1713 (> (string-length filename) 0)
1714 (not (char=? (string-ref filename 0) #\/))
1715 (not (string=? (dirname oldname) ".")))
1716 (string-append (dirname oldname) "/" filename)
1717 filename))))))
0f2d19dd
JB
1718
1719
1720\f
44cf1f0f 1721;;; {MODULE-REF -- exported}
0f2d19dd
JB
1722;;
1723;; Returns the value of a variable called NAME in MODULE or any of its
1724;; used modules. If there is no such variable, then if the optional third
1725;; argument DEFAULT is present, it is returned; otherwise an error is signaled.
1726;;
1727(define (module-ref module name . rest)
1728 (let ((variable (module-variable module name)))
1729 (if (and variable (variable-bound? variable))
1730 (variable-ref variable)
1731 (if (null? rest)
1732 (error "No variable named" name 'in module)
1733 (car rest) ; default value
1734 ))))
1735
1736;; MODULE-SET! -- exported
1737;;
1738;; Sets the variable called NAME in MODULE (or in a module that MODULE uses)
1739;; to VALUE; if there is no such variable, an error is signaled.
1740;;
1741(define (module-set! module name value)
1742 (let ((variable (module-variable module name)))
1743 (if variable
1744 (variable-set! variable value)
1745 (error "No variable named" name 'in module))))
1746
1747;; MODULE-DEFINE! -- exported
1748;;
1749;; Sets the variable called NAME in MODULE to VALUE; if there is no such
1750;; variable, it is added first.
1751;;
1752(define (module-define! module name value)
1753 (let ((variable (module-local-variable module name)))
1754 (if variable
1755 (variable-set! variable value)
1756 (module-add! module name (make-variable value name)))))
1757
ed218d98
MV
1758;; MODULE-DEFINED? -- exported
1759;;
1760;; Return #t iff NAME is defined in MODULE (or in a module that MODULE
1761;; uses)
1762;;
1763(define (module-defined? module name)
1764 (let ((variable (module-variable module name)))
1765 (and variable (variable-bound? variable))))
1766
0f2d19dd
JB
1767;; MODULE-USE! module interface
1768;;
1769;; Add INTERFACE to the list of interfaces used by MODULE.
1770;;
1771(define (module-use! module interface)
1772 (set-module-uses! module
7a0ff2f8 1773 (cons interface (delq! interface (module-uses module)))))
0f2d19dd
JB
1774
1775\f
0f2d19dd
JB
1776;;; {Recursive Namespaces}
1777;;;
1778;;;
1779;;; A hierarchical namespace emerges if we consider some module to be
1780;;; root, and variables bound to modules as nested namespaces.
1781;;;
1782;;; The routines in this file manage variable names in hierarchical namespace.
1783;;; Each variable name is a list of elements, looked up in successively nested
1784;;; modules.
1785;;;
0dd5491c 1786;;; (nested-ref some-root-module '(foo bar baz))
0f2d19dd
JB
1787;;; => <value of a variable named baz in the module bound to bar in
1788;;; the module bound to foo in some-root-module>
1789;;;
1790;;;
1791;;; There are:
1792;;;
1793;;; ;; a-root is a module
1794;;; ;; name is a list of symbols
1795;;;
0dd5491c
MD
1796;;; nested-ref a-root name
1797;;; nested-set! a-root name val
1798;;; nested-define! a-root name val
1799;;; nested-remove! a-root name
0f2d19dd
JB
1800;;;
1801;;;
1802;;; (current-module) is a natural choice for a-root so for convenience there are
1803;;; also:
1804;;;
0dd5491c
MD
1805;;; local-ref name == nested-ref (current-module) name
1806;;; local-set! name val == nested-set! (current-module) name val
1807;;; local-define! name val == nested-define! (current-module) name val
1808;;; local-remove! name == nested-remove! (current-module) name
0f2d19dd
JB
1809;;;
1810
1811
0dd5491c 1812(define (nested-ref root names)
0f2d19dd
JB
1813 (let loop ((cur root)
1814 (elts names))
1815 (cond
1816 ((null? elts) cur)
1817 ((not (module? cur)) #f)
1818 (else (loop (module-ref cur (car elts) #f) (cdr elts))))))
1819
0dd5491c 1820(define (nested-set! root names val)
0f2d19dd
JB
1821 (let loop ((cur root)
1822 (elts names))
1823 (if (null? (cdr elts))
1824 (module-set! cur (car elts) val)
1825 (loop (module-ref cur (car elts)) (cdr elts)))))
1826
0dd5491c 1827(define (nested-define! root names val)
0f2d19dd
JB
1828 (let loop ((cur root)
1829 (elts names))
1830 (if (null? (cdr elts))
1831 (module-define! cur (car elts) val)
1832 (loop (module-ref cur (car elts)) (cdr elts)))))
1833
0dd5491c 1834(define (nested-remove! root names)
0f2d19dd
JB
1835 (let loop ((cur root)
1836 (elts names))
1837 (if (null? (cdr elts))
1838 (module-remove! cur (car elts))
1839 (loop (module-ref cur (car elts)) (cdr elts)))))
1840
0dd5491c
MD
1841(define (local-ref names) (nested-ref (current-module) names))
1842(define (local-set! names val) (nested-set! (current-module) names val))
1843(define (local-define names val) (nested-define! (current-module) names val))
1844(define (local-remove names) (nested-remove! (current-module) names))
0f2d19dd
JB
1845
1846
1847\f
8bb7330c 1848;;; {The (app) module}
0f2d19dd
JB
1849;;;
1850;;; The root of conventionally named objects not directly in the top level.
1851;;;
8bb7330c
JB
1852;;; (app modules)
1853;;; (app modules guile)
0f2d19dd
JB
1854;;;
1855;;; The directory of all modules and the standard root module.
1856;;;
1857
1858(define (module-public-interface m) (module-ref m '%module-public-interface #f))
1859(define (set-module-public-interface! m i) (module-define! m '%module-public-interface i))
1860(define the-root-module (make-root-module))
1861(define the-scm-module (make-scm-module))
1862(set-module-public-interface! the-root-module the-scm-module)
1863(set-module-name! the-root-module 'the-root-module)
1864(set-module-name! the-scm-module 'the-scm-module)
1865
1866(set-current-module the-root-module)
1867
1868(define app (make-module 31))
0dd5491c
MD
1869(local-define '(app modules) (make-module 31))
1870(local-define '(app modules guile) the-root-module)
0f2d19dd
JB
1871
1872;; (define-special-value '(app modules new-ws) (lambda () (make-scm-module)))
1873
0209ca9a 1874(define (resolve-module name . maybe-autoload)
0f2d19dd 1875 (let ((full-name (append '(app modules) name)))
0dd5491c 1876 (let ((already (local-ref full-name)))
0f2d19dd
JB
1877 (or already
1878 (begin
0209ca9a 1879 (if (or (null? maybe-autoload) (car maybe-autoload))
a4f9b1f6
MD
1880 (or (try-module-linked name)
1881 (try-module-autoload name)
d0cbd20c 1882 (try-module-dynamic-link name)))
0f2d19dd
JB
1883 (make-modules-in (current-module) full-name))))))
1884
1885(define (beautify-user-module! module)
1886 (if (not (module-public-interface module))
1887 (let ((interface (make-module 31)))
1888 (set-module-name! interface (module-name module))
1889 (set-module-kind! interface 'interface)
1890 (set-module-public-interface! module interface)))
cc7f066c
MD
1891 (if (and (not (memq the-scm-module (module-uses module)))
1892 (not (eq? module the-root-module)))
0f2d19dd
JB
1893 (set-module-uses! module (append (module-uses module) (list the-scm-module)))))
1894
1895(define (make-modules-in module name)
1896 (if (null? name)
1897 module
1898 (cond
1899 ((module-ref module (car name) #f) => (lambda (m) (make-modules-in m (cdr name))))
1900 (else (let ((m (make-module 31)))
1901 (set-module-kind! m 'directory)
1902 (set-module-name! m (car name))
1903 (module-define! module (car name) m)
1904 (make-modules-in m (cdr name)))))))
1905
1906(define (resolve-interface name)
1907 (let ((module (resolve-module name)))
1908 (and module (module-public-interface module))))
1909
1910
1911(define %autoloader-developer-mode #t)
1912
cf266109
MD
1913(define (internal-use-syntax transformer)
1914 (set-module-transformer! (current-module) transformer)
1915 (set! scm:eval-transformer transformer))
1916
0f2d19dd
JB
1917(define (process-define-module args)
1918 (let* ((module-id (car args))
0209ca9a 1919 (module (resolve-module module-id #f))
0f2d19dd
JB
1920 (kws (cdr args)))
1921 (beautify-user-module! module)
0209ca9a
MV
1922 (let loop ((kws kws)
1923 (reversed-interfaces '()))
1924 (if (null? kws)
1925 (for-each (lambda (interface)
1926 (module-use! module interface))
1927 reversed-interfaces)
f714ca8e
MD
1928 (let ((keyword (cond ((keyword? (car kws))
1929 (keyword->symbol (car kws)))
1930 ((and (symbol? (car kws))
1931 (eq? (string-ref (car kws) 0) #\:))
1932 (string->symbol (substring (car kws) 1)))
1933 (else #f))))
1934 (case keyword
1935 ((use-module use-syntax)
1936 (if (not (pair? (cdr kws)))
1937 (error "unrecognized defmodule argument" kws))
1938 (let* ((used-name (cadr kws))
1939 (used-module (resolve-module used-name)))
1940 (if (not (module-ref used-module '%module-public-interface #f))
1941 (begin
1942 ((if %autoloader-developer-mode warn error)
1943 "no code for module" (module-name used-module))
1944 (beautify-user-module! used-module)))
1945 (let ((interface (module-public-interface used-module)))
1946 (if (not interface)
1947 (error "missing interface for use-module" used-module))
1948 (if (eq? keyword 'use-syntax)
cf266109
MD
1949 (internal-use-syntax
1950 (module-ref interface (car (last-pair used-name))
1951 #f)))
f714ca8e
MD
1952 (loop (cddr kws) (cons interface reversed-interfaces)))))
1953 (else
1954 (error "unrecognized defmodule argument" kws))))))
0f2d19dd
JB
1955 module))
1956\f
44cf1f0f 1957;;; {Autoloading modules}
0f2d19dd
JB
1958
1959(define autoloads-in-progress '())
1960
1961(define (try-module-autoload module-name)
6fa8995c 1962
0f2d19dd
JB
1963 (define (sfx name) (string-append name (scheme-file-suffix)))
1964 (let* ((reverse-name (reverse module-name))
1965 (name (car reverse-name))
1966 (dir-hint-module-name (reverse (cdr reverse-name)))
1967 (dir-hint (apply symbol-append (map (lambda (elt) (symbol-append elt "/")) dir-hint-module-name))))
0209ca9a 1968 (resolve-module dir-hint-module-name #f)
0f2d19dd
JB
1969 (and (not (autoload-done-or-in-progress? dir-hint name))
1970 (let ((didit #f))
1971 (dynamic-wind
1972 (lambda () (autoload-in-progress! dir-hint name))
1973 (lambda ()
1974 (let loop ((dirs %load-path))
1975 (and (not (null? dirs))
1976 (or
1977 (let ((d (car dirs))
1978 (trys (list
1979 dir-hint
1980 (sfx dir-hint)
1981 (in-vicinity dir-hint name)
1982 (in-vicinity dir-hint (sfx name)))))
1983 (and (or-map (lambda (f)
1984 (let ((full (in-vicinity d f)))
1985 full
6fa8995c
GH
1986 (and (file-exists? full)
1987 (not (file-is-directory? full))
0f2d19dd
JB
1988 (begin
1989 (save-module-excursion
1990 (lambda ()
5552355a
GH
1991 (load (string-append
1992 d "/" f))))
0f2d19dd
JB
1993 #t))))
1994 trys)
1995 (begin
1996 (set! didit #t)
1997 #t)))
1998 (loop (cdr dirs))))))
1999 (lambda () (set-autoloaded! dir-hint name didit)))
2000 didit))))
2001
d0cbd20c
MV
2002;;; Dynamic linking of modules
2003
2004;; Initializing a module that is written in C is a two step process.
2005;; First the module's `module init' function is called. This function
2006;; is expected to call `scm_register_module_xxx' to register the `real
2007;; init' function. Later, when the module is referenced for the first
2008;; time, this real init function is called in the right context. See
2009;; gtcltk-lib/gtcltk-module.c for an example.
2010;;
2011;; The code for the module can be in a regular shared library (so that
2012;; the `module init' function will be called when libguile is
2013;; initialized). Or it can be dynamically linked.
2014;;
2015;; You can safely call `scm_register_module_xxx' before libguile
2016;; itself is initialized. You could call it from an C++ constructor
2017;; of a static object, for example.
2018;;
2019;; To make your Guile extension into a dynamic linkable module, follow
2020;; these easy steps:
2021;;
8bb7330c 2022;; - Find a name for your module, like (ice-9 gtcltk)
d0cbd20c
MV
2023;; - Write a function with a name like
2024;;
2025;; scm_init_ice_9_gtcltk_module
2026;;
2027;; This is your `module init' function. It should call
2028;;
2029;; scm_register_module_xxx ("ice-9 gtcltk", scm_init_gtcltk);
2030;;
2031;; "ice-9 gtcltk" is the C version of the module name. Slashes are
2032;; replaced by spaces, the rest is untouched. `scm_init_gtcltk' is
ed218d98 2033;; the real init function that executes the usual initializations
d0cbd20c
MV
2034;; like making new smobs, etc.
2035;;
2036;; - Make a shared library with your code and a name like
2037;;
2038;; ice-9/libgtcltk.so
2039;;
2040;; and put it somewhere in %load-path.
2041;;
8bb7330c 2042;; - Then you can simply write `:use-module (ice-9 gtcltk)' and it
d0cbd20c
MV
2043;; will be linked automatically.
2044;;
2045;; This is all very experimental.
2046
2047(define (split-c-module-name str)
2048 (let loop ((rev '())
2049 (start 0)
2050 (pos 0)
2051 (end (string-length str)))
2052 (cond
2053 ((= pos end)
2054 (reverse (cons (string->symbol (substring str start pos)) rev)))
2055 ((eq? (string-ref str pos) #\space)
2056 (loop (cons (string->symbol (substring str start pos)) rev)
2057 (+ pos 1)
2058 (+ pos 1)
2059 end))
2060 (else
2061 (loop rev start (+ pos 1) end)))))
2062
2063(define (convert-c-registered-modules dynobj)
2064 (let ((res (map (lambda (c)
2065 (list (split-c-module-name (car c)) (cdr c) dynobj))
2066 (c-registered-modules))))
2067 (c-clear-registered-modules)
2068 res))
2069
2070(define registered-modules (convert-c-registered-modules #f))
2071
2072(define (init-dynamic-module modname)
2073 (or-map (lambda (modinfo)
2074 (if (equal? (car modinfo) modname)
2075 (let ((mod (resolve-module modname #f)))
2076 (save-module-excursion
2077 (lambda ()
2078 (set-current-module mod)
2079 (dynamic-call (cadr modinfo) (caddr modinfo))
2080 (set-module-public-interface! mod mod)))
2081 (set! registered-modules (delq! modinfo registered-modules))
2082 #t)
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)
6b856182
MV
2164 (let ((dynobj (dynamic-link filename)))
2165 (dynamic-call initname dynobj)
2166 (set! registered-modules
2167 (append! (convert-c-registered-modules dynobj)
2168 registered-modules))))
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
59e1116d
MD
2423(define abort-hook '())
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
59e1116d
MD
2536(define before-error-hook '())
2537(define after-error-hook '())
2538(define before-backtrace-hook '())
2539(define after-backtrace-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
59e1116d
MD
2587(define before-read-hook '())
2588(define after-read-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
0f2d19dd
JB
2740\f
2741
2742;;; {Macros}
2743;;;
2744
2745;; actually....hobbit might be able to hack these with a little
2746;; coaxing
2747;;
2748
2749(defmacro define-macro (first . rest)
2750 (let ((name (if (symbol? first) first (car first)))
2751 (transformer
2752 (if (symbol? first)
2753 (car rest)
2754 `(lambda ,(cdr first) ,@rest))))
2755 `(define ,name (defmacro:transformer ,transformer))))
2756
2757
2758(defmacro define-syntax-macro (first . rest)
2759 (let ((name (if (symbol? first) first (car first)))
2760 (transformer
2761 (if (symbol? first)
2762 (car rest)
2763 `(lambda ,(cdr first) ,@rest))))
2764 `(define ,name (defmacro:syntax-transformer ,transformer))))
2765\f
2766;;; {Module System Macros}
2767;;;
2768
2769(defmacro define-module args
2770 `(let* ((process-define-module process-define-module)
2771 (set-current-module set-current-module)
2772 (module (process-define-module ',args)))
2773 (set-current-module module)
2774 module))
2775
89da9036
MV
2776;; the guts of the use-modules macro. add the interfaces of the named
2777;; modules to the use-list of the current module, in order
2778(define (process-use-modules module-names)
2779 (for-each (lambda (module-name)
2780 (let ((mod-iface (resolve-interface module-name)))
2781 (or mod-iface
2782 (error "no such module" module-name))
2783 (module-use! (current-module) mod-iface)))
2784 (reverse module-names)))
2785
33cf699f 2786(defmacro use-modules modules
89da9036 2787 `(process-use-modules ',modules))
33cf699f 2788
cf266109
MD
2789(defmacro use-syntax (spec)
2790 (if (pair? spec)
2791 `(begin
2792 (process-use-modules ',(list spec))
2793 (internal-use-syntax ,(car (last-pair spec))))
2794 `(internal-use-syntax ,spec)))
7a0ff2f8 2795
0f2d19dd
JB
2796(define define-private define)
2797
2798(defmacro define-public args
2799 (define (syntax)
2800 (error "bad syntax" (list 'define-public args)))
2801 (define (defined-name n)
2802 (cond
3c5af9ef
JB
2803 ((symbol? n) n)
2804 ((pair? n) (defined-name (car n)))
2805 (else (syntax))))
0f2d19dd 2806 (cond
3c5af9ef
JB
2807 ((null? args) (syntax))
2808
2809 (#t (let ((name (defined-name (car args))))
2810 `(begin
2811 (let ((public-i (module-public-interface (current-module))))
2812 ;; Make sure there is a local variable:
2813 ;;
2814 (module-define! (current-module)
2815 ',name
2816 (module-ref (current-module) ',name #f))
0f2d19dd 2817
3c5af9ef
JB
2818 ;; Make sure that local is exported:
2819 ;;
2820 (module-add! public-i ',name
2821 (module-variable (current-module) ',name)))
0f2d19dd 2822
3c5af9ef
JB
2823 ;; Now (re)define the var normally. Bernard URBAN
2824 ;; suggests we use eval here to accomodate Hobbit; it lets
2825 ;; the interpreter handle the define-private form, which
2826 ;; Hobbit can't digest.
2827 (eval '(define-private ,@ args)))))))
0f2d19dd
JB
2828
2829
2830
2831(defmacro defmacro-public args
2832 (define (syntax)
2833 (error "bad syntax" (list 'defmacro-public args)))
2834 (define (defined-name n)
2835 (cond
2836 ((symbol? n) n)
2837 (else (syntax))))
2838 (cond
2839 ((null? args) (syntax))
2840
2841 (#t (let ((name (defined-name (car args))))
2842 `(begin
2843 (let ((public-i (module-public-interface (current-module))))
2844 ;; Make sure there is a local variable:
2845 ;;
2846 (module-define! (current-module)
2847 ',name
2848 (module-ref (current-module) ',name #f))
2849
2850 ;; Make sure that local is exported:
2851 ;;
2852 (module-add! public-i ',name (module-variable (current-module) ',name)))
2853
2854 ;; Now (re)define the var normally.
2855 ;;
2856 (defmacro ,@ args))))))
2857
2858
a0cc0a01
MD
2859(defmacro export names
2860 `(let* ((m (current-module))
2861 (public-i (module-public-interface m)))
2862 (for-each (lambda (name)
2863 ;; Make sure there is a local variable:
2864 (module-define! m name (module-ref m name #f))
2865 ;; Make sure that local is exported:
2866 (module-add! public-i name (module-variable m name)))
2867 ',names)))
2868
2869(define export-syntax export)
2870
2871
0f2d19dd
JB
2872
2873
0f2d19dd
JB
2874(define load load-module)
2875
2876
2877\f
9aca88c3
JB
2878;;; {Load emacs interface support if emacs option is given.}
2879
2880(define (load-emacs-interface)
2881 (if (memq 'debug-extensions *features*)
2882 (debug-enable 'backtrace))
2883 (define-module (guile-user) :use-module (ice-9 emacs)))
2884
2885\f
44cf1f0f 2886;;; {I/O functions for Tcl channels (disabled)}
0f2d19dd
JB
2887
2888;; (define in-ch (get-standard-channel TCL_STDIN))
2889;; (define out-ch (get-standard-channel TCL_STDOUT))
2890;; (define err-ch (get-standard-channel TCL_STDERR))
2891;;
2892;; (define inp (%make-channel-port in-ch "r"))
2893;; (define outp (%make-channel-port out-ch "w"))
2894;; (define errp (%make-channel-port err-ch "w"))
2895;;
2896;; (define %system-char-ready? char-ready?)
2897;;
2898;; (define (char-ready? p)
2899;; (if (not (channel-port? p))
2900;; (%system-char-ready? p)
2901;; (let* ((channel (%channel-port-channel p))
2902;; (old-blocking (channel-option-ref channel :blocking)))
2903;; (dynamic-wind
2904;; (lambda () (set-channel-option the-root-tcl-interpreter channel :blocking "0"))
2905;; (lambda () (not (eof-object? (peek-char p))))
2906;; (lambda () (set-channel-option the-root-tcl-interpreter channel :blocking old-blocking))))))
2907;;
2908;; (define (top-repl)
2909;; (with-input-from-port inp
2910;; (lambda ()
2911;; (with-output-to-port outp
2912;; (lambda ()
2913;; (with-error-to-port errp
2914;; (lambda ()
2915;; (scm-style-repl))))))))
2916;;
2917;; (set-current-input-port inp)
2918;; (set-current-output-port outp)
2919;; (set-current-error-port errp)
2920
e1a191a8
GH
2921;; this is just (scm-style-repl) with a wrapper to install and remove
2922;; signal handlers.
8e44e7a0 2923(define (top-repl)
9aca88c3
JB
2924
2925 ;; Load emacs interface support if emacs option is given.
2926 (if (and (module-defined? the-root-module 'use-emacs-interface)
2927 use-emacs-interface)
2928 (load-emacs-interface))
2929
4fdf8b2c
MD
2930 ;; Place the user in the guile-user module.
2931 (define-module (guile-user))
2932
e1a191a8
GH
2933 (let ((old-handlers #f)
2934 (signals `((,SIGINT . "User interrupt")
2935 (,SIGFPE . "Arithmetic error")
2936 (,SIGBUS . "Bad memory access (bus error)")
2937 (,SIGSEGV . "Bad memory access (Segmentation violation)"))))
2938
2939 (dynamic-wind
2940
2941 ;; call at entry
2942 (lambda ()
2943 (let ((make-handler (lambda (msg)
2944 (lambda (sig)
096d5f90 2945 (save-stack %deliver-signals)
e1a191a8
GH
2946 (scm-error 'signal
2947 #f
2948 msg
2949 #f
2950 (list sig))))))
2951 (set! old-handlers
2952 (map (lambda (sig-msg)
2953 (sigaction (car sig-msg)
2954 (make-handler (cdr sig-msg))))
2955 signals))))
2956
2957 ;; the protected thunk.
2958 (lambda ()
dc5c2038
MD
2959
2960 ;; If we've got readline, use it to prompt the user. This is a
2961 ;; kludge, but we'll fix it soon. At least we only get
2962 ;; readline involved when we're actually running the repl.
2963 (if (and (memq 'readline *features*)
279ba8c0 2964 (isatty? (current-input-port))
dc5c2038
MD
2965 (not (and (module-defined? the-root-module
2966 'use-emacs-interface)
2967 use-emacs-interface)))
2968 (let ((read-hook (lambda () (run-hooks before-read-hook))))
2969 (set-current-input-port (readline-port))
2970 (set! repl-reader
2971 (lambda (prompt)
2972 (dynamic-wind
2973 (lambda ()
2974 (set-readline-prompt! prompt)
2975 (set-readline-read-hook! read-hook))
2976 (lambda () (read))
2977 (lambda ()
2978 (set-readline-prompt! "")
2979 (set-readline-read-hook! #f)))))))
2055a1bc
MD
2980 (let ((status (scm-style-repl)))
2981 (run-hooks exit-hook)
2982 status))
e1a191a8
GH
2983
2984 ;; call at exit.
2985 (lambda ()
2986 (map (lambda (sig-msg old-handler)
2987 (if (not (car old-handler))
2988 ;; restore original C handler.
2989 (sigaction (car sig-msg) #f)
2990 ;; restore Scheme handler, SIG_IGN or SIG_DFL.
2991 (sigaction (car sig-msg)
2992 (car old-handler)
2993 (cdr old-handler))))
2994 signals old-handlers)))))
0f2d19dd 2995
02b754d3
GH
2996(defmacro false-if-exception (expr)
2997 `(catch #t (lambda () ,expr)
2998 (lambda args #f)))
2999
2055a1bc
MD
3000;;; This hook is run at the very end of an interactive session.
3001;;;
3002(define exit-hook '())
3003
13e341bb
MD
3004;;; Load readline code into root module if readline primitives are available.
3005;;;
3006;;; Ideally, we wouldn't do this until we were sure we were actually
3007;;; going to enter the repl, but autoloading individual functions is
3008;;; clumsy at the moment.
3009(if (and (memq 'readline *features*)
3010 (isatty? (current-input-port)))
3011 (begin
3012 (define-module (guile) :use-module (ice-9 readline))
39bc9948 3013 (define-module (guile-user) :use-module (ice-9 readline))))
13e341bb
MD
3014
3015\f
3016;;; {Load debug extension code into user module if debug extensions present.}
c56634ba
MD
3017;;;
3018;;; *fixme* This is a temporary solution.
3019;;;
0f2d19dd 3020
c56634ba 3021(if (memq 'debug-extensions *features*)
39bc9948 3022 (define-module (guile-user) :use-module (ice-9 debug)))
90895e5c
MD
3023
3024\f
13e341bb 3025;;; {Load session support into user module if present.}
90d5e280
MD
3026;;;
3027;;; *fixme* This is a temporary solution.
3028;;;
3029
3030(if (%search-load-path "ice-9/session.scm")
39bc9948 3031 (define-module (guile-user) :use-module (ice-9 session)))
f246e585 3032
13e341bb 3033;;; {Load thread code into user module if threads are present.}
90895e5c
MD
3034;;;
3035;;; *fixme* This is a temporary solution.
3036;;;
3037
3038(if (memq 'threads *features*)
39bc9948 3039 (define-module (guile-user) :use-module (ice-9 threads)))
90895e5c 3040
21ed9efe 3041\f
05817d9e
JB
3042;;; {Load regexp code if regexp primitives are available.}
3043
3044(if (memq 'regex *features*)
5ef4ef4e 3045 (define-module (guile-user) :use-module (ice-9 regex)))
05817d9e
JB
3046
3047\f
13e341bb
MD
3048(define-module (guile))
3049
9946dd45
JB
3050;;; {Check that the interpreter and scheme code match up.}
3051
3052(let ((show-line
3053 (lambda args
3054 (with-output-to-port (current-error-port)
3055 (lambda ()
3056 (display (car (command-line)))
3057 (display ": ")
3058 (for-each (lambda (string) (display string))
3059 args)
3060 (newline))))))
3061
3062 (load-from-path "ice-9/version.scm")
3063
3064 (if (not (string=?
3065 (libguile-config-stamp) ; from the interprpreter
3066 (ice-9-config-stamp))) ; from the Scheme code
3067 (begin
3068 (show-line "warning: different versions of libguile and ice-9:")
3069 (show-line "libguile: configured on " (libguile-config-stamp))
3070 (show-line "ice-9: configured on " (ice-9-config-stamp)))))
3071
13e341bb 3072(append! %load-path (cons "." ()))
21ed9efe 3073