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