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