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