* scmsigs.h, async.h: updated.
[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))
107 (else (logical:ipow-by-squaring (proc x x)
108 (quotient k 2)
109 (if (even? k) acc (proc acc x))
110 proc))))
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)))
295 (string->symbol (substring sym 1 (length sym)))))
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
0f2d19dd
JB
302;;; {Records}
303;;;
304
305(define record-type-vtable (make-vtable-vtable "prpr" 0))
306
307(define (record-type? obj)
308 (and (struct? obj) (eq? record-type-vtable (struct-vtable obj))))
309
310(define (make-record-type type-name fields . opt)
8e693424 311 (let ((printer-fn (and (pair? opt) (car opt))))
0f2d19dd 312 (let ((struct (make-struct record-type-vtable 0
c7c03b9f
JB
313 (make-struct-layout
314 (apply symbol-append
315 (map (lambda (f) "pw") fields)))
0f2d19dd
JB
316 type-name
317 (copy-tree fields))))
318 ;; !!! leaks printer functions
6355358a
MD
319 ;; MDJ 960919 <djurfeldt@nada.kth.se>: *fixme* need to make it
320 ;; possible to print records nicely.
321 ;(if printer-fn
322; (extend-print-style! default-print-style
323; (logior utag_struct_base (ash (struct-vtable-tag struct) 8))
324; printer-fn))
0f2d19dd
JB
325 struct)))
326
327(define (record-type-name obj)
328 (if (record-type? obj)
329 (struct-ref obj struct-vtable-offset)
330 (error 'not-a-record-type obj)))
331
332(define (record-type-fields obj)
333 (if (record-type? obj)
334 (struct-ref obj (+ 1 struct-vtable-offset))
335 (error 'not-a-record-type obj)))
336
337(define (record-constructor rtd . opt)
8e693424 338 (let ((field-names (if (pair? opt) (car opt) (record-type-fields rtd))))
0f2d19dd
JB
339 (eval `(lambda ,field-names
340 (make-struct ',rtd 0 ,@(map (lambda (f)
341 (if (memq f field-names)
342 f
343 #f))
344 (record-type-fields rtd)))))))
345
346(define (record-predicate rtd)
347 (lambda (obj) (and (struct? obj) (eq? rtd (struct-vtable obj)))))
348
349(define (record-accessor rtd field-name)
350 (let* ((pos (list-index (record-type-fields rtd) field-name)))
351 (if (not pos)
352 (error 'no-such-field field-name))
353 (eval `(lambda (obj)
354 (and (eq? ',rtd (record-type-descriptor obj))
355 (struct-ref obj ,pos))))))
356
357(define (record-modifier rtd field-name)
358 (let* ((pos (list-index (record-type-fields rtd) field-name)))
359 (if (not pos)
360 (error 'no-such-field field-name))
361 (eval `(lambda (obj val)
362 (and (eq? ',rtd (record-type-descriptor obj))
363 (struct-set! obj ,pos val))))))
364
365
366(define (record? obj)
367 (and (struct? obj) (record-type? (struct-vtable obj))))
368
369(define (record-type-descriptor obj)
370 (if (struct? obj)
371 (struct-vtable obj)
372 (error 'not-a-record obj)))
373
21ed9efe
MD
374(provide 'record)
375
0f2d19dd
JB
376\f
377;;; {Booleans}
378;;;
379
380(define (->bool x) (not (not x)))
381
382\f
383;;; {Symbols}
384;;;
385
386(define (symbol-append . args)
387 (string->symbol (apply string-append args)))
388
389(define (list->symbol . args)
390 (string->symbol (apply list->string args)))
391
392(define (symbol . args)
393 (string->symbol (apply string args)))
394
395(define (obarray-symbol-append ob . args)
396 (string->obarray-symbol (apply string-append ob args)))
397
398(define obarray-gensym
399 (let ((n -1))
400 (lambda (obarray . opt)
401 (if (null? opt)
402 (set! opt '(%%gensym)))
403 (let loop ((proposed-name (apply string-append opt)))
404 (if (string->obarray-symbol obarray proposed-name #t)
405 (loop (apply string-append (append opt (begin (set! n (1+ n)) (list (number->string n))))))
406 (string->obarray-symbol obarray proposed-name))))))
407
408(define (gensym . args) (apply obarray-gensym #f args))
409
410\f
411;;; {Lists}
412;;;
413
414(define (list-index l k)
415 (let loop ((n 0)
416 (l l))
417 (and (not (null? l))
418 (if (eq? (car l) k)
419 n
420 (loop (+ n 1) (cdr l))))))
421
422(define (make-list n init)
423 (let loop ((answer '())
424 (n n))
425 (if (<= n 0)
426 answer
427 (loop (cons init answer) (- n 1)))))
428
429
430\f
431;;; {and-map, or-map, and map-in-order}
432;;;
433;;; (and-map fn lst) is like (and (fn (car lst)) (fn (cadr lst)) (fn...) ...)
434;;; (or-map fn lst) is like (or (fn (car lst)) (fn (cadr lst)) (fn...) ...)
435;;; (map-in-order fn lst) is like (map fn lst) but definately in order of lst.
436;;;
437
438;; and-map f l
439;;
440;; Apply f to successive elements of l until exhaustion or f returns #f.
441;; If returning early, return #f. Otherwise, return the last value returned
442;; by f. If f has never been called because l is empty, return #t.
443;;
444(define (and-map f lst)
445 (let loop ((result #t)
446 (l lst))
447 (and result
448 (or (and (null? l)
449 result)
450 (loop (f (car l)) (cdr l))))))
451
452;; or-map f l
453;;
454;; Apply f to successive elements of l until exhaustion or while f returns #f.
455;; If returning early, return the return value of f.
456;;
457(define (or-map f lst)
458 (let loop ((result #f)
459 (l lst))
460 (or result
461 (and (not (null? l))
462 (loop (f (car l)) (cdr l))))))
463
464;; map-in-order
465;;
466;; Like map, but guaranteed to process the list in order.
467;;
468(define (map-in-order fn l)
469 (if (null? l)
470 '()
471 (cons (fn (car l))
472 (map-in-order fn (cdr l)))))
473
474\f
59e1116d
MD
475;;; {Hooks}
476(define (run-hooks hook)
477 (for-each (lambda (thunk) (thunk)) hook))
478
479(define add-hook!
480 (procedure->macro
481 (lambda (exp env)
482 `(let ((thunk ,(caddr exp)))
483 (if (not (memq thunk ,(cadr exp)))
484 (set! ,(cadr exp)
485 (cons thunk ,(cadr exp))))))))
486
487\f
0f2d19dd
JB
488;;; {Files}
489;;; !!!! these should be implemented using Tcl commands, not fports.
490;;;
491
6fa8995c
GH
492(define (feature? feature)
493 (and (memq feature *features*) #t))
494
3afb28ce
GH
495;; Using the vector returned by stat directly is probably not a good
496;; idea (it could just as well be a record). Hence some accessors.
497(define (stat:dev f) (vector-ref f 0))
498(define (stat:ino f) (vector-ref f 1))
499(define (stat:mode f) (vector-ref f 2))
500(define (stat:nlink f) (vector-ref f 3))
501(define (stat:uid f) (vector-ref f 4))
502(define (stat:gid f) (vector-ref f 5))
503(define (stat:rdev f) (vector-ref f 6))
504(define (stat:size f) (vector-ref f 7))
505(define (stat:atime f) (vector-ref f 8))
506(define (stat:mtime f) (vector-ref f 9))
507(define (stat:ctime f) (vector-ref f 10))
508(define (stat:blksize f) (vector-ref f 11))
509(define (stat:blocks f) (vector-ref f 12))
510
511;; derived from stat mode.
512(define (stat:type f) (vector-ref f 13))
513(define (stat:perms f) (vector-ref f 14))
514
6fa8995c
GH
515(define file-exists?
516 (if (feature? 'posix)
517 (lambda (str)
518 (access? str F_OK))
519 (lambda (str)
520 (let ((port (catch 'system-error (lambda () (open-file str OPEN_READ))
521 (lambda args #f))))
522 (if port (begin (close-port port) #t)
523 #f)))))
524
525(define file-is-directory?
526 (if (feature? 'i/o-extensions)
527 (lambda (str)
3afb28ce 528 (eq? (stat:type (stat str)) 'directory))
6fa8995c
GH
529 (lambda (str)
530 (display str)
531 (newline)
532 (let ((port (catch 'system-error
533 (lambda () (open-file (string-append str "/.")
534 OPEN_READ))
535 (lambda args #f))))
536 (if port (begin (close-port port) #t)
537 #f)))))
0f2d19dd
JB
538
539(define (has-suffix? str suffix)
540 (let ((sufl (string-length suffix))
541 (sl (string-length str)))
542 (and (> sl sufl)
543 (string=? (substring str (- sl sufl) sl) suffix))))
544
0f2d19dd
JB
545\f
546;;; {Error Handling}
547;;;
548
0f2d19dd 549(define (error . args)
21ed9efe 550 (save-stack)
2194b6f0 551 (if (null? args)
5552355a 552 (scm-error 'misc-error #f "?" #f #f)
2194b6f0
GH
553 (let loop ((msg "%s")
554 (rest (cdr args)))
555 (if (not (null? rest))
556 (loop (string-append msg " %S")
557 (cdr rest))
5552355a 558 (scm-error 'misc-error #f msg args #f)))))
be2d2c70 559
1349bd53 560;; bad-throw is the hook that is called upon a throw to a an unhandled
9a0d70e2
GH
561;; key (unless the throw has four arguments, in which case
562;; it's usually interpreted as an error throw.)
563;; If the key has a default handler (a throw-handler-default property),
0f2d19dd
JB
564;; it is applied to the throw.
565;;
1349bd53 566(define (bad-throw key . args)
0f2d19dd
JB
567 (let ((default (symbol-property key 'throw-handler-default)))
568 (or (and default (apply default key args))
2194b6f0 569 (apply error "unhandled-exception:" key args))))
0f2d19dd 570
0f2d19dd 571\f
44cf1f0f
JB
572;;; {Non-polymorphic versions of POSIX functions}
573
02b754d3
GH
574(define (getgrnam name) (getgr name))
575(define (getgrgid id) (getgr id))
576(define (gethostbyaddr addr) (gethost addr))
577(define (gethostbyname name) (gethost name))
578(define (getnetbyaddr addr) (getnet addr))
579(define (getnetbyname name) (getnet name))
580(define (getprotobyname name) (getproto name))
581(define (getprotobynumber addr) (getproto addr))
582(define (getpwnam name) (getpw name))
583(define (getpwuid uid) (getpw uid))
920235cc
GH
584(define (getservbyname name proto) (getserv name proto))
585(define (getservbyport port proto) (getserv port proto))
0f2d19dd
JB
586(define (endgrent) (setgr))
587(define (endhostent) (sethost))
588(define (endnetent) (setnet))
589(define (endprotoent) (setproto))
590(define (endpwent) (setpw))
591(define (endservent) (setserv))
02b754d3
GH
592(define (getgrent) (getgr))
593(define (gethostent) (gethost))
594(define (getnetent) (getnet))
595(define (getprotoent) (getproto))
596(define (getpwent) (getpw))
597(define (getservent) (getserv))
0f2d19dd 598(define (reopen-file . args) (apply freopen args))
bce074ee
GH
599(define (setgrent) (setgr #f))
600(define (sethostent) (sethost #t))
601(define (setnetent) (setnet #t))
602(define (setprotoent) (setproto #t))
603(define (setpwent) (setpw #t))
604(define (setservent) (setserv #t))
605
606(define (passwd:name obj) (vector-ref obj 0))
607(define (passwd:passwd obj) (vector-ref obj 1))
608(define (passwd:uid obj) (vector-ref obj 2))
609(define (passwd:gid obj) (vector-ref obj 3))
610(define (passwd:gecos obj) (vector-ref obj 4))
611(define (passwd:dir obj) (vector-ref obj 5))
612(define (passwd:shell obj) (vector-ref obj 6))
613
614(define (group:name obj) (vector-ref obj 0))
615(define (group:passwd obj) (vector-ref obj 1))
616(define (group:gid obj) (vector-ref obj 2))
617(define (group:mem obj) (vector-ref obj 3))
618
619(define (hostent:name obj) (vector-ref obj 0))
620(define (hostent:aliases obj) (vector-ref obj 1))
621(define (hostent:addrtype obj) (vector-ref obj 2))
622(define (hostent:length obj) (vector-ref obj 3))
623(define (hostent:addr-list obj) (vector-ref obj 4))
624
625(define (netent:name obj) (vector-ref obj 0))
626(define (netent:aliases obj) (vector-ref obj 1))
9337637f
GH
627(define (netent:addrtype obj) (vector-ref obj 2))
628(define (netent:net obj) (vector-ref obj 3))
bce074ee
GH
629
630(define (protoent:name obj) (vector-ref obj 0))
631(define (protoent:aliases obj) (vector-ref obj 1))
632(define (protoent:proto obj) (vector-ref obj 2))
633
634(define (servent:name obj) (vector-ref obj 0))
635(define (servent:aliases obj) (vector-ref obj 1))
9337637f
GH
636(define (servent:port obj) (vector-ref obj 2))
637(define (servent:proto obj) (vector-ref obj 3))
638
639(define (sockaddr:fam obj) (vector-ref obj 0))
640(define (sockaddr:path obj) (vector-ref obj 1))
641(define (sockaddr:addr obj) (vector-ref obj 1))
642(define (sockaddr:port obj) (vector-ref obj 2))
643
644(define (utsname:sysname obj) (vector-ref obj 0))
645(define (utsname:nodename obj) (vector-ref obj 1))
646(define (utsname:release obj) (vector-ref obj 2))
647(define (utsname:version obj) (vector-ref obj 3))
648(define (utsname:machine obj) (vector-ref obj 4))
bce074ee 649
708bf0f3
GH
650(define (tm:sec obj) (vector-ref obj 0))
651(define (tm:min obj) (vector-ref obj 1))
652(define (tm:hour obj) (vector-ref obj 2))
653(define (tm:mday obj) (vector-ref obj 3))
654(define (tm:mon obj) (vector-ref obj 4))
655(define (tm:year obj) (vector-ref obj 5))
656(define (tm:wday obj) (vector-ref obj 6))
657(define (tm:yday obj) (vector-ref obj 7))
658(define (tm:isdst obj) (vector-ref obj 8))
659(define (tm:gmtoff obj) (vector-ref obj 9))
660(define (tm:zone obj) (vector-ref obj 10))
661
662(define (set-tm:sec obj val) (vector-set! obj 0 val))
663(define (set-tm:min obj val) (vector-set! obj 1 val))
664(define (set-tm:hour obj val) (vector-set! obj 2 val))
665(define (set-tm:mday obj val) (vector-set! obj 3 val))
666(define (set-tm:mon obj val) (vector-set! obj 4 val))
667(define (set-tm:year obj val) (vector-set! obj 5 val))
668(define (set-tm:wday obj val) (vector-set! obj 6 val))
669(define (set-tm:yday obj val) (vector-set! obj 7 val))
670(define (set-tm:isdst obj val) (vector-set! obj 8 val))
671(define (set-tm:gmtoff obj val) (vector-set! obj 9 val))
672(define (set-tm:zone obj val) (vector-set! obj 10 val))
673
bce074ee
GH
674(define (file-position . args) (apply ftell args))
675(define (file-set-position . args) (apply fseek args))
8b13c6b3 676
708bf0f3
GH
677(define (open-input-pipe command) (open-pipe command OPEN_READ))
678(define (open-output-pipe command) (open-pipe command OPEN_WRITE))
679
02b754d3 680(define (move->fdes port fd)
8b13c6b3
GH
681 (primitive-move->fdes port fd)
682 (set-port-revealed! port 1)
683 port)
684
685(define (release-port-handle port)
686 (let ((revealed (port-revealed port)))
687 (if (> revealed 0)
688 (set-port-revealed! port (- revealed 1)))))
0f2d19dd
JB
689
690\f
691;;; {Load Paths}
692;;;
693
0f2d19dd
JB
694;;; Here for backward compatability
695;;
696(define scheme-file-suffix (lambda () ".scm"))
697
3cab8392
JB
698(define (in-vicinity vicinity file)
699 (let ((tail (let ((len (string-length vicinity)))
700 (if (zero? len) #f
701 (string-ref vicinity (- len 1))))))
702 (string-append vicinity
703 (if (eq? tail #\/) "" "/")
704 file)))
02ceadb8 705
0f2d19dd 706\f
ef00e7f4
JB
707;;; {Help for scm_shell}
708;;; The argument-processing code used by Guile-based shells generates
709;;; Scheme code based on the argument list. This page contains help
710;;; functions for the code it generates.
711
ef00e7f4
JB
712(define (command-line) (program-arguments))
713
5aa7fe69
JB
714;; This is mostly for the internal use of the code generated by
715;; scm_compile_shell_switches.
ef00e7f4
JB
716(define (load-user-init)
717 (define (has-init? dir)
718 (let ((path (in-vicinity dir ".guile")))
719 (catch 'system-error
720 (lambda ()
721 (let ((stats (stat path)))
722 (if (not (eq? (stat:type stats) 'directory))
723 path)))
724 (lambda dummy #f))))
725 (let ((path (or (has-init? (getenv "HOME"))
726 (has-init? (passwd:dir (getpw (getuid)))))))
727 (if path (primitive-load path))))
728
729\f
a06181a2
JB
730;;; {Loading by paths}
731
732;;; Load a Scheme source file named NAME, searching for it in the
733;;; directories listed in %load-path, and applying each of the file
734;;; name extensions listed in %load-extensions.
735(define (load-from-path name)
736 (start-stack 'load-stack
75a97b92 737 (primitive-load-path name)))
0f2d19dd 738
5552355a 739
0f2d19dd 740\f
0f2d19dd
JB
741;;; {Transcendental Functions}
742;;;
743;;; Derived from "Transcen.scm", Complex trancendental functions for SCM.
744;;; Copyright (C) 1992, 1993 Jerry D. Hedden.
745;;; See the file `COPYING' for terms applying to this program.
746;;;
747
748(define (exp z)
749 (if (real? z) ($exp z)
750 (make-polar ($exp (real-part z)) (imag-part z))))
751
752(define (log z)
753 (if (and (real? z) (>= z 0))
754 ($log z)
755 (make-rectangular ($log (magnitude z)) (angle z))))
756
757(define (sqrt z)
758 (if (real? z)
759 (if (negative? z) (make-rectangular 0 ($sqrt (- z)))
760 ($sqrt z))
761 (make-polar ($sqrt (magnitude z)) (/ (angle z) 2))))
762
763(define expt
764 (let ((integer-expt integer-expt))
765 (lambda (z1 z2)
766 (cond ((exact? z2)
767 (integer-expt z1 z2))
768 ((and (real? z2) (real? z1) (>= z1 0))
769 ($expt z1 z2))
770 (else
771 (exp (* z2 (log z1))))))))
772
773(define (sinh z)
774 (if (real? z) ($sinh z)
775 (let ((x (real-part z)) (y (imag-part z)))
776 (make-rectangular (* ($sinh x) ($cos y))
777 (* ($cosh x) ($sin y))))))
778(define (cosh z)
779 (if (real? z) ($cosh z)
780 (let ((x (real-part z)) (y (imag-part z)))
781 (make-rectangular (* ($cosh x) ($cos y))
782 (* ($sinh x) ($sin y))))))
783(define (tanh z)
784 (if (real? z) ($tanh z)
785 (let* ((x (* 2 (real-part z)))
786 (y (* 2 (imag-part z)))
787 (w (+ ($cosh x) ($cos y))))
788 (make-rectangular (/ ($sinh x) w) (/ ($sin y) w)))))
789
790(define (asinh z)
791 (if (real? z) ($asinh z)
792 (log (+ z (sqrt (+ (* z z) 1))))))
793
794(define (acosh z)
795 (if (and (real? z) (>= z 1))
796 ($acosh z)
797 (log (+ z (sqrt (- (* z z) 1))))))
798
799(define (atanh z)
800 (if (and (real? z) (> z -1) (< z 1))
801 ($atanh z)
802 (/ (log (/ (+ 1 z) (- 1 z))) 2)))
803
804(define (sin z)
805 (if (real? z) ($sin z)
806 (let ((x (real-part z)) (y (imag-part z)))
807 (make-rectangular (* ($sin x) ($cosh y))
808 (* ($cos x) ($sinh y))))))
809(define (cos z)
810 (if (real? z) ($cos z)
811 (let ((x (real-part z)) (y (imag-part z)))
812 (make-rectangular (* ($cos x) ($cosh y))
813 (- (* ($sin x) ($sinh y)))))))
814(define (tan z)
815 (if (real? z) ($tan z)
816 (let* ((x (* 2 (real-part z)))
817 (y (* 2 (imag-part z)))
818 (w (+ ($cos x) ($cosh y))))
819 (make-rectangular (/ ($sin x) w) (/ ($sinh y) w)))))
820
821(define (asin z)
822 (if (and (real? z) (>= z -1) (<= z 1))
823 ($asin z)
824 (* -i (asinh (* +i z)))))
825
826(define (acos z)
827 (if (and (real? z) (>= z -1) (<= z 1))
828 ($acos z)
829 (+ (/ (angle -1) 2) (* +i (asinh (* +i z))))))
830
831(define (atan z . y)
832 (if (null? y)
833 (if (real? z) ($atan z)
834 (/ (log (/ (- +i z) (+ +i z))) +2i))
835 ($atan2 z (car y))))
836
837(set! abs magnitude)
838
65495221
GH
839(define (log10 arg)
840 (/ (log arg) (log 10)))
841
0f2d19dd 842\f
0f2d19dd
JB
843
844;;; {Reader Extensions}
845;;;
846
847;;; Reader code for various "#c" forms.
848;;;
849
850(define (parse-path-symbol s)
21ed9efe 851 (define (separate-fields-discarding-char ch str ret)
0f2d19dd
JB
852 (let loop ((fields '())
853 (str str))
854 (cond
855 ((string-rindex str ch)
856 => (lambda (pos) (loop (cons (make-shared-substring str (+ 1 pos)) fields)
857 (make-shared-substring str 0 pos))))
858 (else (ret (cons str fields))))))
21ed9efe 859 (separate-fields-discarding-char #\/
0f2d19dd
JB
860 s
861 (lambda (fields)
862 (map string->symbol fields))))
863
864
75a97b92
GH
865(read-hash-extend #\' (lambda (c port)
866 (read port)))
867(read-hash-extend #\. (lambda (c port)
868 (eval (read port))))
869
870(if (feature? 'array)
871 (begin
872 (let ((make-array-proc (lambda (template)
873 (lambda (c port)
874 (read:uniform-vector template port)))))
875 (for-each (lambda (char template)
876 (read-hash-extend char
877 (make-array-proc template)))
878 '(#\b #\a #\u #\e #\s #\i #\c)
879 '(#t #\a 1 -1 1.0 1/3 0+i)))
880 (let ((array-proc (lambda (c port)
881 (read:array c port))))
882 (for-each (lambda (char) (read-hash-extend char array-proc))
883 '(#\0 #\1 #\2 #\3 #\4 #\5 #\6 #\7 #\8 #\9)))))
884
00c34e45
GH
885;; pushed to the beginning of the alist since it's used more than the
886;; others at present.
887(read-hash-extend #\/
888 (lambda (c port)
889 (let ((look (peek-char port)))
890 (if (or (eof-object? look)
891 (and (char? look)
892 (or (char-whitespace? look)
893 (string-index ")" look))))
894 '()
895 (parse-path-symbol (read port))))))
896
0f2d19dd
JB
897(define (read:array digit port)
898 (define chr0 (char->integer #\0))
899 (let ((rank (let readnum ((val (- (char->integer digit) chr0)))
900 (if (char-numeric? (peek-char port))
901 (readnum (+ (* 10 val)
902 (- (char->integer (read-char port)) chr0)))
903 val)))
904 (prot (if (eq? #\( (peek-char port))
905 '()
906 (let ((c (read-char port)))
907 (case c ((#\b) #t)
908 ((#\a) #\a)
909 ((#\u) 1)
910 ((#\e) -1)
911 ((#\s) 1.0)
912 ((#\i) 1/3)
913 ((#\c) 0+i)
914 (else (error "read:array unknown option " c)))))))
915 (if (eq? (peek-char port) #\()
75a97b92 916 (list->uniform-array rank prot (read port))
0f2d19dd
JB
917 (error "read:array list not found"))))
918
919(define (read:uniform-vector proto port)
920 (if (eq? #\( (peek-char port))
75a97b92 921 (list->uniform-array 1 proto (read port))
0f2d19dd
JB
922 (error "read:uniform-vector list not found")))
923
0f2d19dd
JB
924\f
925;;; {Command Line Options}
926;;;
927
928(define (get-option argv kw-opts kw-args return)
929 (cond
930 ((null? argv)
931 (return #f #f argv))
932
933 ((or (not (eq? #\- (string-ref (car argv) 0)))
934 (eq? (string-length (car argv)) 1))
935 (return 'normal-arg (car argv) (cdr argv)))
936
937 ((eq? #\- (string-ref (car argv) 1))
938 (let* ((kw-arg-pos (or (string-index (car argv) #\=)
939 (string-length (car argv))))
940 (kw (symbol->keyword (substring (car argv) 2 kw-arg-pos)))
941 (kw-opt? (member kw kw-opts))
942 (kw-arg? (member kw kw-args))
943 (arg (or (and (not (eq? kw-arg-pos (string-length (car argv))))
944 (substring (car argv)
945 (+ kw-arg-pos 1)
946 (string-length (car argv))))
947 (and kw-arg?
948 (begin (set! argv (cdr argv)) (car argv))))))
949 (if (or kw-opt? kw-arg?)
950 (return kw arg (cdr argv))
951 (return 'usage-error kw (cdr argv)))))
952
953 (else
954 (let* ((char (substring (car argv) 1 2))
955 (kw (symbol->keyword char)))
956 (cond
957
958 ((member kw kw-opts)
959 (let* ((rest-car (substring (car argv) 2 (string-length (car argv))))
960 (new-argv (if (= 0 (string-length rest-car))
961 (cdr argv)
962 (cons (string-append "-" rest-car) (cdr argv)))))
963 (return kw #f new-argv)))
964
965 ((member kw kw-args)
966 (let* ((rest-car (substring (car argv) 2 (string-length (car argv))))
967 (arg (if (= 0 (string-length rest-car))
968 (cadr argv)
969 rest-car))
970 (new-argv (if (= 0 (string-length rest-car))
971 (cddr argv)
972 (cdr argv))))
973 (return kw arg new-argv)))
974
975 (else (return 'usage-error kw argv)))))))
976
977(define (for-next-option proc argv kw-opts kw-args)
978 (let loop ((argv argv))
979 (get-option argv kw-opts kw-args
980 (lambda (opt opt-arg argv)
981 (and opt (proc opt opt-arg argv loop))))))
982
983(define (display-usage-report kw-desc)
984 (for-each
985 (lambda (kw)
986 (or (eq? (car kw) #t)
987 (eq? (car kw) 'else)
988 (let* ((opt-desc kw)
989 (help (cadr opt-desc))
990 (opts (car opt-desc))
991 (opts-proper (if (string? (car opts)) (cdr opts) opts))
992 (arg-name (if (string? (car opts))
993 (string-append "<" (car opts) ">")
994 ""))
995 (left-part (string-append
996 (with-output-to-string
997 (lambda ()
998 (map (lambda (x) (display (keyword-symbol x)) (display " "))
999 opts-proper)))
1000 arg-name))
1001 (middle-part (if (and (< (length left-part) 30)
1002 (< (length help) 40))
1003 (make-string (- 30 (length left-part)) #\ )
1004 "\n\t")))
1005 (display left-part)
1006 (display middle-part)
1007 (display help)
1008 (newline))))
1009 kw-desc))
1010
1011
1012
0f2d19dd
JB
1013(define (transform-usage-lambda cases)
1014 (let* ((raw-usage (delq! 'else (map car cases)))
1015 (usage-sans-specials (map (lambda (x)
1016 (or (and (not (list? x)) x)
1017 (and (symbol? (car x)) #t)
1018 (and (boolean? (car x)) #t)
1019 x))
1020 raw-usage))
ed440df5 1021 (usage-desc (delq! #t usage-sans-specials))
0f2d19dd
JB
1022 (kw-desc (map car usage-desc))
1023 (kw-opts (apply append (map (lambda (x) (and (not (string? (car x))) x)) kw-desc)))
1024 (kw-args (apply append (map (lambda (x) (and (string? (car x)) (cdr x))) kw-desc)))
1025 (transmogrified-cases (map (lambda (case)
1026 (cons (let ((opts (car case)))
1027 (if (or (boolean? opts) (eq? 'else opts))
1028 opts
1029 (cond
1030 ((symbol? (car opts)) opts)
1031 ((boolean? (car opts)) opts)
1032 ((string? (caar opts)) (cdar opts))
1033 (else (car opts)))))
1034 (cdr case)))
1035 cases)))
1036 `(let ((%display-usage (lambda () (display-usage-report ',usage-desc))))
1037 (lambda (%argv)
1038 (let %next-arg ((%argv %argv))
1039 (get-option %argv
1040 ',kw-opts
1041 ',kw-args
1042 (lambda (%opt %arg %new-argv)
1043 (case %opt
1044 ,@ transmogrified-cases))))))))
1045
1046
1047\f
1048
1049;;; {Low Level Modules}
1050;;;
1051;;; These are the low level data structures for modules.
1052;;;
1053;;; !!! warning: The interface to lazy binder procedures is going
1054;;; to be changed in an incompatible way to permit all the basic
1055;;; module ops to be virtualized.
1056;;;
1057;;; (make-module size use-list lazy-binding-proc) => module
1058;;; module-{obarray,uses,binder}[|-set!]
1059;;; (module? obj) => [#t|#f]
1060;;; (module-locally-bound? module symbol) => [#t|#f]
1061;;; (module-bound? module symbol) => [#t|#f]
1062;;; (module-symbol-locally-interned? module symbol) => [#t|#f]
1063;;; (module-symbol-interned? module symbol) => [#t|#f]
1064;;; (module-local-variable module symbol) => [#<variable ...> | #f]
1065;;; (module-variable module symbol) => [#<variable ...> | #f]
1066;;; (module-symbol-binding module symbol opt-value)
1067;;; => [ <obj> | opt-value | an error occurs ]
1068;;; (module-make-local-var! module symbol) => #<variable...>
1069;;; (module-add! module symbol var) => unspecified
1070;;; (module-remove! module symbol) => unspecified
1071;;; (module-for-each proc module) => unspecified
1072;;; (make-scm-module) => module ; a lazy copy of the symhash module
1073;;; (set-current-module module) => unspecified
1074;;; (current-module) => #<module...>
1075;;;
1076;;;
1077
1078\f
44cf1f0f
JB
1079;;; {Printing Modules}
1080;; This is how modules are printed. You can re-define it.
0f2d19dd
JB
1081;;
1082(define (%print-module mod port depth length style table)
1083 (display "#<" port)
1084 (display (or (module-kind mod) "module") port)
1085 (let ((name (module-name mod)))
1086 (if name
1087 (begin
1088 (display " " port)
1089 (display name port))))
1090 (display " " port)
1091 (display (number->string (object-address mod) 16) port)
1092 (display ">" port))
1093
1094;; module-type
1095;;
1096;; A module is characterized by an obarray in which local symbols
1097;; are interned, a list of modules, "uses", from which non-local
1098;; bindings can be inherited, and an optional lazy-binder which
31d50456 1099;; is a (CLOSURE module symbol) which, as a last resort, can provide
0f2d19dd
JB
1100;; bindings that would otherwise not be found locally in the module.
1101;;
1102(define module-type
31d50456 1103 (make-record-type 'module '(obarray uses binder eval-closure name kind)
8b718458 1104 %print-module))
0f2d19dd 1105
8b718458 1106;; make-module &opt size uses binder
0f2d19dd 1107;;
8b718458
JB
1108;; Create a new module, perhaps with a particular size of obarray,
1109;; initial uses list, or binding procedure.
0f2d19dd 1110;;
0f2d19dd
JB
1111(define make-module
1112 (lambda args
0f2d19dd 1113
8b718458
JB
1114 (define (parse-arg index default)
1115 (if (> (length args) index)
1116 (list-ref args index)
1117 default))
1118
1119 (if (> (length args) 3)
1120 (error "Too many args to make-module." args))
0f2d19dd 1121
8b718458
JB
1122 (let ((size (parse-arg 0 1021))
1123 (uses (parse-arg 1 '()))
1124 (binder (parse-arg 2 #f)))
0f2d19dd 1125
8b718458
JB
1126 (if (not (integer? size))
1127 (error "Illegal size to make-module." size))
1128 (if (not (and (list? uses)
1129 (and-map module? uses)))
1130 (error "Incorrect use list." uses))
0f2d19dd
JB
1131 (if (and binder (not (procedure? binder)))
1132 (error
1133 "Lazy-binder expected to be a procedure or #f." binder))
1134
8b718458
JB
1135 (let ((module (module-constructor (make-vector size '())
1136 uses binder #f #f #f)))
1137
1138 ;; We can't pass this as an argument to module-constructor,
1139 ;; because we need it to close over a pointer to the module
1140 ;; itself.
31d50456 1141 (set-module-eval-closure! module
8b718458
JB
1142 (lambda (symbol define?)
1143 (if define?
1144 (module-make-local-var! module symbol)
1145 (module-variable module symbol))))
1146
1147 module))))
0f2d19dd 1148
8b718458 1149(define module-constructor (record-constructor module-type))
0f2d19dd
JB
1150(define module-obarray (record-accessor module-type 'obarray))
1151(define set-module-obarray! (record-modifier module-type 'obarray))
1152(define module-uses (record-accessor module-type 'uses))
1153(define set-module-uses! (record-modifier module-type 'uses))
1154(define module-binder (record-accessor module-type 'binder))
1155(define set-module-binder! (record-modifier module-type 'binder))
31d50456
JB
1156(define module-eval-closure (record-accessor module-type 'eval-closure))
1157(define set-module-eval-closure! (record-modifier module-type 'eval-closure))
0f2d19dd
JB
1158(define module-name (record-accessor module-type 'name))
1159(define set-module-name! (record-modifier module-type 'name))
1160(define module-kind (record-accessor module-type 'kind))
1161(define set-module-kind! (record-modifier module-type 'kind))
1162(define module? (record-predicate module-type))
1163
8b718458 1164
0f2d19dd 1165(define (eval-in-module exp module)
31d50456 1166 (eval2 exp (module-eval-closure module)))
0f2d19dd
JB
1167
1168\f
1169;;; {Module Searching in General}
1170;;;
1171;;; We sometimes want to look for properties of a symbol
1172;;; just within the obarray of one module. If the property
1173;;; holds, then it is said to hold ``locally'' as in, ``The symbol
1174;;; DISPLAY is locally rebound in the module `safe-guile'.''
1175;;;
1176;;;
1177;;; Other times, we want to test for a symbol property in the obarray
1178;;; of M and, if it is not found there, try each of the modules in the
1179;;; uses list of M. This is the normal way of testing for some
1180;;; property, so we state these properties without qualification as
1181;;; in: ``The symbol 'fnord is interned in module M because it is
1182;;; interned locally in module M2 which is a member of the uses list
1183;;; of M.''
1184;;;
1185
1186;; module-search fn m
1187;;
1188;; return the first non-#f result of FN applied to M and then to
1189;; the modules in the uses of m, and so on recursively. If all applications
1190;; return #f, then so does this function.
1191;;
1192(define (module-search fn m v)
1193 (define (loop pos)
1194 (and (pair? pos)
1195 (or (module-search fn (car pos) v)
1196 (loop (cdr pos)))))
1197 (or (fn m v)
1198 (loop (module-uses m))))
1199
1200
1201;;; {Is a symbol bound in a module?}
1202;;;
1203;;; Symbol S in Module M is bound if S is interned in M and if the binding
1204;;; of S in M has been set to some well-defined value.
1205;;;
1206
1207;; module-locally-bound? module symbol
1208;;
1209;; Is a symbol bound (interned and defined) locally in a given module?
1210;;
1211(define (module-locally-bound? m v)
1212 (let ((var (module-local-variable m v)))
1213 (and var
1214 (variable-bound? var))))
1215
1216;; module-bound? module symbol
1217;;
1218;; Is a symbol bound (interned and defined) anywhere in a given module
1219;; or its uses?
1220;;
1221(define (module-bound? m v)
1222 (module-search module-locally-bound? m v))
1223
1224;;; {Is a symbol interned in a module?}
1225;;;
1226;;; Symbol S in Module M is interned if S occurs in
1227;;; of S in M has been set to some well-defined value.
1228;;;
1229;;; It is possible to intern a symbol in a module without providing
1230;;; an initial binding for the corresponding variable. This is done
1231;;; with:
1232;;; (module-add! module symbol (make-undefined-variable))
1233;;;
1234;;; In that case, the symbol is interned in the module, but not
1235;;; bound there. The unbound symbol shadows any binding for that
1236;;; symbol that might otherwise be inherited from a member of the uses list.
1237;;;
1238
1239(define (module-obarray-get-handle ob key)
1240 ((if (symbol? key) hashq-get-handle hash-get-handle) ob key))
1241
1242(define (module-obarray-ref ob key)
1243 ((if (symbol? key) hashq-ref hash-ref) ob key))
1244
1245(define (module-obarray-set! ob key val)
1246 ((if (symbol? key) hashq-set! hash-set!) ob key val))
1247
1248(define (module-obarray-remove! ob key)
1249 ((if (symbol? key) hashq-remove! hash-remove!) ob key))
1250
1251;; module-symbol-locally-interned? module symbol
1252;;
1253;; is a symbol interned (not neccessarily defined) locally in a given module
1254;; or its uses? Interned symbols shadow inherited bindings even if
1255;; they are not themselves bound to a defined value.
1256;;
1257(define (module-symbol-locally-interned? m v)
1258 (not (not (module-obarray-get-handle (module-obarray m) v))))
1259
1260;; module-symbol-interned? module symbol
1261;;
1262;; is a symbol interned (not neccessarily defined) anywhere in a given module
1263;; or its uses? Interned symbols shadow inherited bindings even if
1264;; they are not themselves bound to a defined value.
1265;;
1266(define (module-symbol-interned? m v)
1267 (module-search module-symbol-locally-interned? m v))
1268
1269
1270;;; {Mapping modules x symbols --> variables}
1271;;;
1272
1273;; module-local-variable module symbol
1274;; return the local variable associated with a MODULE and SYMBOL.
1275;;
1276;;; This function is very important. It is the only function that can
1277;;; return a variable from a module other than the mutators that store
1278;;; new variables in modules. Therefore, this function is the location
1279;;; of the "lazy binder" hack.
1280;;;
1281;;; If symbol is defined in MODULE, and if the definition binds symbol
1282;;; to a variable, return that variable object.
1283;;;
1284;;; If the symbols is not found at first, but the module has a lazy binder,
1285;;; then try the binder.
1286;;;
1287;;; If the symbol is not found at all, return #f.
1288;;;
1289(define (module-local-variable m v)
6fa8995c
GH
1290; (caddr
1291; (list m v
0f2d19dd
JB
1292 (let ((b (module-obarray-ref (module-obarray m) v)))
1293 (or (and (variable? b) b)
1294 (and (module-binder m)
6fa8995c
GH
1295 ((module-binder m) m v #f)))))
1296;))
0f2d19dd
JB
1297
1298;; module-variable module symbol
1299;;
1300;; like module-local-variable, except search the uses in the
1301;; case V is not found in M.
1302;;
1303(define (module-variable m v)
1304 (module-search module-local-variable m v))
1305
1306
1307;;; {Mapping modules x symbols --> bindings}
1308;;;
1309;;; These are similar to the mapping to variables, except that the
1310;;; variable is dereferenced.
1311;;;
1312
1313;; module-symbol-binding module symbol opt-value
1314;;
1315;; return the binding of a variable specified by name within
1316;; a given module, signalling an error if the variable is unbound.
1317;; If the OPT-VALUE is passed, then instead of signalling an error,
1318;; return OPT-VALUE.
1319;;
1320(define (module-symbol-local-binding m v . opt-val)
1321 (let ((var (module-local-variable m v)))
1322 (if var
1323 (variable-ref var)
1324 (if (not (null? opt-val))
1325 (car opt-val)
1326 (error "Locally unbound variable." v)))))
1327
1328;; module-symbol-binding module symbol opt-value
1329;;
1330;; return the binding of a variable specified by name within
1331;; a given module, signalling an error if the variable is unbound.
1332;; If the OPT-VALUE is passed, then instead of signalling an error,
1333;; return OPT-VALUE.
1334;;
1335(define (module-symbol-binding m v . opt-val)
1336 (let ((var (module-variable m v)))
1337 (if var
1338 (variable-ref var)
1339 (if (not (null? opt-val))
1340 (car opt-val)
1341 (error "Unbound variable." v)))))
1342
1343
1344\f
1345;;; {Adding Variables to Modules}
1346;;;
1347;;;
1348
1349
1350;; module-make-local-var! module symbol
1351;;
1352;; ensure a variable for V in the local namespace of M.
1353;; If no variable was already there, then create a new and uninitialzied
1354;; variable.
1355;;
1356(define (module-make-local-var! m v)
1357 (or (let ((b (module-obarray-ref (module-obarray m) v)))
1358 (and (variable? b) b))
1359 (and (module-binder m)
1360 ((module-binder m) m v #t))
1361 (begin
1362 (let ((answer (make-undefined-variable v)))
1363 (module-obarray-set! (module-obarray m) v answer)
1364 answer))))
1365
1366;; module-add! module symbol var
1367;;
1368;; ensure a particular variable for V in the local namespace of M.
1369;;
1370(define (module-add! m v var)
1371 (if (not (variable? var))
1372 (error "Bad variable to module-add!" var))
1373 (module-obarray-set! (module-obarray m) v var))
1374
1375;; module-remove!
1376;;
1377;; make sure that a symbol is undefined in the local namespace of M.
1378;;
1379(define (module-remove! m v)
1380 (module-obarray-remove! (module-obarray m) v))
1381
1382(define (module-clear! m)
1383 (vector-fill! (module-obarray m) '()))
1384
1385;; MODULE-FOR-EACH -- exported
1386;;
1387;; Call PROC on each symbol in MODULE, with arguments of (SYMBOL VARIABLE).
1388;;
1389(define (module-for-each proc module)
1390 (let ((obarray (module-obarray module)))
1391 (do ((index 0 (+ index 1))
1392 (end (vector-length obarray)))
1393 ((= index end))
1394 (for-each
1395 (lambda (bucket)
1396 (proc (car bucket) (cdr bucket)))
1397 (vector-ref obarray index)))))
1398
1399
1400(define (module-map proc module)
1401 (let* ((obarray (module-obarray module))
1402 (end (vector-length obarray)))
1403
1404 (let loop ((i 0)
1405 (answer '()))
1406 (if (= i end)
1407 answer
1408 (loop (+ 1 i)
1409 (append!
1410 (map (lambda (bucket)
1411 (proc (car bucket) (cdr bucket)))
1412 (vector-ref obarray i))
1413 answer))))))
1414\f
1415
1416;;; {Low Level Bootstrapping}
1417;;;
1418
1419;; make-root-module
1420
21ed9efe 1421;; A root module uses the symhash table (the system's privileged
0f2d19dd
JB
1422;; obarray). Being inside a root module is like using SCM without
1423;; any module system.
1424;;
1425
1426
31d50456 1427(define (root-module-closure m s define?)
0f2d19dd
JB
1428 (let ((bi (and (symbol-interned? #f s)
1429 (builtin-variable s))))
1430 (and bi
1431 (or define? (variable-bound? bi))
1432 (begin
1433 (module-add! m s bi)
1434 bi))))
1435
1436(define (make-root-module)
31d50456 1437 (make-module 1019 '() root-module-closure))
0f2d19dd
JB
1438
1439
1440;; make-scm-module
1441
1442;; An scm module is a module into which the lazy binder copies
1443;; variable bindings from the system symhash table. The mapping is
1444;; one way only; newly introduced bindings in an scm module are not
1445;; copied back into the system symhash table (and can be used to override
1446;; bindings from the symhash table).
1447;;
1448
1449(define (make-scm-module)
8b718458 1450 (make-module 1019 '()
0f2d19dd
JB
1451 (lambda (m s define?)
1452 (let ((bi (and (symbol-interned? #f s)
1453 (builtin-variable s))))
1454 (and bi
1455 (variable-bound? bi)
1456 (begin
1457 (module-add! m s bi)
1458 bi))))))
1459
1460
1461
1462
1463;; the-module
1464;;
1465(define the-module #f)
1466
1467;; set-current-module module
1468;;
1469;; set the current module as viewed by the normalizer.
1470;;
1471(define (set-current-module m)
1472 (set! the-module m)
1473 (if m
31d50456
JB
1474 (set! *top-level-lookup-closure* (module-eval-closure the-module))
1475 (set! *top-level-lookup-closure* #f)))
0f2d19dd
JB
1476
1477
1478;; current-module
1479;;
1480;; return the current module as viewed by the normalizer.
1481;;
1482(define (current-module) the-module)
1483\f
1484;;; {Module-based Loading}
1485;;;
1486
1487(define (save-module-excursion thunk)
1488 (let ((inner-module (current-module))
1489 (outer-module #f))
1490 (dynamic-wind (lambda ()
1491 (set! outer-module (current-module))
1492 (set-current-module inner-module)
1493 (set! inner-module #f))
1494 thunk
1495 (lambda ()
1496 (set! inner-module (current-module))
1497 (set-current-module outer-module)
1498 (set! outer-module #f)))))
1499
0f2d19dd
JB
1500(define basic-load load)
1501
0f2d19dd
JB
1502(define (load-module . args)
1503 (save-module-excursion (lambda () (apply basic-load args))))
1504
1505
1506\f
44cf1f0f 1507;;; {MODULE-REF -- exported}
0f2d19dd
JB
1508;;
1509;; Returns the value of a variable called NAME in MODULE or any of its
1510;; used modules. If there is no such variable, then if the optional third
1511;; argument DEFAULT is present, it is returned; otherwise an error is signaled.
1512;;
1513(define (module-ref module name . rest)
1514 (let ((variable (module-variable module name)))
1515 (if (and variable (variable-bound? variable))
1516 (variable-ref variable)
1517 (if (null? rest)
1518 (error "No variable named" name 'in module)
1519 (car rest) ; default value
1520 ))))
1521
1522;; MODULE-SET! -- exported
1523;;
1524;; Sets the variable called NAME in MODULE (or in a module that MODULE uses)
1525;; to VALUE; if there is no such variable, an error is signaled.
1526;;
1527(define (module-set! module name value)
1528 (let ((variable (module-variable module name)))
1529 (if variable
1530 (variable-set! variable value)
1531 (error "No variable named" name 'in module))))
1532
1533;; MODULE-DEFINE! -- exported
1534;;
1535;; Sets the variable called NAME in MODULE to VALUE; if there is no such
1536;; variable, it is added first.
1537;;
1538(define (module-define! module name value)
1539 (let ((variable (module-local-variable module name)))
1540 (if variable
1541 (variable-set! variable value)
1542 (module-add! module name (make-variable value name)))))
1543
ed218d98
MV
1544;; MODULE-DEFINED? -- exported
1545;;
1546;; Return #t iff NAME is defined in MODULE (or in a module that MODULE
1547;; uses)
1548;;
1549(define (module-defined? module name)
1550 (let ((variable (module-variable module name)))
1551 (and variable (variable-bound? variable))))
1552
0f2d19dd
JB
1553;; MODULE-USE! module interface
1554;;
1555;; Add INTERFACE to the list of interfaces used by MODULE.
1556;;
1557(define (module-use! module interface)
1558 (set-module-uses! module
1559 (cons interface (delq! interface (module-uses module)))))
1560
1561\f
0f2d19dd
JB
1562;;; {Recursive Namespaces}
1563;;;
1564;;;
1565;;; A hierarchical namespace emerges if we consider some module to be
1566;;; root, and variables bound to modules as nested namespaces.
1567;;;
1568;;; The routines in this file manage variable names in hierarchical namespace.
1569;;; Each variable name is a list of elements, looked up in successively nested
1570;;; modules.
1571;;;
0dd5491c 1572;;; (nested-ref some-root-module '(foo bar baz))
0f2d19dd
JB
1573;;; => <value of a variable named baz in the module bound to bar in
1574;;; the module bound to foo in some-root-module>
1575;;;
1576;;;
1577;;; There are:
1578;;;
1579;;; ;; a-root is a module
1580;;; ;; name is a list of symbols
1581;;;
0dd5491c
MD
1582;;; nested-ref a-root name
1583;;; nested-set! a-root name val
1584;;; nested-define! a-root name val
1585;;; nested-remove! a-root name
0f2d19dd
JB
1586;;;
1587;;;
1588;;; (current-module) is a natural choice for a-root so for convenience there are
1589;;; also:
1590;;;
0dd5491c
MD
1591;;; local-ref name == nested-ref (current-module) name
1592;;; local-set! name val == nested-set! (current-module) name val
1593;;; local-define! name val == nested-define! (current-module) name val
1594;;; local-remove! name == nested-remove! (current-module) name
0f2d19dd
JB
1595;;;
1596
1597
0dd5491c 1598(define (nested-ref root names)
0f2d19dd
JB
1599 (let loop ((cur root)
1600 (elts names))
1601 (cond
1602 ((null? elts) cur)
1603 ((not (module? cur)) #f)
1604 (else (loop (module-ref cur (car elts) #f) (cdr elts))))))
1605
0dd5491c 1606(define (nested-set! root names val)
0f2d19dd
JB
1607 (let loop ((cur root)
1608 (elts names))
1609 (if (null? (cdr elts))
1610 (module-set! cur (car elts) val)
1611 (loop (module-ref cur (car elts)) (cdr elts)))))
1612
0dd5491c 1613(define (nested-define! root names val)
0f2d19dd
JB
1614 (let loop ((cur root)
1615 (elts names))
1616 (if (null? (cdr elts))
1617 (module-define! cur (car elts) val)
1618 (loop (module-ref cur (car elts)) (cdr elts)))))
1619
0dd5491c 1620(define (nested-remove! root names)
0f2d19dd
JB
1621 (let loop ((cur root)
1622 (elts names))
1623 (if (null? (cdr elts))
1624 (module-remove! cur (car elts))
1625 (loop (module-ref cur (car elts)) (cdr elts)))))
1626
0dd5491c
MD
1627(define (local-ref names) (nested-ref (current-module) names))
1628(define (local-set! names val) (nested-set! (current-module) names val))
1629(define (local-define names val) (nested-define! (current-module) names val))
1630(define (local-remove names) (nested-remove! (current-module) names))
0f2d19dd
JB
1631
1632
1633\f
44cf1f0f 1634;;; {#/app}
0f2d19dd
JB
1635;;;
1636;;; The root of conventionally named objects not directly in the top level.
1637;;;
1638;;; #/app/modules
1639;;; #/app/modules/guile
1640;;;
1641;;; The directory of all modules and the standard root module.
1642;;;
1643
1644(define (module-public-interface m) (module-ref m '%module-public-interface #f))
1645(define (set-module-public-interface! m i) (module-define! m '%module-public-interface i))
1646(define the-root-module (make-root-module))
1647(define the-scm-module (make-scm-module))
1648(set-module-public-interface! the-root-module the-scm-module)
1649(set-module-name! the-root-module 'the-root-module)
1650(set-module-name! the-scm-module 'the-scm-module)
1651
1652(set-current-module the-root-module)
1653
1654(define app (make-module 31))
0dd5491c
MD
1655(local-define '(app modules) (make-module 31))
1656(local-define '(app modules guile) the-root-module)
0f2d19dd
JB
1657
1658;; (define-special-value '(app modules new-ws) (lambda () (make-scm-module)))
1659
0209ca9a 1660(define (resolve-module name . maybe-autoload)
0f2d19dd 1661 (let ((full-name (append '(app modules) name)))
0dd5491c 1662 (let ((already (local-ref full-name)))
0f2d19dd
JB
1663 (or already
1664 (begin
0209ca9a 1665 (if (or (null? maybe-autoload) (car maybe-autoload))
d0cbd20c
MV
1666 (or (try-module-autoload name)
1667 (try-module-dynamic-link name)))
0f2d19dd
JB
1668 (make-modules-in (current-module) full-name))))))
1669
1670(define (beautify-user-module! module)
1671 (if (not (module-public-interface module))
1672 (let ((interface (make-module 31)))
1673 (set-module-name! interface (module-name module))
1674 (set-module-kind! interface 'interface)
1675 (set-module-public-interface! module interface)))
cc7f066c
MD
1676 (if (and (not (memq the-scm-module (module-uses module)))
1677 (not (eq? module the-root-module)))
0f2d19dd
JB
1678 (set-module-uses! module (append (module-uses module) (list the-scm-module)))))
1679
1680(define (make-modules-in module name)
1681 (if (null? name)
1682 module
1683 (cond
1684 ((module-ref module (car name) #f) => (lambda (m) (make-modules-in m (cdr name))))
1685 (else (let ((m (make-module 31)))
1686 (set-module-kind! m 'directory)
1687 (set-module-name! m (car name))
1688 (module-define! module (car name) m)
1689 (make-modules-in m (cdr name)))))))
1690
1691(define (resolve-interface name)
1692 (let ((module (resolve-module name)))
1693 (and module (module-public-interface module))))
1694
1695
1696(define %autoloader-developer-mode #t)
1697
1698(define (process-define-module args)
1699 (let* ((module-id (car args))
0209ca9a 1700 (module (resolve-module module-id #f))
0f2d19dd
JB
1701 (kws (cdr args)))
1702 (beautify-user-module! module)
0209ca9a
MV
1703 (let loop ((kws kws)
1704 (reversed-interfaces '()))
1705 (if (null? kws)
1706 (for-each (lambda (interface)
1707 (module-use! module interface))
1708 reversed-interfaces)
04798288
MD
1709 (case (cond ((keyword? (car kws))
1710 (keyword->symbol (car kws)))
90268b35
MD
1711 ((and (symbol? (car kws))
1712 (eq? (string-ref (car kws) 0) #\:))
04798288 1713 (string->symbol (substring (car kws) 1)))
90268b35 1714 (else #f))
04798288 1715 ((use-module)
0209ca9a
MV
1716 (if (not (pair? (cdr kws)))
1717 (error "unrecognized defmodule argument" kws))
1718 (let* ((used-name (cadr kws))
1719 (used-module (resolve-module used-name)))
1720 (if (not (module-ref used-module '%module-public-interface #f))
1721 (begin
1722 ((if %autoloader-developer-mode warn error)
1723 "no code for module" (module-name used-module))
1724 (beautify-user-module! used-module)))
1725 (let ((interface (module-public-interface used-module)))
1726 (if (not interface)
1727 (error "missing interface for use-module" used-module))
1728 (loop (cddr kws) (cons interface reversed-interfaces)))))
1729 (else
1730 (error "unrecognized defmodule argument" kws)))))
0f2d19dd
JB
1731 module))
1732\f
44cf1f0f 1733;;; {Autoloading modules}
0f2d19dd
JB
1734
1735(define autoloads-in-progress '())
1736
1737(define (try-module-autoload module-name)
6fa8995c 1738
0f2d19dd
JB
1739 (define (sfx name) (string-append name (scheme-file-suffix)))
1740 (let* ((reverse-name (reverse module-name))
1741 (name (car reverse-name))
1742 (dir-hint-module-name (reverse (cdr reverse-name)))
1743 (dir-hint (apply symbol-append (map (lambda (elt) (symbol-append elt "/")) dir-hint-module-name))))
0209ca9a 1744 (resolve-module dir-hint-module-name #f)
0f2d19dd
JB
1745 (and (not (autoload-done-or-in-progress? dir-hint name))
1746 (let ((didit #f))
1747 (dynamic-wind
1748 (lambda () (autoload-in-progress! dir-hint name))
1749 (lambda ()
1750 (let loop ((dirs %load-path))
1751 (and (not (null? dirs))
1752 (or
1753 (let ((d (car dirs))
1754 (trys (list
1755 dir-hint
1756 (sfx dir-hint)
1757 (in-vicinity dir-hint name)
1758 (in-vicinity dir-hint (sfx name)))))
1759 (and (or-map (lambda (f)
1760 (let ((full (in-vicinity d f)))
1761 full
6fa8995c
GH
1762 (and (file-exists? full)
1763 (not (file-is-directory? full))
0f2d19dd
JB
1764 (begin
1765 (save-module-excursion
1766 (lambda ()
5552355a
GH
1767 (load (string-append
1768 d "/" f))))
0f2d19dd
JB
1769 #t))))
1770 trys)
1771 (begin
1772 (set! didit #t)
1773 #t)))
1774 (loop (cdr dirs))))))
1775 (lambda () (set-autoloaded! dir-hint name didit)))
1776 didit))))
1777
d0cbd20c
MV
1778;;; Dynamic linking of modules
1779
1780;; Initializing a module that is written in C is a two step process.
1781;; First the module's `module init' function is called. This function
1782;; is expected to call `scm_register_module_xxx' to register the `real
1783;; init' function. Later, when the module is referenced for the first
1784;; time, this real init function is called in the right context. See
1785;; gtcltk-lib/gtcltk-module.c for an example.
1786;;
1787;; The code for the module can be in a regular shared library (so that
1788;; the `module init' function will be called when libguile is
1789;; initialized). Or it can be dynamically linked.
1790;;
1791;; You can safely call `scm_register_module_xxx' before libguile
1792;; itself is initialized. You could call it from an C++ constructor
1793;; of a static object, for example.
1794;;
1795;; To make your Guile extension into a dynamic linkable module, follow
1796;; these easy steps:
1797;;
1798;; - Find a name for your module, like #/ice-9/gtcltk
1799;; - Write a function with a name like
1800;;
1801;; scm_init_ice_9_gtcltk_module
1802;;
1803;; This is your `module init' function. It should call
1804;;
1805;; scm_register_module_xxx ("ice-9 gtcltk", scm_init_gtcltk);
1806;;
1807;; "ice-9 gtcltk" is the C version of the module name. Slashes are
1808;; replaced by spaces, the rest is untouched. `scm_init_gtcltk' is
ed218d98 1809;; the real init function that executes the usual initializations
d0cbd20c
MV
1810;; like making new smobs, etc.
1811;;
1812;; - Make a shared library with your code and a name like
1813;;
1814;; ice-9/libgtcltk.so
1815;;
1816;; and put it somewhere in %load-path.
1817;;
1818;; - Then you can simply write `:use-module #/ice-9/gtcltk' and it
1819;; will be linked automatically.
1820;;
1821;; This is all very experimental.
1822
1823(define (split-c-module-name str)
1824 (let loop ((rev '())
1825 (start 0)
1826 (pos 0)
1827 (end (string-length str)))
1828 (cond
1829 ((= pos end)
1830 (reverse (cons (string->symbol (substring str start pos)) rev)))
1831 ((eq? (string-ref str pos) #\space)
1832 (loop (cons (string->symbol (substring str start pos)) rev)
1833 (+ pos 1)
1834 (+ pos 1)
1835 end))
1836 (else
1837 (loop rev start (+ pos 1) end)))))
1838
1839(define (convert-c-registered-modules dynobj)
1840 (let ((res (map (lambda (c)
1841 (list (split-c-module-name (car c)) (cdr c) dynobj))
1842 (c-registered-modules))))
1843 (c-clear-registered-modules)
1844 res))
1845
1846(define registered-modules (convert-c-registered-modules #f))
1847
1848(define (init-dynamic-module modname)
1849 (or-map (lambda (modinfo)
1850 (if (equal? (car modinfo) modname)
1851 (let ((mod (resolve-module modname #f)))
1852 (save-module-excursion
1853 (lambda ()
1854 (set-current-module mod)
1855 (dynamic-call (cadr modinfo) (caddr modinfo))
1856 (set-module-public-interface! mod mod)))
1857 (set! registered-modules (delq! modinfo registered-modules))
1858 #t)
1859 #f))
1860 registered-modules))
1861
1862(define (dynamic-maybe-call name dynobj)
1863 (catch #t ; could use false-if-exception here
1864 (lambda ()
1865 (dynamic-call name dynobj))
1866 (lambda args
1867 #f)))
1868
ed218d98
MV
1869(define (dynamic-maybe-link filename)
1870 (catch #t ; could use false-if-exception here
1871 (lambda ()
1872 (dynamic-link filename))
1873 (lambda args
1874 #f)))
1875
d0cbd20c
MV
1876(define (find-and-link-dynamic-module module-name)
1877 (define (make-init-name mod-name)
1878 (string-append 'scm_init
1879 (list->string (map (lambda (c)
1880 (if (or (char-alphabetic? c)
1881 (char-numeric? c))
1882 c
1883 #\_))
1884 (string->list mod-name)))
1885 '_module))
1886 (let ((libname
1887 (let loop ((dirs "")
1888 (syms module-name))
1889 (cond
1890 ((null? (cdr syms))
1891 (string-append dirs "lib" (car syms) ".so"))
1892 (else
1893 (loop (string-append dirs (car syms) "/") (cdr syms))))))
1894 (init (make-init-name (apply string-append
1895 (map (lambda (s)
1896 (string-append "_" s))
1897 module-name)))))
1898 ;; (pk 'libname libname 'init init)
1899 (or-map
1900 (lambda (dir)
1901 (let ((full (in-vicinity dir libname)))
1902 ;; (pk 'trying full)
1903 (if (file-exists? full)
1904 (begin
1905 (link-dynamic-module full init)
1906 #t)
1907 #f)))
1908 %load-path)))
1909
1910(define (link-dynamic-module filename initname)
6b856182
MV
1911 (let ((dynobj (dynamic-link filename)))
1912 (dynamic-call initname dynobj)
1913 (set! registered-modules
1914 (append! (convert-c-registered-modules dynobj)
1915 registered-modules))))
ed218d98 1916
d0cbd20c
MV
1917(define (try-module-dynamic-link module-name)
1918 (or (init-dynamic-module module-name)
1919 (and (find-and-link-dynamic-module module-name)
1920 (init-dynamic-module module-name))))
1921
ed218d98
MV
1922
1923
0f2d19dd
JB
1924(define autoloads-done '((guile . guile)))
1925
1926(define (autoload-done-or-in-progress? p m)
1927 (let ((n (cons p m)))
1928 (->bool (or (member n autoloads-done)
1929 (member n autoloads-in-progress)))))
1930
1931(define (autoload-done! p m)
1932 (let ((n (cons p m)))
1933 (set! autoloads-in-progress
1934 (delete! n autoloads-in-progress))
1935 (or (member n autoloads-done)
1936 (set! autoloads-done (cons n autoloads-done)))))
1937
1938(define (autoload-in-progress! p m)
1939 (let ((n (cons p m)))
1940 (set! autoloads-done
1941 (delete! n autoloads-done))
1942 (set! autoloads-in-progress (cons n autoloads-in-progress))))
1943
1944(define (set-autoloaded! p m done?)
1945 (if done?
1946 (autoload-done! p m)
1947 (let ((n (cons p m)))
1948 (set! autoloads-done (delete! n autoloads-done))
1949 (set! autoloads-in-progress (delete! n autoloads-in-progress)))))
1950
1951
1952
1953
1954\f
1955;;; {Macros}
1956;;;
1957
9591db87
MD
1958(define macro-table (make-weak-key-hash-table 523))
1959(define xformer-table (make-weak-key-hash-table 523))
0f2d19dd
JB
1960
1961(define (defmacro? m) (hashq-ref macro-table m))
1962(define (assert-defmacro?! m) (hashq-set! macro-table m #t))
1963(define (defmacro-transformer m) (hashq-ref xformer-table m))
1964(define (set-defmacro-transformer! m t) (hashq-set! xformer-table m t))
1965
1966(define defmacro:transformer
1967 (lambda (f)
1968 (let* ((xform (lambda (exp env)
1969 (copy-tree (apply f (cdr exp)))))
1970 (a (procedure->memoizing-macro xform)))
1971 (assert-defmacro?! a)
1972 (set-defmacro-transformer! a f)
1973 a)))
1974
1975
1976(define defmacro
1977 (let ((defmacro-transformer
1978 (lambda (name parms . body)
1979 (let ((transformer `(lambda ,parms ,@body)))
1980 `(define ,name
1981 (,(lambda (transformer)
1982 (defmacro:transformer transformer))
1983 ,transformer))))))
1984 (defmacro:transformer defmacro-transformer)))
1985
1986(define defmacro:syntax-transformer
1987 (lambda (f)
1988 (procedure->syntax
1989 (lambda (exp env)
1990 (copy-tree (apply f (cdr exp)))))))
1991
ed218d98
MV
1992
1993;; XXX - should the definition of the car really be looked up in the
1994;; current module?
1995
0f2d19dd
JB
1996(define (macroexpand-1 e)
1997 (cond
1998 ((pair? e) (let* ((a (car e))
ed218d98 1999 (val (and (symbol? a) (local-ref (list a)))))
0f2d19dd
JB
2000 (if (defmacro? val)
2001 (apply (defmacro-transformer val) (cdr e))
2002 e)))
2003 (#t e)))
2004
2005(define (macroexpand e)
2006 (cond
2007 ((pair? e) (let* ((a (car e))
ed218d98 2008 (val (and (symbol? a) (local-ref (list a)))))
0f2d19dd
JB
2009 (if (defmacro? val)
2010 (macroexpand (apply (defmacro-transformer val) (cdr e)))
2011 e)))
2012 (#t e)))
2013
2014(define gentemp
2015 (let ((*gensym-counter* -1))
2016 (lambda ()
2017 (set! *gensym-counter* (+ *gensym-counter* 1))
2018 (string->symbol
2019 (string-append "scm:G" (number->string *gensym-counter*))))))
2020
2021
2022\f
2023
2024;;; {Running Repls}
2025;;;
2026
2027(define (repl read evaler print)
75a97b92 2028 (let loop ((source (read (current-input-port))))
0f2d19dd 2029 (print (evaler source))
75a97b92 2030 (loop (read (current-input-port)))))
0f2d19dd
JB
2031
2032;; A provisional repl that acts like the SCM repl:
2033;;
2034(define scm-repl-silent #f)
2035(define (assert-repl-silence v) (set! scm-repl-silent v))
2036
21ed9efe
MD
2037(define *unspecified* (if #f #f))
2038(define (unspecified? v) (eq? v *unspecified*))
2039
2040(define scm-repl-print-unspecified #f)
2041(define (assert-repl-print-unspecified v) (set! scm-repl-print-unspecified v))
2042
79451588 2043(define scm-repl-verbose #f)
0f2d19dd
JB
2044(define (assert-repl-verbosity v) (set! scm-repl-verbose v))
2045
e6875011 2046(define scm-repl-prompt "guile> ")
0f2d19dd 2047
e6875011
MD
2048(define (set-repl-prompt! v) (set! scm-repl-prompt v))
2049
d5d34fa1
MD
2050(define (default-lazy-handler key . args)
2051 (save-stack lazy-handler-dispatch)
2052 (apply throw key args))
2053
2054(define apply-frame-handler default-lazy-handler)
2055(define exit-frame-handler default-lazy-handler)
2056
2057(define (lazy-handler-dispatch key . args)
2058 (case key
2059 ((apply-frame)
2060 (apply apply-frame-handler key args))
2061 ((exit-frame)
2062 (apply exit-frame-handler key args))
2063 (else
2064 (apply default-lazy-handler key args))))
0f2d19dd 2065
59e1116d
MD
2066(define abort-hook '())
2067
0f2d19dd 2068(define (error-catching-loop thunk)
8e44e7a0
GH
2069 (let ((status #f))
2070 (define (loop first)
2071 (let ((next
2072 (catch #t
9a0d70e2 2073
8e44e7a0
GH
2074 (lambda ()
2075 (lazy-catch #t
2076 (lambda ()
2077 (dynamic-wind
2078 (lambda () (unmask-signals))
2079 (lambda ()
2080 (first)
2081
2082 ;; This line is needed because mark
2083 ;; doesn't do closures quite right.
2084 ;; Unreferenced locals should be
2085 ;; collected.
2086 ;;
2087 (set! first #f)
2088 (let loop ((v (thunk)))
2089 (loop (thunk)))
2090 #f)
2091 (lambda () (mask-signals))))
2092
2093 lazy-handler-dispatch))
2094
2095 (lambda (key . args)
2096 (case key
2097 ((quit)
8e44e7a0
GH
2098 (force-output)
2099 (set! status args)
2100 #f)
2101
2102 ((switch-repl)
2103 (apply throw 'switch-repl args))
2104
2105 ((abort)
2106 ;; This is one of the closures that require
2107 ;; (set! first #f) above
2108 ;;
2109 (lambda ()
2110 (run-hooks abort-hook)
2111 (force-output)
2112 (display "ABORT: " (current-error-port))
2113 (write args (current-error-port))
2114 (newline (current-error-port))
2115 (if (and (not has-shown-debugger-hint?)
2116 (not (memq 'backtrace
2117 (debug-options-interface)))
2118 (stack? the-last-stack))
2119 (begin
2120 (newline (current-error-port))
2121 (display
2122 "Type \"(backtrace)\" to get more information.\n"
2123 (current-error-port))
2124 (set! has-shown-debugger-hint? #t)))
2125 (set! stack-saved? #f)))
2126
2127 (else
2128 ;; This is the other cons-leak closure...
2129 (lambda ()
2130 (cond ((= (length args) 4)
2131 (apply handle-system-error key args))
2132 (else
2133 (apply bad-throw key args))))))))))
2134 (if next (loop next) status)))
2135 (loop (lambda () #t))))
0f2d19dd 2136
d590bbf6 2137;;(define the-last-stack #f) Defined by scm_init_backtrace ()
21ed9efe
MD
2138(define stack-saved? #f)
2139
2140(define (save-stack . narrowing)
2141 (cond (stack-saved?)
2142 ((not (memq 'debug (debug-options-interface)))
2143 (set! the-last-stack #f)
2144 (set! stack-saved? #t))
2145 (else
2146 (set! the-last-stack
2147 (case (stack-id #t)
2148 ((repl-stack)
2149 (apply make-stack #t save-stack eval narrowing))
2150 ((load-stack)
2151 (apply make-stack #t save-stack gsubr-apply narrowing))
2152 ((tk-stack)
2153 (apply make-stack #t save-stack tk-stack-mark narrowing))
2154 ((#t)
e6875011 2155 (apply make-stack #t save-stack 0 1 narrowing))
21ed9efe
MD
2156 (else (let ((id (stack-id #t)))
2157 (and (procedure? id)
2158 (apply make-stack #t save-stack id narrowing))))))
2159 (set! stack-saved? #t))))
1c6cd8e8 2160
59e1116d
MD
2161(define before-error-hook '())
2162(define after-error-hook '())
2163(define before-backtrace-hook '())
2164(define after-backtrace-hook '())
1c6cd8e8 2165
21ed9efe
MD
2166(define has-shown-debugger-hint? #f)
2167
35c5db87
GH
2168(define (handle-system-error key . args)
2169 (let ((cep (current-error-port)))
21ed9efe
MD
2170 (cond ((not (stack? the-last-stack)))
2171 ((memq 'backtrace (debug-options-interface))
59e1116d 2172 (run-hooks before-backtrace-hook)
21ed9efe
MD
2173 (newline cep)
2174 (display-backtrace the-last-stack cep)
2175 (newline cep)
59e1116d
MD
2176 (run-hooks after-backtrace-hook)))
2177 (run-hooks before-error-hook)
c27659c8 2178 (apply display-error the-last-stack cep args)
59e1116d 2179 (run-hooks after-error-hook)
35c5db87
GH
2180 (force-output cep)
2181 (throw 'abort key)))
21ed9efe 2182
0f2d19dd
JB
2183(define (quit . args)
2184 (apply throw 'quit args))
2185
7950df7c
GH
2186(define exit quit)
2187
d590bbf6
MD
2188;;(define has-shown-backtrace-hint? #f) Defined by scm_init_backtrace ()
2189
2190;; Replaced by C code:
2191;;(define (backtrace)
2192;; (if the-last-stack
2193;; (begin
2194;; (newline)
2195;; (display-backtrace the-last-stack (current-output-port))
2196;; (newline)
2197;; (if (and (not has-shown-backtrace-hint?)
2198;; (not (memq 'backtrace (debug-options-interface))))
2199;; (begin
2200;; (display
2201;;"Type \"(debug-enable 'backtrace)\" if you would like a backtrace
2202;;automatically if an error occurs in the future.\n")
2203;; (set! has-shown-backtrace-hint? #t))))
2204;; (display "No backtrace available.\n")))
21ed9efe 2205
0f2d19dd
JB
2206(define (error-catching-repl r e p)
2207 (error-catching-loop (lambda () (p (e (r))))))
2208
2209(define (gc-run-time)
2210 (cdr (assq 'gc-time-taken (gc-stats))))
2211
59e1116d
MD
2212(define before-read-hook '())
2213(define after-read-hook '())
1c6cd8e8 2214
0f2d19dd
JB
2215(define (scm-style-repl)
2216 (letrec (
2217 (start-gc-rt #f)
2218 (start-rt #f)
2219 (repl-report-reset (lambda () #f))
2220 (repl-report-start-timing (lambda ()
2221 (set! start-gc-rt (gc-run-time))
2222 (set! start-rt (get-internal-run-time))))
2223 (repl-report (lambda ()
2224 (display ";;; ")
2225 (display (inexact->exact
2226 (* 1000 (/ (- (get-internal-run-time) start-rt)
2227 internal-time-units-per-second))))
2228 (display " msec (")
2229 (display (inexact->exact
2230 (* 1000 (/ (- (gc-run-time) start-gc-rt)
2231 internal-time-units-per-second))))
2232 (display " msec in gc)\n")))
480977d0
JB
2233
2234 (consume-trailing-whitespace
2235 (lambda ()
2236 (let ((ch (peek-char)))
2237 (cond
2238 ((eof-object? ch))
2239 ((or (char=? ch #\space) (char=? ch #\tab))
2240 (read-char)
2241 (consume-trailing-whitespace))
2242 ((char=? ch #\newline)
2243 (read-char))))))
0f2d19dd
JB
2244 (-read (lambda ()
2245 (if scm-repl-prompt
2246 (begin
e6875011
MD
2247 (display (cond ((string? scm-repl-prompt)
2248 scm-repl-prompt)
2249 ((thunk? scm-repl-prompt)
2250 (scm-repl-prompt))
2251 (else "> ")))
0f2d19dd
JB
2252 (force-output)
2253 (repl-report-reset)))
59e1116d 2254 (run-hooks before-read-hook)
75a97b92 2255 (let ((val (read (current-input-port))))
480977d0
JB
2256 ;; As described in R4RS, the READ procedure updates the
2257 ;; port to point to the first characetr past the end of
2258 ;; the external representation of the object. This
2259 ;; means that it doesn't consume the newline typically
2260 ;; found after an expression. This means that, when
2261 ;; debugging Guile with GDB, GDB gets the newline, which
2262 ;; it often interprets as a "continue" command, making
2263 ;; breakpoints kind of useless. So, consume any
2264 ;; trailing newline here, as well as any whitespace
2265 ;; before it.
2266 (consume-trailing-whitespace)
59e1116d 2267 (run-hooks after-read-hook)
0f2d19dd
JB
2268 (if (eof-object? val)
2269 (begin
7950df7c 2270 (repl-report-start-timing)
0f2d19dd
JB
2271 (if scm-repl-verbose
2272 (begin
2273 (newline)
2274 (display ";;; EOF -- quitting")
2275 (newline)))
2276 (quit 0)))
2277 val)))
2278
2279 (-eval (lambda (sourc)
2280 (repl-report-start-timing)
4cdee789 2281 (start-stack 'repl-stack (eval sourc))))
0f2d19dd
JB
2282
2283 (-print (lambda (result)
2284 (if (not scm-repl-silent)
2285 (begin
21ed9efe
MD
2286 (if (or scm-repl-print-unspecified
2287 (not (unspecified? result)))
2288 (begin
2289 (write result)
2290 (newline)))
0f2d19dd
JB
2291 (if scm-repl-verbose
2292 (repl-report))
2293 (force-output)))))
2294
8e44e7a0 2295 (-quit (lambda (args)
0f2d19dd
JB
2296 (if scm-repl-verbose
2297 (begin
2298 (display ";;; QUIT executed, repl exitting")
2299 (newline)
2300 (repl-report)))
8e44e7a0 2301 args))
0f2d19dd
JB
2302
2303 (-abort (lambda ()
2304 (if scm-repl-verbose
2305 (begin
2306 (display ";;; ABORT executed.")
2307 (newline)
2308 (repl-report)))
2309 (repl -read -eval -print))))
2310
8e44e7a0
GH
2311 (let ((status (error-catching-repl -read
2312 -eval
2313 -print)))
2314 (-quit status))))
2315
0f2d19dd 2316
0f2d19dd 2317\f
44cf1f0f 2318;;; {IOTA functions: generating lists of numbers}
0f2d19dd
JB
2319
2320(define (reverse-iota n) (if (> n 0) (cons (1- n) (reverse-iota (1- n))) '()))
2321(define (iota n) (list-reverse! (reverse-iota n)))
2322
2323\f
2324;;; {While}
2325;;;
2326;;; with `continue' and `break'.
2327;;;
2328
2329(defmacro while (cond . body)
2330 `(letrec ((continue (lambda () (or (not ,cond) (begin (begin ,@ body) (continue)))))
2331 (break (lambda val (apply throw 'break val))))
2332 (catch 'break
2333 (lambda () (continue))
2334 (lambda v (cadr v)))))
2335
2336
2337\f
2338
2339;;; {Macros}
2340;;;
2341
2342;; actually....hobbit might be able to hack these with a little
2343;; coaxing
2344;;
2345
2346(defmacro define-macro (first . rest)
2347 (let ((name (if (symbol? first) first (car first)))
2348 (transformer
2349 (if (symbol? first)
2350 (car rest)
2351 `(lambda ,(cdr first) ,@rest))))
2352 `(define ,name (defmacro:transformer ,transformer))))
2353
2354
2355(defmacro define-syntax-macro (first . rest)
2356 (let ((name (if (symbol? first) first (car first)))
2357 (transformer
2358 (if (symbol? first)
2359 (car rest)
2360 `(lambda ,(cdr first) ,@rest))))
2361 `(define ,name (defmacro:syntax-transformer ,transformer))))
2362\f
2363;;; {Module System Macros}
2364;;;
2365
2366(defmacro define-module args
2367 `(let* ((process-define-module process-define-module)
2368 (set-current-module set-current-module)
2369 (module (process-define-module ',args)))
2370 (set-current-module module)
2371 module))
2372
89da9036
MV
2373;; the guts of the use-modules macro. add the interfaces of the named
2374;; modules to the use-list of the current module, in order
2375(define (process-use-modules module-names)
2376 (for-each (lambda (module-name)
2377 (let ((mod-iface (resolve-interface module-name)))
2378 (or mod-iface
2379 (error "no such module" module-name))
2380 (module-use! (current-module) mod-iface)))
2381 (reverse module-names)))
2382
33cf699f 2383(defmacro use-modules modules
89da9036 2384 `(process-use-modules ',modules))
33cf699f 2385
0f2d19dd
JB
2386(define define-private define)
2387
2388(defmacro define-public args
2389 (define (syntax)
2390 (error "bad syntax" (list 'define-public args)))
2391 (define (defined-name n)
2392 (cond
2393 ((symbol? n) n)
2394 ((pair? n) (defined-name (car n)))
2395 (else (syntax))))
2396 (cond
2397 ((null? args) (syntax))
2398
2399 (#t (let ((name (defined-name (car args))))
2400 `(begin
2401 (let ((public-i (module-public-interface (current-module))))
2402 ;; Make sure there is a local variable:
2403 ;;
2404 (module-define! (current-module)
2405 ',name
2406 (module-ref (current-module) ',name #f))
2407
2408 ;; Make sure that local is exported:
2409 ;;
2410 (module-add! public-i ',name (module-variable (current-module) ',name)))
2411
2412 ;; Now (re)define the var normally.
2413 ;;
2414 (define-private ,@ args))))))
2415
2416
2417
2418(defmacro defmacro-public args
2419 (define (syntax)
2420 (error "bad syntax" (list 'defmacro-public args)))
2421 (define (defined-name n)
2422 (cond
2423 ((symbol? n) n)
2424 (else (syntax))))
2425 (cond
2426 ((null? args) (syntax))
2427
2428 (#t (let ((name (defined-name (car args))))
2429 `(begin
2430 (let ((public-i (module-public-interface (current-module))))
2431 ;; Make sure there is a local variable:
2432 ;;
2433 (module-define! (current-module)
2434 ',name
2435 (module-ref (current-module) ',name #f))
2436
2437 ;; Make sure that local is exported:
2438 ;;
2439 (module-add! public-i ',name (module-variable (current-module) ',name)))
2440
2441 ;; Now (re)define the var normally.
2442 ;;
2443 (defmacro ,@ args))))))
2444
2445
2446
2447
0f2d19dd 2448(define load load-module)
1c6cd8e8
MD
2449;(define (load . args)
2450; (start-stack 'load-stack (apply load-module args)))
0f2d19dd
JB
2451
2452
2453\f
44cf1f0f 2454;;; {I/O functions for Tcl channels (disabled)}
0f2d19dd
JB
2455
2456;; (define in-ch (get-standard-channel TCL_STDIN))
2457;; (define out-ch (get-standard-channel TCL_STDOUT))
2458;; (define err-ch (get-standard-channel TCL_STDERR))
2459;;
2460;; (define inp (%make-channel-port in-ch "r"))
2461;; (define outp (%make-channel-port out-ch "w"))
2462;; (define errp (%make-channel-port err-ch "w"))
2463;;
2464;; (define %system-char-ready? char-ready?)
2465;;
2466;; (define (char-ready? p)
2467;; (if (not (channel-port? p))
2468;; (%system-char-ready? p)
2469;; (let* ((channel (%channel-port-channel p))
2470;; (old-blocking (channel-option-ref channel :blocking)))
2471;; (dynamic-wind
2472;; (lambda () (set-channel-option the-root-tcl-interpreter channel :blocking "0"))
2473;; (lambda () (not (eof-object? (peek-char p))))
2474;; (lambda () (set-channel-option the-root-tcl-interpreter channel :blocking old-blocking))))))
2475;;
2476;; (define (top-repl)
2477;; (with-input-from-port inp
2478;; (lambda ()
2479;; (with-output-to-port outp
2480;; (lambda ()
2481;; (with-error-to-port errp
2482;; (lambda ()
2483;; (scm-style-repl))))))))
2484;;
2485;; (set-current-input-port inp)
2486;; (set-current-output-port outp)
2487;; (set-current-error-port errp)
2488
e1a191a8
GH
2489;; this is just (scm-style-repl) with a wrapper to install and remove
2490;; signal handlers.
8e44e7a0 2491(define (top-repl)
e1a191a8
GH
2492 (let ((old-handlers #f)
2493 (signals `((,SIGINT . "User interrupt")
2494 (,SIGFPE . "Arithmetic error")
2495 (,SIGBUS . "Bad memory access (bus error)")
2496 (,SIGSEGV . "Bad memory access (Segmentation violation)"))))
2497
2498 (dynamic-wind
2499
2500 ;; call at entry
2501 (lambda ()
2502 (let ((make-handler (lambda (msg)
2503 (lambda (sig)
2504 (scm-error 'signal
2505 #f
2506 msg
2507 #f
2508 (list sig))))))
2509 (set! old-handlers
2510 (map (lambda (sig-msg)
2511 (sigaction (car sig-msg)
2512 (make-handler (cdr sig-msg))))
2513 signals))))
2514
2515 ;; the protected thunk.
2516 (lambda ()
2517 (scm-style-repl))
2518
2519 ;; call at exit.
2520 (lambda ()
2521 (map (lambda (sig-msg old-handler)
2522 (if (not (car old-handler))
2523 ;; restore original C handler.
2524 (sigaction (car sig-msg) #f)
2525 ;; restore Scheme handler, SIG_IGN or SIG_DFL.
2526 (sigaction (car sig-msg)
2527 (car old-handler)
2528 (cdr old-handler))))
2529 signals old-handlers)))))
0f2d19dd 2530
02b754d3
GH
2531(defmacro false-if-exception (expr)
2532 `(catch #t (lambda () ,expr)
2533 (lambda args #f)))
2534
0f2d19dd 2535\f
44cf1f0f 2536;;; {Calling Conventions}
0f2d19dd
JB
2537(define-module (ice-9 calling))
2538
2539;;;;
0f2d19dd
JB
2540;;;
2541;;; This file contains a number of macros that support
2542;;; common calling conventions.
2543
2544;;;
2545;;; with-excursion-function <vars> proc
2546;;; <vars> is an unevaluated list of names that are bound in the caller.
2547;;; proc is a procedure, called:
2548;;; (proc excursion)
2549;;;
2550;;; excursion is a procedure isolates all changes to <vars>
2551;;; in the dynamic scope of the call to proc. In other words,
2552;;; the values of <vars> are saved when proc is entered, and when
2553;;; proc returns, those values are restored. Values are also restored
2554;;; entering and leaving the call to proc non-locally, such as using
2555;;; call-with-current-continuation, error, or throw.
2556;;;
2557(defmacro-public with-excursion-function (vars proc)
2558 `(,proc ,(excursion-function-syntax vars)))
2559
2560
2561
2562;;; with-getter-and-setter <vars> proc
2563;;; <vars> is an unevaluated list of names that are bound in the caller.
2564;;; proc is a procedure, called:
2565;;; (proc getter setter)
2566;;;
2567;;; getter and setter are procedures used to access
2568;;; or modify <vars>.
2569;;;
2570;;; setter, called with keywords arguments, modifies the named
2571;;; values. If "foo" and "bar" are among <vars>, then:
2572;;;
2573;;; (setter :foo 1 :bar 2)
2574;;; == (set! foo 1 bar 2)
2575;;;
2576;;; getter, called with just keywords, returns
2577;;; a list of the corresponding values. For example,
2578;;; if "foo" and "bar" are among the <vars>, then
2579;;;
2580;;; (getter :foo :bar)
2581;;; => (<value-of-foo> <value-of-bar>)
2582;;;
2583;;; getter, called with no arguments, returns a list of all accepted
2584;;; keywords and the corresponding values. If "foo" and "bar" are
2585;;; the *only* <vars>, then:
2586;;;
2587;;; (getter)
2588;;; => (:foo <value-of-bar> :bar <value-of-foo>)
2589;;;
2590;;; The unusual calling sequence of a getter supports too handy
2591;;; idioms:
2592;;;
2593;;; (apply setter (getter)) ;; save and restore
2594;;;
2595;;; (apply-to-args (getter :foo :bar) ;; fetch and bind
2596;;; (lambda (foo bar) ....))
2597;;;
2598;;; ;; [ "apply-to-args" is just like two-argument "apply" except that it
2599;;; ;; takes its arguments in a different order.
2600;;;
2601;;;
2602(defmacro-public with-getter-and-setter (vars proc)
2603 `(,proc ,@ (getter-and-setter-syntax vars)))
2604
2605;;; with-getter vars proc
2606;;; A short-hand for a call to with-getter-and-setter.
2607;;; The procedure is called:
2608;;; (proc getter)
2609;;;
2610(defmacro-public with-getter (vars proc)
2611 `(,proc ,(car (getter-and-setter-syntax vars))))
2612
2613
2614;;; with-delegating-getter-and-setter <vars> get-delegate set-delegate proc
2615;;; Compose getters and setters.
2616;;;
2617;;; <vars> is an unevaluated list of names that are bound in the caller.
2618;;;
2619;;; get-delegate is called by the new getter to extend the set of
2620;;; gettable variables beyond just <vars>
2621;;; set-delegate is called by the new setter to extend the set of
2622;;; gettable variables beyond just <vars>
2623;;;
2624;;; proc is a procedure that is called
2625;;; (proc getter setter)
2626;;;
2627(defmacro-public with-delegating-getter-and-setter (vars get-delegate set-delegate proc)
2628 `(,proc ,@ (delegating-getter-and-setter-syntax vars get-delegate set-delegate)))
2629
2630
2631;;; with-delegating-getter-and-setter <vars> get-delegate set-delegate proc
2632;;; <vars> is an unevaluated list of names that are bound in the caller.
2633;;; proc is called:
2634;;;
2635;;; (proc excursion getter setter)
2636;;;
2637;;; See also:
2638;;; with-getter-and-setter
2639;;; with-excursion-function
2640;;;
2641(defmacro-public with-excursion-getter-and-setter (vars proc)
2642 `(,proc ,(excursion-function-syntax vars)
2643 ,@ (getter-and-setter-syntax vars)))
2644
2645
2646(define (excursion-function-syntax vars)
2647 (let ((saved-value-names (map gensym vars))
2648 (tmp-var-name (gensym 'temp))
2649 (swap-fn-name (gensym 'swap))
2650 (thunk-name (gensym 'thunk)))
2651 `(lambda (,thunk-name)
2652 (letrec ((,tmp-var-name #f)
2653 (,swap-fn-name
2654 (lambda () ,@ (map (lambda (n sn) `(set! ,tmp-var-name ,n ,n ,sn ,sn ,tmp-var-name))
2655 vars saved-value-names)))
2656 ,@ (map (lambda (sn n) `(,sn ,n)) saved-value-names vars))
2657 (dynamic-wind
2658 ,swap-fn-name
2659 ,thunk-name
2660 ,swap-fn-name)))))
2661
2662
2663(define (getter-and-setter-syntax vars)
2664 (let ((args-name (gensym 'args))
2665 (an-arg-name (gensym 'an-arg))
2666 (new-val-name (gensym 'new-value))
2667 (loop-name (gensym 'loop))
2668 (kws (map symbol->keyword vars)))
2669 (list `(lambda ,args-name
2670 (let ,loop-name ((,args-name ,args-name))
2671 (if (null? ,args-name)
2672 ,(if (null? kws)
2673 ''()
2674 `(let ((all-vals (,loop-name ',kws)))
2675 (let ,loop-name ((vals all-vals)
2676 (kws ',kws))
2677 (if (null? vals)
2678 '()
2679 `(,(car kws) ,(car vals) ,@(,loop-name (cdr vals) (cdr kws)))))))
2680 (map (lambda (,an-arg-name)
2681 (case ,an-arg-name
2682 ,@ (append
2683 (map (lambda (kw v) `((,kw) ,v)) kws vars)
2684 `((else (throw 'bad-get-option ,an-arg-name))))))
2685 ,args-name))))
2686
2687 `(lambda ,args-name
2688 (let ,loop-name ((,args-name ,args-name))
2689 (or (null? ,args-name)
2690 (null? (cdr ,args-name))
2691 (let ((,an-arg-name (car ,args-name))
2692 (,new-val-name (cadr ,args-name)))
2693 (case ,an-arg-name
2694 ,@ (append
2695 (map (lambda (kw v) `((,kw) (set! ,v ,new-val-name))) kws vars)
2696 `((else (throw 'bad-set-option ,an-arg-name)))))
2697 (,loop-name (cddr ,args-name)))))))))
2698
2699(define (delegating-getter-and-setter-syntax vars get-delegate set-delegate)
2700 (let ((args-name (gensym 'args))
2701 (an-arg-name (gensym 'an-arg))
2702 (new-val-name (gensym 'new-value))
2703 (loop-name (gensym 'loop))
2704 (kws (map symbol->keyword vars)))
2705 (list `(lambda ,args-name
2706 (let ,loop-name ((,args-name ,args-name))
2707 (if (null? ,args-name)
2708 (append!
2709 ,(if (null? kws)
2710 ''()
2711 `(let ((all-vals (,loop-name ',kws)))
2712 (let ,loop-name ((vals all-vals)
2713 (kws ',kws))
2714 (if (null? vals)
2715 '()
2716 `(,(car kws) ,(car vals) ,@(,loop-name (cdr vals) (cdr kws)))))))
2717 (,get-delegate))
2718 (map (lambda (,an-arg-name)
2719 (case ,an-arg-name
2720 ,@ (append
2721 (map (lambda (kw v) `((,kw) ,v)) kws vars)
2722 `((else (car (,get-delegate ,an-arg-name)))))))
2723 ,args-name))))
2724
2725 `(lambda ,args-name
2726 (let ,loop-name ((,args-name ,args-name))
2727 (or (null? ,args-name)
2728 (null? (cdr ,args-name))
2729 (let ((,an-arg-name (car ,args-name))
2730 (,new-val-name (cadr ,args-name)))
2731 (case ,an-arg-name
2732 ,@ (append
2733 (map (lambda (kw v) `((,kw) (set! ,v ,new-val-name))) kws vars)
2734 `((else (,set-delegate ,an-arg-name ,new-val-name)))))
2735 (,loop-name (cddr ,args-name)))))))))
2736
2737
2738
2739
2740;;; with-configuration-getter-and-setter <vars-etc> proc
2741;;;
2742;;; Create a getter and setter that can trigger arbitrary computation.
2743;;;
2744;;; <vars-etc> is a list of variable specifiers, explained below.
2745;;; proc is called:
2746;;;
2747;;; (proc getter setter)
2748;;;
2749;;; Each element of the <vars-etc> list is of the form:
2750;;;
2751;;; (<var> getter-hook setter-hook)
2752;;;
2753;;; Both hook elements are evaluated; the variable name is not.
2754;;; Either hook may be #f or procedure.
2755;;;
2756;;; A getter hook is a thunk that returns a value for the corresponding
2757;;; variable. If omitted (#f is passed), the binding of <var> is
2758;;; returned.
2759;;;
2760;;; A setter hook is a procedure of one argument that accepts a new value
2761;;; for the corresponding variable. If omitted, the binding of <var>
2762;;; is simply set using set!.
2763;;;
2764(defmacro-public with-configuration-getter-and-setter (vars-etc proc)
2765 `((lambda (simpler-get simpler-set body-proc)
2766 (with-delegating-getter-and-setter ()
2767 simpler-get simpler-set body-proc))
2768
2769 (lambda (kw)
2770 (case kw
2771 ,@(map (lambda (v) `((,(symbol->keyword (car v)))
2772 ,(cond
2773 ((cadr v) => list)
2774 (else `(list ,(car v))))))
2775 vars-etc)))
2776
2777 (lambda (kw new-val)
2778 (case kw
2779 ,@(map (lambda (v) `((,(symbol->keyword (car v)))
2780 ,(cond
2781 ((caddr v) => (lambda (proc) `(,proc new-val)))
2782 (else `(set! ,(car v) new-val)))))
2783 vars-etc)))
2784
2785 ,proc))
2786
2787(defmacro-public with-delegating-configuration-getter-and-setter (vars-etc delegate-get delegate-set proc)
2788 `((lambda (simpler-get simpler-set body-proc)
2789 (with-delegating-getter-and-setter ()
2790 simpler-get simpler-set body-proc))
2791
2792 (lambda (kw)
2793 (case kw
2794 ,@(append! (map (lambda (v) `((,(symbol->keyword (car v)))
2795 ,(cond
2796 ((cadr v) => list)
2797 (else `(list ,(car v))))))
2798 vars-etc)
2799 `((else (,delegate-get kw))))))
2800
2801 (lambda (kw new-val)
2802 (case kw
2803 ,@(append! (map (lambda (v) `((,(symbol->keyword (car v)))
2804 ,(cond
2805 ((caddr v) => (lambda (proc) `(,proc new-val)))
2806 (else `(set! ,(car v) new-val)))))
2807 vars-etc)
2808 `((else (,delegate-set kw new-val))))))
2809
2810 ,proc))
2811
2812
2813;;; let-configuration-getter-and-setter <vars-etc> proc
2814;;;
2815;;; This procedure is like with-configuration-getter-and-setter (q.v.)
2816;;; except that each element of <vars-etc> is:
2817;;;
2818;;; (<var> initial-value getter-hook setter-hook)
2819;;;
2820;;; Unlike with-configuration-getter-and-setter, let-configuration-getter-and-setter
2821;;; introduces bindings for the variables named in <vars-etc>.
2822;;; It is short-hand for:
2823;;;
2824;;; (let ((<var1> initial-value-1)
2825;;; (<var2> initial-value-2)
2826;;; ...)
2827;;; (with-configuration-getter-and-setter ((<var1> v1-get v1-set) ...) proc))
2828;;;
2829(defmacro-public let-with-configuration-getter-and-setter (vars-etc proc)
2830 `(let ,(map (lambda (v) `(,(car v) ,(cadr v))) vars-etc)
2831 (with-configuration-getter-and-setter ,(map (lambda (v) `(,(car v) ,(caddr v) ,(cadddr v))) vars-etc)
2832 ,proc)))
2833
2834
2835
2836\f
44cf1f0f
JB
2837;;; {Implementation of COMMON LISP list functions for Scheme}
2838
0f2d19dd
JB
2839(define-module (ice-9 common-list))
2840
2841;;"comlist.scm" Implementation of COMMON LISP list functions for Scheme
2842; Copyright (C) 1991, 1993, 1995 Aubrey Jaffer.
2843;
2844;Permission to copy this software, to redistribute it, and to use it
2845;for any purpose is granted, subject to the following restrictions and
2846;understandings.
2847;
2848;1. Any copy made of this software must include this copyright notice
2849;in full.
2850;
2851;2. I have made no warrantee or representation that the operation of
2852;this software will be error-free, and I am under no obligation to
2853;provide any services, by way of maintenance, update, or otherwise.
2854;
2855;3. In conjunction with products arising from the use of this
2856;material, there shall be no use of my name in any advertising,
2857;promotional, or sales literature without prior written consent in
2858;each case.
2859
0f2d19dd
JB
2860;;;From: hugh@ear.mit.edu (Hugh Secker-Walker)
2861(define-public (make-list k . init)
2862 (set! init (if (pair? init) (car init)))
2863 (do ((k k (+ -1 k))
2864 (result '() (cons init result)))
2865 ((<= k 0) result)))
2866
2867(define-public (adjoin e l) (if (memq e l) l (cons e l)))
2868
2869(define-public (union l1 l2)
2870 (cond ((null? l1) l2)
2871 ((null? l2) l1)
2872 (else (union (cdr l1) (adjoin (car l1) l2)))))
2873
2874(define-public (intersection l1 l2)
2875 (cond ((null? l1) l1)
2876 ((null? l2) l2)
2877 ((memv (car l1) l2) (cons (car l1) (intersection (cdr l1) l2)))
2878 (else (intersection (cdr l1) l2))))
2879
2880(define-public (set-difference l1 l2)
2881 (cond ((null? l1) l1)
2882 ((memv (car l1) l2) (set-difference (cdr l1) l2))
2883 (else (cons (car l1) (set-difference (cdr l1) l2)))))
2884
2885(define-public (reduce-init p init l)
2886 (if (null? l)
2887 init
2888 (reduce-init p (p init (car l)) (cdr l))))
2889
2890(define-public (reduce p l)
2891 (cond ((null? l) l)
2892 ((null? (cdr l)) (car l))
2893 (else (reduce-init p (car l) (cdr l)))))
2894
2895(define-public (some pred l . rest)
2896 (cond ((null? rest)
2897 (let mapf ((l l))
2898 (and (not (null? l))
2899 (or (pred (car l)) (mapf (cdr l))))))
2900 (else (let mapf ((l l) (rest rest))
2901 (and (not (null? l))
2902 (or (apply pred (car l) (map car rest))
2903 (mapf (cdr l) (map cdr rest))))))))
2904
2905(define-public (every pred l . rest)
2906 (cond ((null? rest)
2907 (let mapf ((l l))
2908 (or (null? l)
2909 (and (pred (car l)) (mapf (cdr l))))))
2910 (else (let mapf ((l l) (rest rest))
2911 (or (null? l)
2912 (and (apply pred (car l) (map car rest))
2913 (mapf (cdr l) (map cdr rest))))))))
2914
2915(define-public (notany pred . ls) (not (apply some pred ls)))
2916
2917(define-public (notevery pred . ls) (not (apply every pred ls)))
2918
2919(define-public (find-if t l)
2920 (cond ((null? l) #f)
2921 ((t (car l)) (car l))
2922 (else (find-if t (cdr l)))))
2923
2924(define-public (member-if t l)
2925 (cond ((null? l) #f)
2926 ((t (car l)) l)
2927 (else (member-if t (cdr l)))))
2928
2929(define-public (remove-if p l)
2930 (cond ((null? l) '())
2931 ((p (car l)) (remove-if p (cdr l)))
2932 (else (cons (car l) (remove-if p (cdr l))))))
2933
2934(define-public (delete-if! pred list)
2935 (let delete-if ((list list))
2936 (cond ((null? list) '())
2937 ((pred (car list)) (delete-if (cdr list)))
2938 (else
2939 (set-cdr! list (delete-if (cdr list)))
2940 list))))
2941
2942(define-public (delete-if-not! pred list)
2943 (let delete-if ((list list))
2944 (cond ((null? list) '())
2945 ((not (pred (car list))) (delete-if (cdr list)))
2946 (else
2947 (set-cdr! list (delete-if (cdr list)))
2948 list))))
2949
2950(define-public (butlast lst n)
2951 (letrec ((l (- (length lst) n))
2952 (bl (lambda (lst n)
2953 (cond ((null? lst) lst)
2954 ((positive? n)
2955 (cons (car lst) (bl (cdr lst) (+ -1 n))))
2956 (else '())))))
2957 (bl lst (if (negative? n)
2958 (slib:error "negative argument to butlast" n)
2959 l))))
2960
2961(define-public (and? . args)
2962 (cond ((null? args) #t)
2963 ((car args) (apply and? (cdr args)))
2964 (else #f)))
2965
2966(define-public (or? . args)
2967 (cond ((null? args) #f)
2968 ((car args) #t)
2969 (else (apply or? (cdr args)))))
2970
2971(define-public (has-duplicates? lst)
2972 (cond ((null? lst) #f)
2973 ((member (car lst) (cdr lst)) #t)
2974 (else (has-duplicates? (cdr lst)))))
2975
2976(define-public (list* x . y)
2977 (define (list*1 x)
2978 (if (null? (cdr x))
2979 (car x)
2980 (cons (car x) (list*1 (cdr x)))))
2981 (if (null? y)
2982 x
2983 (cons x (list*1 y))))
2984
2985;; pick p l
2986;; Apply P to each element of L, returning a list of elts
2987;; for which P returns a non-#f value.
2988;;
2989(define-public (pick p l)
2990 (let loop ((s '())
2991 (l l))
2992 (cond
2993 ((null? l) s)
2994 ((p (car l)) (loop (cons (car l) s) (cdr l)))
2995 (else (loop s (cdr l))))))
2996
2997;; pick p l
2998;; Apply P to each element of L, returning a list of the
2999;; non-#f return values of P.
3000;;
3001(define-public (pick-mappings p l)
3002 (let loop ((s '())
3003 (l l))
3004 (cond
3005 ((null? l) s)
3006 ((p (car l)) => (lambda (mapping) (loop (cons mapping s) (cdr l))))
3007 (else (loop s (cdr l))))))
3008
3009(define-public (uniq l)
3010 (if (null? l)
3011 '()
3012 (let ((u (uniq (cdr l))))
3013 (if (memq (car l) u)
3014 u
3015 (cons (car l) u)))))
3016
3017\f
44cf1f0f
JB
3018;;; {Functions for browsing modules}
3019
0f2d19dd
JB
3020(define-module (ice-9 ls)
3021 :use-module (ice-9 common-list))
3022
0f2d19dd
JB
3023;;;;
3024;;; local-definitions-in root name
8b718458
JB
3025;;; Returns a list of names defined locally in the named
3026;;; subdirectory of root.
0f2d19dd 3027;;; definitions-in root name
8b718458
JB
3028;;; Returns a list of all names defined in the named
3029;;; subdirectory of root. The list includes alll locally
3030;;; defined names as well as all names inherited from a
3031;;; member of a use-list.
0f2d19dd
JB
3032;;;
3033;;; A convenient interface for examining the nature of things:
3034;;;
3035;;; ls . various-names
3036;;;
8b718458
JB
3037;;; With just one argument, interpret that argument as the
3038;;; name of a subdirectory of the current module and
3039;;; return a list of names defined there.
0f2d19dd 3040;;;
8b718458
JB
3041;;; With more than one argument, still compute
3042;;; subdirectory lists, but return a list:
0f2d19dd
JB
3043;;; ((<subdir-name> . <names-defined-there>)
3044;;; (<subdir-name> . <names-defined-there>)
3045;;; ...)
3046;;;
3047
3048(define-public (local-definitions-in root names)
0dd5491c 3049 (let ((m (nested-ref root names))
0f2d19dd
JB
3050 (answer '()))
3051 (if (not (module? m))
3052 (set! answer m)
3053 (module-for-each (lambda (k v) (set! answer (cons k answer))) m))
3054 answer))
3055
3056(define-public (definitions-in root names)
0dd5491c 3057 (let ((m (nested-ref root names)))
0f2d19dd
JB
3058 (if (not (module? m))
3059 m
3060 (reduce union
3061 (cons (local-definitions-in m '())
8b718458
JB
3062 (map (lambda (m2) (definitions-in m2 '()))
3063 (module-uses m)))))))
0f2d19dd
JB
3064
3065(define-public (ls . various-refs)
3066 (and various-refs
3067 (if (cdr various-refs)
3068 (map (lambda (ref)
3069 (cons ref (definitions-in (current-module) ref)))
3070 various-refs)
3071 (definitions-in (current-module) (car various-refs)))))
3072
3073(define-public (lls . various-refs)
3074 (and various-refs
3075 (if (cdr various-refs)
3076 (map (lambda (ref)
3077 (cons ref (local-definitions-in (current-module) ref)))
3078 various-refs)
3079 (local-definitions-in (current-module) (car various-refs)))))
3080
0dd5491c 3081(define-public (recursive-local-define name value)
0f2d19dd
JB
3082 (let ((parent (reverse! (cdr (reverse name)))))
3083 (and parent (make-modules-in (current-module) parent))
0dd5491c 3084 (local-define name value)))
0f2d19dd 3085\f
44cf1f0f
JB
3086;;; {Queues}
3087
0f2d19dd
JB
3088(define-module (ice-9 q))
3089
3090;;;; Copyright (C) 1995 Free Software Foundation, Inc.
3091;;;;
3092;;;; This program is free software; you can redistribute it and/or modify
3093;;;; it under the terms of the GNU General Public License as published by
3094;;;; the Free Software Foundation; either version 2, or (at your option)
3095;;;; any later version.
3096;;;;
3097;;;; This program is distributed in the hope that it will be useful,
3098;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
3099;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
3100;;;; GNU General Public License for more details.
3101;;;;
3102;;;; You should have received a copy of the GNU General Public License
3103;;;; along with this software; see the file COPYING. If not, write to
15328041
JB
3104;;;; the Free Software Foundation, Inc., 59 Temple Place, Suite 330,
3105;;;; Boston, MA 02111-1307 USA
0f2d19dd
JB
3106;;;;
3107
0f2d19dd
JB
3108;;;;
3109;;; Q: Based on the interface to
3110;;;
3111;;; "queue.scm" Queues/Stacks for Scheme
3112;;; Written by Andrew Wilcox (awilcox@astro.psu.edu) on April 1, 1992.
3113;;;
3114
0f2d19dd
JB
3115;;;;
3116;;; {Q}
3117;;;
3118;;; A list is just a bunch of cons pairs that follows some constrains, right?
3119;;; Association lists are the same. Hash tables are just vectors and association
3120;;; lists. You can print them, read them, write them as constants, pun them off as other data
3121;;; structures etc. This is good. This is lisp. These structures are fast and compact
3122;;; and easy to manipulate arbitrarily because of their simple, regular structure and
3123;;; non-disjointedness (associations being lists and so forth).
3124;;;
3125;;; So I figured, queues should be the same -- just a "subtype" of cons-pair
3126;;; structures in general.
3127;;;
3128;;; A queue is a cons pair:
3129;;; ( <the-q> . <last-pair> )
3130;;;
3131;;; <the-q> is a list of things in the q. New elements go at the end of that list.
3132;;;
3133;;; <last-pair> is #f if the q is empty, and otherwise is the last pair of <the-q>.
3134;;;
3135;;; q's print nicely, but alas, they do not read well because the eq?-ness of
3136;;; <last-pair> and (last-pair <the-q>) is lost by read. The procedure
3137;;;
3138;;; (sync-q! q)
3139;;;
3140;;; recomputes and resets the <last-pair> component of a queue.
3141;;;
3142
3143(define-public (sync-q! obj) (set-cdr! obj (and (car obj) (last-pair (car obj)))))
3144
3145;;; make-q
3146;;; return a new q.
3147;;;
3148(define-public (make-q) (cons '() '()))
3149
3150;;; q? obj
3151;;; Return true if obj is a Q.
3152;;; An object is a queue if it is equal? to '(#f . #f) or
3153;;; if it is a pair P with (list? (car P)) and (eq? (cdr P) (last-pair P)).
3154;;;
3155(define-public (q? obj) (and (pair? obj)
3156 (or (and (null? (car obj))
3157 (null? (cdr obj)))
3158 (and
3159 (list? (car obj))
3160 (eq? (cdr obj) (last-pair (car obj)))))))
3161
3162;;; q-empty? obj
3163;;;
3164(define-public (q-empty? obj) (null? (car obj)))
3165
3166;;; q-empty-check q
3167;;; Throw a q-empty exception if Q is empty.
3168(define-public (q-empty-check q) (if (q-empty? q) (throw 'q-empty q)))
3169
3170
3171;;; q-front q
3172;;; Return the first element of Q.
3173(define-public (q-front q) (q-empty-check q) (caar q))
3174
3175;;; q-front q
3176;;; Return the last element of Q.
3177(define-public (q-rear q) (q-empty-check q) (cadr q))
3178
3179;;; q-remove! q obj
3180;;; Remove all occurences of obj from Q.
3181(define-public (q-remove! q obj)
3182 (while (memq obj (car q))
3183 (set-car! q (delq! obj (car q))))
3184 (set-cdr! q (last-pair (car q))))
3185
3186;;; q-push! q obj
3187;;; Add obj to the front of Q
3188(define-public (q-push! q d)
3189 (let ((h (cons d (car q))))
3190 (set-car! q h)
3191 (if (null? (cdr q))
3192 (set-cdr! q h))))
3193
3194;;; enq! q obj
3195;;; Add obj to the rear of Q
3196(define-public (enq! q d)
3197 (let ((h (cons d '())))
3198 (if (not (null? (cdr q)))
3199 (set-cdr! (cdr q) h)
3200 (set-car! q h))
3201 (set-cdr! q h)))
3202
3203;;; q-pop! q
3204;;; Take the front of Q and return it.
3205(define-public (q-pop! q)
3206 (q-empty-check q)
3207 (let ((it (caar q))
3208 (next (cdar q)))
3209 (if (not next)
3210 (set-cdr! q #f))
3211 (set-car! q next)
3212 it))
3213
3214;;; deq! q
3215;;; Take the front of Q and return it.
3216(define-public deq! q-pop!)
3217
3218;;; q-length q
3219;;; Return the number of enqueued elements.
3220;;;
3221(define-public (q-length q) (length (car q)))
3222
3223
3224
3225\f
44cf1f0f
JB
3226;;; {The runq data structure}
3227
0f2d19dd
JB
3228(define-module (ice-9 runq)
3229 :use-module (ice-9 q))
3230
0f2d19dd
JB
3231;;;; Copyright (C) 1996 Free Software Foundation, Inc.
3232;;;;
3233;;;; This program is free software; you can redistribute it and/or modify
3234;;;; it under the terms of the GNU General Public License as published by
3235;;;; the Free Software Foundation; either version 2, or (at your option)
3236;;;; any later version.
3237;;;;
3238;;;; This program is distributed in the hope that it will be useful,
3239;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
3240;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
3241;;;; GNU General Public License for more details.
3242;;;;
3243;;;; You should have received a copy of the GNU General Public License
3244;;;; along with this software; see the file COPYING. If not, write to
15328041
JB
3245;;;; the Free Software Foundation, Inc., 59 Temple Place, Suite 330,
3246;;;; Boston, MA 02111-1307 USA
0f2d19dd
JB
3247;;;;
3248
0f2d19dd 3249;;;;
0f2d19dd
JB
3250;;;
3251;;; One way to schedule parallel computations in a serial environment is
3252;;; to explicitly divide each task up into small, finite execution time,
3253;;; strips. Then you interleave the execution of strips from various
3254;;; tasks to achieve a kind of parallelism. Runqs are a handy data
3255;;; structure for this style of programming.
3256;;;
3257;;; We use thunks (nullary procedures) and lists of thunks to represent
3258;;; strips. By convention, the return value of a strip-thunk must either
3259;;; be another strip or the value #f.
3260;;;
3261;;; A runq is a procedure that manages a queue of strips. Called with no
3262;;; arguments, it processes one strip from the queue. Called with
3263;;; arguments, the arguments form a control message for the queue. The
3264;;; first argument is a symbol which is the message selector.
3265;;;
3266;;; A strip is processed this way: If the strip is a thunk, the thunk is
3267;;; called -- if it returns a strip, that strip is added back to the
3268;;; queue. To process a strip which is a list of thunks, the CAR of that
3269;;; list is called. After a call to that CAR, there are 0, 1, or 2 strips
3270;;; -- perhaps one returned by the thunk, and perhaps the CDR of the
3271;;; original strip if that CDR is not nil. The runq puts whichever of
3272;;; these strips exist back on the queue. (The exact order in which
3273;;; strips are put back on the queue determines the scheduling behavior of
3274;;; a particular queue -- it's a parameter.)
3275;;;
3276;;;
3277
3278
3279
3280;;;;
3281;;; (runq-control q msg . args)
3282;;;
3283;;; processes in the default way the control messages that
3284;;; can be sent to a runq. Q should be an ordinary
3285;;; Q (see utils/q.scm).
3286;;;
3287;;; The standard runq messages are:
3288;;;
3289;;; 'add! strip0 strip1... ;; to enqueue one or more strips
3290;;; 'enqueue! strip0 strip1... ;; to enqueue one or more strips
3291;;; 'push! strip0 ... ;; add strips to the front of the queue
3292;;; 'empty? ;; true if it is
3293;;; 'length ;; how many strips in the queue?
3294;;; 'kill! ;; empty the queue
3295;;; else ;; throw 'not-understood
3296;;;
3297(define-public (runq-control q msg . args)
3298 (case msg
3299 ((add!) (for-each (lambda (t) (enq! q t)) args) '*unspecified*)
3300 ((enque!) (for-each (lambda (t) (enq! q t)) args) '*unspecified*)
3301 ((push!) (for-each (lambda (t) (q-push! q t)) args) '*unspecified*)
3302 ((empty?) (q-empty? q))
3303 ((length) (q-length q))
3304 ((kill!) (set! q (make-q)))
3305 (else (throw 'not-understood msg args))))
3306
3307(define (run-strip thunk) (catch #t thunk (lambda ign (warn 'runq-strip thunk ign) #f)))
3308
3309;;;;
3310;;; make-void-runq
3311;;;
3312;;; Make a runq that discards all messages except "length", for which
3313;;; it returns 0.
3314;;;
3315(define-public (make-void-runq)
3316 (lambda opts
3317 (and opts
3318 (apply-to-args opts
3319 (lambda (msg . args)
3320 (case msg
3321 ((length) 0)
3322 (else #f)))))))
3323
3324;;;;
3325;;; (make-fair-runq)
3326;;;
3327;;; Returns a runq procedure.
3328;;; Called with no arguments, the procedure processes one strip from the queue.
3329;;; Called with arguments, it uses runq-control.
3330;;;
3331;;; In a fair runq, if a strip returns a new strip X, X is added
3332;;; to the end of the queue, meaning it will be the last to execute
3333;;; of all the remaining procedures.
3334;;;
3335(define-public (make-fair-runq)
3336 (letrec ((q (make-q))
3337 (self
3338 (lambda ctl
3339 (if ctl
3340 (apply runq-control q ctl)
3341 (and (not (q-empty? q))
3342 (let ((next-strip (deq! q)))
3343 (cond
3344 ((procedure? next-strip) (let ((k (run-strip next-strip)))
3345 (and k (enq! q k))))
3346 ((pair? next-strip) (let ((k (run-strip (car next-strip))))
3347 (and k (enq! q k)))
3348 (if (not (null? (cdr next-strip)))
3349 (enq! q (cdr next-strip)))))
3350 self))))))
3351 self))
3352
3353
3354;;;;
3355;;; (make-exclusive-runq)
3356;;;
3357;;; Returns a runq procedure.
3358;;; Called with no arguments, the procedure processes one strip from the queue.
3359;;; Called with arguments, it uses runq-control.
3360;;;
3361;;; In an exclusive runq, if a strip W returns a new strip X, X is added
3362;;; to the front of the queue, meaning it will be the next to execute
3363;;; of all the remaining procedures.
3364;;;
3365;;; An exception to this occurs if W was the CAR of a list of strips.
3366;;; In that case, after the return value of W is pushed onto the front
3367;;; of the queue, the CDR of the list of strips is pushed in front
3368;;; of that (if the CDR is not nil). This way, the rest of the thunks
3369;;; in the list that contained W have priority over the return value of W.
3370;;;
3371(define-public (make-exclusive-runq)
3372 (letrec ((q (make-q))
3373 (self
3374 (lambda ctl
3375 (if ctl
3376 (apply runq-control q ctl)
3377 (and (not (q-empty? q))
3378 (let ((next-strip (deq! q)))
3379 (cond
3380 ((procedure? next-strip) (let ((k (run-strip next-strip)))
3381 (and k (q-push! q k))))
3382 ((pair? next-strip) (let ((k (run-strip (car next-strip))))
3383 (and k (q-push! q k)))
3384 (if (not (null? (cdr next-strip)))
3385 (q-push! q (cdr next-strip)))))
3386 self))))))
3387 self))
3388
3389
3390;;;;
3391;;; (make-subordinate-runq-to superior basic-inferior)
3392;;;
3393;;; Returns a runq proxy for the runq basic-inferior.
3394;;;
3395;;; The proxy watches for operations on the basic-inferior that cause
3396;;; a transition from a queue length of 0 to a non-zero length and
3397;;; vice versa. While the basic-inferior queue is not empty,
3398;;; the proxy installs a task on the superior runq. Each strip
3399;;; of that task processes N strips from the basic-inferior where
3400;;; N is the length of the basic-inferior queue when the proxy
3401;;; strip is entered. [Countless scheduling variations are possible.]
3402;;;
3403(define-public (make-subordinate-runq-to superior-runq basic-runq)
3404 (let ((runq-task (cons #f #f)))
3405 (set-car! runq-task
3406 (lambda ()
3407 (if (basic-runq 'empty?)
3408 (set-cdr! runq-task #f)
3409 (do ((n (basic-runq 'length) (1- n)))
3410 ((<= n 0) #f)
3411 (basic-runq)))))
3412 (letrec ((self
3413 (lambda ctl
3414 (if (not ctl)
3415 (let ((answer (basic-runq)))
3416 (self 'empty?)
3417 answer)
3418 (begin
3419 (case (car ctl)
3420 ((suspend) (set-cdr! runq-task #f))
3421 (else (let ((answer (apply basic-runq ctl)))
3422 (if (and (not (cdr runq-task)) (not (basic-runq 'empty?)))
3423 (begin
3424 (set-cdr! runq-task runq-task)
3425 (superior-runq 'add! runq-task)))
3426 answer))))))))
3427 self)))
3428
3429;;;;
3430;;; (define fork-strips (lambda args args))
3431;;; Return a strip that starts several strips in
3432;;; parallel. If this strip is enqueued on a fair
3433;;; runq, strips of the parallel subtasks will run
3434;;; round-robin style.
3435;;;
3436(define fork-strips (lambda args args))
3437
3438
3439;;;;
3440;;; (strip-sequence . strips)
3441;;;
3442;;; Returns a new strip which is the concatenation of the argument strips.
3443;;;
3444(define-public ((strip-sequence . strips))
3445 (let loop ((st (let ((a strips)) (set! strips #f) a)))
3446 (and (not (null? st))
3447 (let ((then ((car st))))
3448 (if then
3449 (lambda () (loop (cons then (cdr st))))
3450 (lambda () (loop (cdr st))))))))
3451
3452
3453;;;;
3454;;; (fair-strip-subtask . initial-strips)
3455;;;
3456;;; Returns a new strip which is the synchronos, fair,
3457;;; parallel execution of the argument strips.
3458;;;
3459;;;
3460;;;
3461(define-public (fair-strip-subtask . initial-strips)
3462 (let ((st (make-fair-runq)))
3463 (apply st 'add! initial-strips)
3464 st))
3465
3466\f
44cf1f0f 3467;;; {String Fun}
0f2d19dd 3468
0f2d19dd
JB
3469(define-module (ice-9 string-fun))
3470
0f2d19dd 3471;;;;
0f2d19dd
JB
3472;;;
3473;;; Various string funcitons, particularly those that take
3474;;; advantage of the "shared substring" capability.
3475;;;
3476\f
44cf1f0f 3477;;; {String Fun: Dividing Strings Into Fields}
0f2d19dd
JB
3478;;;
3479;;; The names of these functions are very regular.
3480;;; Here is a grammar of a call to one of these:
3481;;;
3482;;; <string-function-invocation>
3483;;; := (<action>-<seperator-disposition>-<seperator-determination> <seperator-param> <str> <ret>)
3484;;;
3485;;; <str> = the string
3486;;;
3487;;; <ret> = The continuation. String functions generally return
3488;;; multiple values by passing them to this procedure.
3489;;;
3490;;; <action> = split
3491;;; | separate-fields
3492;;;
3493;;; "split" means to divide a string into two parts.
3494;;; <ret> will be called with two arguments.
3495;;;
3496;;; "separate-fields" means to divide a string into as many
3497;;; parts as possible. <ret> will be called with
3498;;; however many fields are found.
3499;;;
3500;;; <seperator-disposition> = before
3501;;; | after
3502;;; | discarding
3503;;;
3504;;; "before" means to leave the seperator attached to
3505;;; the beginning of the field to its right.
3506;;; "after" means to leave the seperator attached to
3507;;; the end of the field to its left.
3508;;; "discarding" means to discard seperators.
3509;;;
3510;;; Other dispositions might be handy. For example, "isolate"
3511;;; could mean to treat the separator as a field unto itself.
3512;;;
3513;;; <seperator-determination> = char
3514;;; | predicate
3515;;;
3516;;; "char" means to use a particular character as field seperator.
3517;;; "predicate" means to check each character using a particular predicate.
3518;;;
3519;;; Other determinations might be handy. For example, "character-set-member".
3520;;;
3521;;; <seperator-param> = A parameter that completes the meaning of the determinations.
3522;;; For example, if the determination is "char", then this parameter
3523;;; says which character. If it is "predicate", the parameter is the
3524;;; predicate.
3525;;;
3526;;;
3527;;; For example:
3528;;;
3529;;; (separate-fields-discarding-char #\, "foo, bar, baz, , bat" list)
3530;;; => ("foo" " bar" " baz" " " " bat")
3531;;;
3532;;; (split-after-char #\- 'an-example-of-split list)
3533;;; => ("an-" "example-of-split")
3534;;;
3535;;; As an alternative to using a determination "predicate", or to trying to do anything
3536;;; complicated with these functions, consider using regular expressions.
3537;;;
3538
3539(define-public (split-after-char char str ret)
3540 (let ((end (cond
3541 ((string-index str char) => 1+)
3542 (else (string-length str)))))
3543 (ret (make-shared-substring str 0 end)
3544 (make-shared-substring str end))))
3545
3546(define-public (split-before-char char str ret)
3547 (let ((end (or (string-index str char)
3548 (string-length str))))
3549 (ret (make-shared-substring str 0 end)
3550 (make-shared-substring str end))))
3551
3552(define-public (split-discarding-char char str ret)
3553 (let ((end (string-index str char)))
3554 (if (not end)
3555 (ret str "")
3556 (ret (make-shared-substring str 0 end)
3557 (make-shared-substring str (1+ end))))))
3558
3559(define-public (split-after-char-last char str ret)
3560 (let ((end (cond
3561 ((string-rindex str char) => 1+)
3562 (else 0))))
3563 (ret (make-shared-substring str 0 end)
3564 (make-shared-substring str end))))
3565
3566(define-public (split-before-char-last char str ret)
3567 (let ((end (or (string-rindex str char) 0)))
3568 (ret (make-shared-substring str 0 end)
3569 (make-shared-substring str end))))
3570
3571(define-public (split-discarding-char-last char str ret)
3572 (let ((end (string-rindex str char)))
3573 (if (not end)
3574 (ret str "")
3575 (ret (make-shared-substring str 0 end)
3576 (make-shared-substring str (1+ end))))))
3577
3578(define (split-before-predicate pred str ret)
3579 (let loop ((n 0))
3580 (cond
3581 ((= n (length str)) (ret str ""))
3582 ((not (pred (string-ref str n))) (loop (1+ n)))
3583 (else (ret (make-shared-substring str 0 n)
3584 (make-shared-substring str n))))))
3585(define (split-after-predicate pred str ret)
3586 (let loop ((n 0))
3587 (cond
3588 ((= n (length str)) (ret str ""))
3589 ((not (pred (string-ref str n))) (loop (1+ n)))
3590 (else (ret (make-shared-substring str 0 (1+ n))
3591 (make-shared-substring str (1+ n)))))))
3592
3593(define (split-discarding-predicate pred str ret)
3594 (let loop ((n 0))
3595 (cond
3596 ((= n (length str)) (ret str ""))
3597 ((not (pred (string-ref str n))) (loop (1+ n)))
3598 (else (ret (make-shared-substring str 0 n)
3599 (make-shared-substring str (1+ n)))))))
3600
21ed9efe 3601(define-public (separate-fields-discarding-char ch str ret)
0f2d19dd
JB
3602 (let loop ((fields '())
3603 (str str))
3604 (cond
3605 ((string-rindex str ch)
3606 => (lambda (pos) (loop (cons (make-shared-substring str (+ 1 w)) fields)
3607 (make-shared-substring str 0 w))))
3608 (else (ret (cons str fields))))))
3609
21ed9efe 3610(define-public (separate-fields-after-char ch str ret)
0f2d19dd
JB
3611 (let loop ((fields '())
3612 (str str))
3613 (cond
3614 ((string-rindex str ch)
3615 => (lambda (pos) (loop (cons (make-shared-substring str (+ 1 w)) fields)
3616 (make-shared-substring str 0 (+ 1 w)))))
3617 (else (ret (cons str fields))))))
3618
21ed9efe 3619(define-public (separate-fields-before-char ch str ret)
0f2d19dd
JB
3620 (let loop ((fields '())
3621 (str str))
3622 (cond
3623 ((string-rindex str ch)
3624 => (lambda (pos) (loop (cons (make-shared-substring str w) fields)
3625 (make-shared-substring str 0 w))))
3626 (else (ret (cons str fields))))))
3627
3628\f
44cf1f0f 3629;;; {String Fun: String Prefix Predicates}
0f2d19dd
JB
3630;;;
3631;;; Very simple:
3632;;;
21ed9efe 3633;;; (define-public ((string-prefix-predicate pred?) prefix str)
0f2d19dd
JB
3634;;; (and (<= (length prefix) (length str))
3635;;; (pred? prefix (make-shared-substring str 0 (length prefix)))))
3636;;;
3637;;; (define-public string-prefix=? (string-prefix-predicate string=?))
3638;;;
3639
3640(define-public ((string-prefix-predicate pred?) prefix str)
3641 (and (<= (length prefix) (length str))
3642 (pred? prefix (make-shared-substring str 0 (length prefix)))))
3643
3644(define-public string-prefix=? (string-prefix-predicate string=?))
3645
3646\f
44cf1f0f 3647;;; {String Fun: Strippers}
0f2d19dd
JB
3648;;;
3649;;; <stripper> = sans-<removable-part>
3650;;;
3651;;; <removable-part> = surrounding-whitespace
3652;;; | trailing-whitespace
3653;;; | leading-whitespace
3654;;; | final-newline
3655;;;
3656
3657(define-public (sans-surrounding-whitespace s)
3658 (let ((st 0)
3659 (end (string-length s)))
3660 (while (and (< st (string-length s))
3661 (char-whitespace? (string-ref s st)))
3662 (set! st (1+ st)))
3663 (while (and (< 0 end)
3664 (char-whitespace? (string-ref s (1- end))))
3665 (set! end (1- end)))
3666 (if (< end st)
3667 ""
3668 (make-shared-substring s st end))))
3669
3670(define-public (sans-trailing-whitespace s)
3671 (let ((st 0)
3672 (end (string-length s)))
3673 (while (and (< 0 end)
3674 (char-whitespace? (string-ref s (1- end))))
3675 (set! end (1- end)))
3676 (if (< end st)
3677 ""
3678 (make-shared-substring s st end))))
3679
3680(define-public (sans-leading-whitespace s)
3681 (let ((st 0)
3682 (end (string-length s)))
3683 (while (and (< st (string-length s))
3684 (char-whitespace? (string-ref s st)))
3685 (set! st (1+ st)))
3686 (if (< end st)
3687 ""
3688 (make-shared-substring s st end))))
3689
3690(define-public (sans-final-newline str)
3691 (cond
3692 ((= 0 (string-length str))
3693 str)
3694
3695 ((char=? #\nl (string-ref str (1- (string-length str))))
3696 (make-shared-substring str 0 (1- (string-length str))))
3697
3698 (else str)))
3699\f
44cf1f0f 3700;;; {String Fun: has-trailing-newline?}
0f2d19dd
JB
3701;;;
3702
3703(define-public (has-trailing-newline? str)
3704 (and (< 0 (string-length str))
3705 (char=? #\nl (string-ref str (1- (string-length str))))))
3706
3707
3708\f
44cf1f0f 3709;;; {String Fun: with-regexp-parts}
0f2d19dd
JB
3710
3711(define-public (with-regexp-parts regexp fields str return fail)
3712 (let ((parts (regexec regexp str fields)))
3713 (if (number? parts)
3714 (fail parts)
3715 (apply return parts))))
3716
3717\f
c56634ba
MD
3718;;; {Load debug extension code if debug extensions present.}
3719;;;
3720;;; *fixme* This is a temporary solution.
3721;;;
0f2d19dd 3722
c56634ba 3723(if (memq 'debug-extensions *features*)
90895e5c
MD
3724 (define-module (guile) :use-module (ice-9 debug)))
3725
3726\f
90d5e280
MD
3727;;; {Load session support if present.}
3728;;;
3729;;; *fixme* This is a temporary solution.
3730;;;
3731
3732(if (%search-load-path "ice-9/session.scm")
3733 (define-module (guile) :use-module (ice-9 session)))
3734
3735\f
90895e5c
MD
3736;;; {Load thread code if threads are present.}
3737;;;
3738;;; *fixme* This is a temporary solution.
3739;;;
3740
3741(if (memq 'threads *features*)
3742 (define-module (guile) :use-module (ice-9 threads)))
3743
21ed9efe
MD
3744\f
3745;;; {Load emacs interface support if emacs option is given.}
3746;;;
3747;;; *fixme* This is a temporary solution.
3748;;;
3749
2e3fbd8d
MD
3750(if (and (module-defined? the-root-module 'use-emacs-interface)
3751 use-emacs-interface)
21ed9efe
MD
3752 (define-module (guile) :use-module (ice-9 emacs)))
3753
3754\f
05817d9e
JB
3755;;; {Load regexp code if regexp primitives are available.}
3756
3757(if (memq 'regex *features*)
3758 (define-module (guile) :use-module (ice-9 regex)))
3759
3760\f
21ed9efe 3761
90895e5c 3762(define-module (guile))
6fa8995c
GH
3763
3764(append! %load-path (cons "." ()))