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