* boot-9.scm (process-define-module): Modified to handle both
[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)
04798288
MD
1725 (case (cond ((keyword? (car kws))
1726 (keyword->symbol (car kws)))
1727 ((symbol? (car kws))
1728 (string->symbol (substring (car kws) 1)))
1729 (else (car kws)))
1730 ((use-module)
0209ca9a
MV
1731 (if (not (pair? (cdr kws)))
1732 (error "unrecognized defmodule argument" kws))
1733 (let* ((used-name (cadr kws))
1734 (used-module (resolve-module used-name)))
1735 (if (not (module-ref used-module '%module-public-interface #f))
1736 (begin
1737 ((if %autoloader-developer-mode warn error)
1738 "no code for module" (module-name used-module))
1739 (beautify-user-module! used-module)))
1740 (let ((interface (module-public-interface used-module)))
1741 (if (not interface)
1742 (error "missing interface for use-module" used-module))
1743 (loop (cddr kws) (cons interface reversed-interfaces)))))
1744 (else
1745 (error "unrecognized defmodule argument" kws)))))
0f2d19dd
JB
1746 module))
1747\f
44cf1f0f 1748;;; {Autoloading modules}
0f2d19dd
JB
1749
1750(define autoloads-in-progress '())
1751
1752(define (try-module-autoload module-name)
6fa8995c 1753
0f2d19dd
JB
1754 (define (sfx name) (string-append name (scheme-file-suffix)))
1755 (let* ((reverse-name (reverse module-name))
1756 (name (car reverse-name))
1757 (dir-hint-module-name (reverse (cdr reverse-name)))
1758 (dir-hint (apply symbol-append (map (lambda (elt) (symbol-append elt "/")) dir-hint-module-name))))
0209ca9a 1759 (resolve-module dir-hint-module-name #f)
0f2d19dd
JB
1760 (and (not (autoload-done-or-in-progress? dir-hint name))
1761 (let ((didit #f))
1762 (dynamic-wind
1763 (lambda () (autoload-in-progress! dir-hint name))
1764 (lambda ()
1765 (let loop ((dirs %load-path))
1766 (and (not (null? dirs))
1767 (or
1768 (let ((d (car dirs))
1769 (trys (list
1770 dir-hint
1771 (sfx dir-hint)
1772 (in-vicinity dir-hint name)
1773 (in-vicinity dir-hint (sfx name)))))
1774 (and (or-map (lambda (f)
1775 (let ((full (in-vicinity d f)))
1776 full
6fa8995c
GH
1777 (and (file-exists? full)
1778 (not (file-is-directory? full))
0f2d19dd
JB
1779 (begin
1780 (save-module-excursion
1781 (lambda ()
5552355a
GH
1782 (load (string-append
1783 d "/" f))))
0f2d19dd
JB
1784 #t))))
1785 trys)
1786 (begin
1787 (set! didit #t)
1788 #t)))
1789 (loop (cdr dirs))))))
1790 (lambda () (set-autoloaded! dir-hint name didit)))
1791 didit))))
1792
d0cbd20c
MV
1793;;; Dynamic linking of modules
1794
1795;; Initializing a module that is written in C is a two step process.
1796;; First the module's `module init' function is called. This function
1797;; is expected to call `scm_register_module_xxx' to register the `real
1798;; init' function. Later, when the module is referenced for the first
1799;; time, this real init function is called in the right context. See
1800;; gtcltk-lib/gtcltk-module.c for an example.
1801;;
1802;; The code for the module can be in a regular shared library (so that
1803;; the `module init' function will be called when libguile is
1804;; initialized). Or it can be dynamically linked.
1805;;
1806;; You can safely call `scm_register_module_xxx' before libguile
1807;; itself is initialized. You could call it from an C++ constructor
1808;; of a static object, for example.
1809;;
1810;; To make your Guile extension into a dynamic linkable module, follow
1811;; these easy steps:
1812;;
1813;; - Find a name for your module, like #/ice-9/gtcltk
1814;; - Write a function with a name like
1815;;
1816;; scm_init_ice_9_gtcltk_module
1817;;
1818;; This is your `module init' function. It should call
1819;;
1820;; scm_register_module_xxx ("ice-9 gtcltk", scm_init_gtcltk);
1821;;
1822;; "ice-9 gtcltk" is the C version of the module name. Slashes are
1823;; replaced by spaces, the rest is untouched. `scm_init_gtcltk' is
ed218d98 1824;; the real init function that executes the usual initializations
d0cbd20c
MV
1825;; like making new smobs, etc.
1826;;
1827;; - Make a shared library with your code and a name like
1828;;
1829;; ice-9/libgtcltk.so
1830;;
1831;; and put it somewhere in %load-path.
1832;;
1833;; - Then you can simply write `:use-module #/ice-9/gtcltk' and it
1834;; will be linked automatically.
1835;;
1836;; This is all very experimental.
1837
1838(define (split-c-module-name str)
1839 (let loop ((rev '())
1840 (start 0)
1841 (pos 0)
1842 (end (string-length str)))
1843 (cond
1844 ((= pos end)
1845 (reverse (cons (string->symbol (substring str start pos)) rev)))
1846 ((eq? (string-ref str pos) #\space)
1847 (loop (cons (string->symbol (substring str start pos)) rev)
1848 (+ pos 1)
1849 (+ pos 1)
1850 end))
1851 (else
1852 (loop rev start (+ pos 1) end)))))
1853
1854(define (convert-c-registered-modules dynobj)
1855 (let ((res (map (lambda (c)
1856 (list (split-c-module-name (car c)) (cdr c) dynobj))
1857 (c-registered-modules))))
1858 (c-clear-registered-modules)
1859 res))
1860
1861(define registered-modules (convert-c-registered-modules #f))
1862
1863(define (init-dynamic-module modname)
1864 (or-map (lambda (modinfo)
1865 (if (equal? (car modinfo) modname)
1866 (let ((mod (resolve-module modname #f)))
1867 (save-module-excursion
1868 (lambda ()
1869 (set-current-module mod)
1870 (dynamic-call (cadr modinfo) (caddr modinfo))
1871 (set-module-public-interface! mod mod)))
1872 (set! registered-modules (delq! modinfo registered-modules))
1873 #t)
1874 #f))
1875 registered-modules))
1876
1877(define (dynamic-maybe-call name dynobj)
1878 (catch #t ; could use false-if-exception here
1879 (lambda ()
1880 (dynamic-call name dynobj))
1881 (lambda args
1882 #f)))
1883
ed218d98
MV
1884(define (dynamic-maybe-link filename)
1885 (catch #t ; could use false-if-exception here
1886 (lambda ()
1887 (dynamic-link filename))
1888 (lambda args
1889 #f)))
1890
d0cbd20c
MV
1891(define (find-and-link-dynamic-module module-name)
1892 (define (make-init-name mod-name)
1893 (string-append 'scm_init
1894 (list->string (map (lambda (c)
1895 (if (or (char-alphabetic? c)
1896 (char-numeric? c))
1897 c
1898 #\_))
1899 (string->list mod-name)))
1900 '_module))
1901 (let ((libname
1902 (let loop ((dirs "")
1903 (syms module-name))
1904 (cond
1905 ((null? (cdr syms))
1906 (string-append dirs "lib" (car syms) ".so"))
1907 (else
1908 (loop (string-append dirs (car syms) "/") (cdr syms))))))
1909 (init (make-init-name (apply string-append
1910 (map (lambda (s)
1911 (string-append "_" s))
1912 module-name)))))
1913 ;; (pk 'libname libname 'init init)
1914 (or-map
1915 (lambda (dir)
1916 (let ((full (in-vicinity dir libname)))
1917 ;; (pk 'trying full)
1918 (if (file-exists? full)
1919 (begin
1920 (link-dynamic-module full init)
1921 #t)
1922 #f)))
1923 %load-path)))
1924
1925(define (link-dynamic-module filename initname)
ed218d98
MV
1926 (let ((dynobj (dynamic-maybe-link filename)))
1927 (if dynobj
1928 (if (dynamic-maybe-call initname dynobj)
1929 (set! registered-modules
1930 (append! (convert-c-registered-modules dynobj)
1931 registered-modules))
1932 (begin
1933 (pk 'no_init)
1934 (dynamic-unlink dynobj))))))
1935
d0cbd20c
MV
1936(define (try-module-dynamic-link module-name)
1937 (or (init-dynamic-module module-name)
1938 (and (find-and-link-dynamic-module module-name)
1939 (init-dynamic-module module-name))))
1940
ed218d98
MV
1941
1942
0f2d19dd
JB
1943(define autoloads-done '((guile . guile)))
1944
1945(define (autoload-done-or-in-progress? p m)
1946 (let ((n (cons p m)))
1947 (->bool (or (member n autoloads-done)
1948 (member n autoloads-in-progress)))))
1949
1950(define (autoload-done! p m)
1951 (let ((n (cons p m)))
1952 (set! autoloads-in-progress
1953 (delete! n autoloads-in-progress))
1954 (or (member n autoloads-done)
1955 (set! autoloads-done (cons n autoloads-done)))))
1956
1957(define (autoload-in-progress! p m)
1958 (let ((n (cons p m)))
1959 (set! autoloads-done
1960 (delete! n autoloads-done))
1961 (set! autoloads-in-progress (cons n autoloads-in-progress))))
1962
1963(define (set-autoloaded! p m done?)
1964 (if done?
1965 (autoload-done! p m)
1966 (let ((n (cons p m)))
1967 (set! autoloads-done (delete! n autoloads-done))
1968 (set! autoloads-in-progress (delete! n autoloads-in-progress)))))
1969
1970
1971
1972
1973\f
1974;;; {Macros}
1975;;;
1976
9591db87
MD
1977(define macro-table (make-weak-key-hash-table 523))
1978(define xformer-table (make-weak-key-hash-table 523))
0f2d19dd
JB
1979
1980(define (defmacro? m) (hashq-ref macro-table m))
1981(define (assert-defmacro?! m) (hashq-set! macro-table m #t))
1982(define (defmacro-transformer m) (hashq-ref xformer-table m))
1983(define (set-defmacro-transformer! m t) (hashq-set! xformer-table m t))
1984
1985(define defmacro:transformer
1986 (lambda (f)
1987 (let* ((xform (lambda (exp env)
1988 (copy-tree (apply f (cdr exp)))))
1989 (a (procedure->memoizing-macro xform)))
1990 (assert-defmacro?! a)
1991 (set-defmacro-transformer! a f)
1992 a)))
1993
1994
1995(define defmacro
1996 (let ((defmacro-transformer
1997 (lambda (name parms . body)
1998 (let ((transformer `(lambda ,parms ,@body)))
1999 `(define ,name
2000 (,(lambda (transformer)
2001 (defmacro:transformer transformer))
2002 ,transformer))))))
2003 (defmacro:transformer defmacro-transformer)))
2004
2005(define defmacro:syntax-transformer
2006 (lambda (f)
2007 (procedure->syntax
2008 (lambda (exp env)
2009 (copy-tree (apply f (cdr exp)))))))
2010
ed218d98
MV
2011
2012;; XXX - should the definition of the car really be looked up in the
2013;; current module?
2014
0f2d19dd
JB
2015(define (macroexpand-1 e)
2016 (cond
2017 ((pair? e) (let* ((a (car e))
ed218d98 2018 (val (and (symbol? a) (local-ref (list a)))))
0f2d19dd
JB
2019 (if (defmacro? val)
2020 (apply (defmacro-transformer val) (cdr e))
2021 e)))
2022 (#t e)))
2023
2024(define (macroexpand e)
2025 (cond
2026 ((pair? e) (let* ((a (car e))
ed218d98 2027 (val (and (symbol? a) (local-ref (list a)))))
0f2d19dd
JB
2028 (if (defmacro? val)
2029 (macroexpand (apply (defmacro-transformer val) (cdr e)))
2030 e)))
2031 (#t e)))
2032
2033(define gentemp
2034 (let ((*gensym-counter* -1))
2035 (lambda ()
2036 (set! *gensym-counter* (+ *gensym-counter* 1))
2037 (string->symbol
2038 (string-append "scm:G" (number->string *gensym-counter*))))))
2039
2040
2041\f
2042
2043;;; {Running Repls}
2044;;;
2045
2046(define (repl read evaler print)
75a97b92 2047 (let loop ((source (read (current-input-port))))
0f2d19dd 2048 (print (evaler source))
75a97b92 2049 (loop (read (current-input-port)))))
0f2d19dd
JB
2050
2051;; A provisional repl that acts like the SCM repl:
2052;;
2053(define scm-repl-silent #f)
2054(define (assert-repl-silence v) (set! scm-repl-silent v))
2055
21ed9efe
MD
2056(define *unspecified* (if #f #f))
2057(define (unspecified? v) (eq? v *unspecified*))
2058
2059(define scm-repl-print-unspecified #f)
2060(define (assert-repl-print-unspecified v) (set! scm-repl-print-unspecified v))
2061
79451588 2062(define scm-repl-verbose #f)
0f2d19dd
JB
2063(define (assert-repl-verbosity v) (set! scm-repl-verbose v))
2064
e6875011 2065(define scm-repl-prompt "guile> ")
0f2d19dd 2066
e6875011
MD
2067(define (set-repl-prompt! v) (set! scm-repl-prompt v))
2068
d5d34fa1
MD
2069(define (default-lazy-handler key . args)
2070 (save-stack lazy-handler-dispatch)
2071 (apply throw key args))
2072
2073(define apply-frame-handler default-lazy-handler)
2074(define exit-frame-handler default-lazy-handler)
2075
2076(define (lazy-handler-dispatch key . args)
2077 (case key
2078 ((apply-frame)
2079 (apply apply-frame-handler key args))
2080 ((exit-frame)
2081 (apply exit-frame-handler key args))
2082 (else
2083 (apply default-lazy-handler key args))))
0f2d19dd 2084
59e1116d
MD
2085(define abort-hook '())
2086
0f2d19dd 2087(define (error-catching-loop thunk)
8e44e7a0
GH
2088 (let ((status #f))
2089 (define (loop first)
2090 (let ((next
2091 (catch #t
9a0d70e2 2092
8e44e7a0
GH
2093 (lambda ()
2094 (lazy-catch #t
2095 (lambda ()
2096 (dynamic-wind
2097 (lambda () (unmask-signals))
2098 (lambda ()
2099 (first)
2100
2101 ;; This line is needed because mark
2102 ;; doesn't do closures quite right.
2103 ;; Unreferenced locals should be
2104 ;; collected.
2105 ;;
2106 (set! first #f)
2107 (let loop ((v (thunk)))
2108 (loop (thunk)))
2109 #f)
2110 (lambda () (mask-signals))))
2111
2112 lazy-handler-dispatch))
2113
2114 (lambda (key . args)
2115 (case key
2116 ((quit)
2117 (read-line) ; discard trailing junk and linefeed.
2118 (force-output)
2119 (set! status args)
2120 #f)
2121
2122 ((switch-repl)
2123 (apply throw 'switch-repl args))
2124
2125 ((abort)
2126 ;; This is one of the closures that require
2127 ;; (set! first #f) above
2128 ;;
2129 (lambda ()
2130 (run-hooks abort-hook)
2131 (force-output)
2132 (display "ABORT: " (current-error-port))
2133 (write args (current-error-port))
2134 (newline (current-error-port))
2135 (if (and (not has-shown-debugger-hint?)
2136 (not (memq 'backtrace
2137 (debug-options-interface)))
2138 (stack? the-last-stack))
2139 (begin
2140 (newline (current-error-port))
2141 (display
2142 "Type \"(backtrace)\" to get more information.\n"
2143 (current-error-port))
2144 (set! has-shown-debugger-hint? #t)))
2145 (set! stack-saved? #f)))
2146
2147 (else
2148 ;; This is the other cons-leak closure...
2149 (lambda ()
2150 (cond ((= (length args) 4)
2151 (apply handle-system-error key args))
2152 (else
2153 (apply bad-throw key args))))))))))
2154 (if next (loop next) status)))
2155 (loop (lambda () #t))))
0f2d19dd 2156
d590bbf6 2157;;(define the-last-stack #f) Defined by scm_init_backtrace ()
21ed9efe
MD
2158(define stack-saved? #f)
2159
2160(define (save-stack . narrowing)
2161 (cond (stack-saved?)
2162 ((not (memq 'debug (debug-options-interface)))
2163 (set! the-last-stack #f)
2164 (set! stack-saved? #t))
2165 (else
2166 (set! the-last-stack
2167 (case (stack-id #t)
2168 ((repl-stack)
2169 (apply make-stack #t save-stack eval narrowing))
2170 ((load-stack)
2171 (apply make-stack #t save-stack gsubr-apply narrowing))
2172 ((tk-stack)
2173 (apply make-stack #t save-stack tk-stack-mark narrowing))
2174 ((#t)
e6875011 2175 (apply make-stack #t save-stack 0 1 narrowing))
21ed9efe
MD
2176 (else (let ((id (stack-id #t)))
2177 (and (procedure? id)
2178 (apply make-stack #t save-stack id narrowing))))))
2179 (set! stack-saved? #t))))
1c6cd8e8 2180
59e1116d
MD
2181(define before-error-hook '())
2182(define after-error-hook '())
2183(define before-backtrace-hook '())
2184(define after-backtrace-hook '())
1c6cd8e8 2185
21ed9efe
MD
2186(define has-shown-debugger-hint? #f)
2187
35c5db87
GH
2188(define (handle-system-error key . args)
2189 (let ((cep (current-error-port)))
21ed9efe
MD
2190 (cond ((not (stack? the-last-stack)))
2191 ((memq 'backtrace (debug-options-interface))
59e1116d 2192 (run-hooks before-backtrace-hook)
21ed9efe
MD
2193 (newline cep)
2194 (display-backtrace the-last-stack cep)
2195 (newline cep)
59e1116d
MD
2196 (run-hooks after-backtrace-hook)))
2197 (run-hooks before-error-hook)
c27659c8 2198 (apply display-error the-last-stack cep args)
59e1116d 2199 (run-hooks after-error-hook)
35c5db87
GH
2200 (force-output cep)
2201 (throw 'abort key)))
21ed9efe 2202
0f2d19dd
JB
2203(define (quit . args)
2204 (apply throw 'quit args))
2205
7950df7c
GH
2206(define exit quit)
2207
d590bbf6
MD
2208;;(define has-shown-backtrace-hint? #f) Defined by scm_init_backtrace ()
2209
2210;; Replaced by C code:
2211;;(define (backtrace)
2212;; (if the-last-stack
2213;; (begin
2214;; (newline)
2215;; (display-backtrace the-last-stack (current-output-port))
2216;; (newline)
2217;; (if (and (not has-shown-backtrace-hint?)
2218;; (not (memq 'backtrace (debug-options-interface))))
2219;; (begin
2220;; (display
2221;;"Type \"(debug-enable 'backtrace)\" if you would like a backtrace
2222;;automatically if an error occurs in the future.\n")
2223;; (set! has-shown-backtrace-hint? #t))))
2224;; (display "No backtrace available.\n")))
21ed9efe 2225
0f2d19dd
JB
2226(define (error-catching-repl r e p)
2227 (error-catching-loop (lambda () (p (e (r))))))
2228
2229(define (gc-run-time)
2230 (cdr (assq 'gc-time-taken (gc-stats))))
2231
59e1116d
MD
2232(define before-read-hook '())
2233(define after-read-hook '())
1c6cd8e8 2234
0f2d19dd
JB
2235(define (scm-style-repl)
2236 (letrec (
2237 (start-gc-rt #f)
2238 (start-rt #f)
2239 (repl-report-reset (lambda () #f))
2240 (repl-report-start-timing (lambda ()
2241 (set! start-gc-rt (gc-run-time))
2242 (set! start-rt (get-internal-run-time))))
2243 (repl-report (lambda ()
2244 (display ";;; ")
2245 (display (inexact->exact
2246 (* 1000 (/ (- (get-internal-run-time) start-rt)
2247 internal-time-units-per-second))))
2248 (display " msec (")
2249 (display (inexact->exact
2250 (* 1000 (/ (- (gc-run-time) start-gc-rt)
2251 internal-time-units-per-second))))
2252 (display " msec in gc)\n")))
2253 (-read (lambda ()
2254 (if scm-repl-prompt
2255 (begin
e6875011
MD
2256 (display (cond ((string? scm-repl-prompt)
2257 scm-repl-prompt)
2258 ((thunk? scm-repl-prompt)
2259 (scm-repl-prompt))
2260 (else "> ")))
0f2d19dd
JB
2261 (force-output)
2262 (repl-report-reset)))
59e1116d 2263 (run-hooks before-read-hook)
75a97b92 2264 (let ((val (read (current-input-port))))
59e1116d 2265 (run-hooks after-read-hook)
0f2d19dd
JB
2266 (if (eof-object? val)
2267 (begin
7950df7c 2268 (repl-report-start-timing)
0f2d19dd
JB
2269 (if scm-repl-verbose
2270 (begin
2271 (newline)
2272 (display ";;; EOF -- quitting")
2273 (newline)))
2274 (quit 0)))
2275 val)))
2276
2277 (-eval (lambda (sourc)
2278 (repl-report-start-timing)
4cdee789 2279 (start-stack 'repl-stack (eval sourc))))
0f2d19dd
JB
2280
2281 (-print (lambda (result)
2282 (if (not scm-repl-silent)
2283 (begin
21ed9efe
MD
2284 (if (or scm-repl-print-unspecified
2285 (not (unspecified? result)))
2286 (begin
2287 (write result)
2288 (newline)))
0f2d19dd
JB
2289 (if scm-repl-verbose
2290 (repl-report))
2291 (force-output)))))
2292
8e44e7a0 2293 (-quit (lambda (args)
0f2d19dd
JB
2294 (if scm-repl-verbose
2295 (begin
2296 (display ";;; QUIT executed, repl exitting")
2297 (newline)
2298 (repl-report)))
8e44e7a0 2299 args))
0f2d19dd
JB
2300
2301 (-abort (lambda ()
2302 (if scm-repl-verbose
2303 (begin
2304 (display ";;; ABORT executed.")
2305 (newline)
2306 (repl-report)))
2307 (repl -read -eval -print))))
2308
8e44e7a0
GH
2309 (let ((status (error-catching-repl -read
2310 -eval
2311 -print)))
2312 (-quit status))))
2313
0f2d19dd 2314
8e44e7a0
GH
2315;(define (stand-alone-repl)
2316; (let ((oport (current-input-port)))
2317; (set-current-input-port *stdin*)
2318; (scm-style-repl)
2319; (set-current-input-port oport)))
0f2d19dd
JB
2320
2321
2322\f
44cf1f0f 2323;;; {IOTA functions: generating lists of numbers}
0f2d19dd
JB
2324
2325(define (reverse-iota n) (if (> n 0) (cons (1- n) (reverse-iota (1- n))) '()))
2326(define (iota n) (list-reverse! (reverse-iota n)))
2327
2328\f
2329;;; {While}
2330;;;
2331;;; with `continue' and `break'.
2332;;;
2333
2334(defmacro while (cond . body)
2335 `(letrec ((continue (lambda () (or (not ,cond) (begin (begin ,@ body) (continue)))))
2336 (break (lambda val (apply throw 'break val))))
2337 (catch 'break
2338 (lambda () (continue))
2339 (lambda v (cadr v)))))
2340
2341
2342\f
2343
2344;;; {Macros}
2345;;;
2346
2347;; actually....hobbit might be able to hack these with a little
2348;; coaxing
2349;;
2350
2351(defmacro define-macro (first . rest)
2352 (let ((name (if (symbol? first) first (car first)))
2353 (transformer
2354 (if (symbol? first)
2355 (car rest)
2356 `(lambda ,(cdr first) ,@rest))))
2357 `(define ,name (defmacro:transformer ,transformer))))
2358
2359
2360(defmacro define-syntax-macro (first . rest)
2361 (let ((name (if (symbol? first) first (car first)))
2362 (transformer
2363 (if (symbol? first)
2364 (car rest)
2365 `(lambda ,(cdr first) ,@rest))))
2366 `(define ,name (defmacro:syntax-transformer ,transformer))))
2367\f
2368;;; {Module System Macros}
2369;;;
2370
2371(defmacro define-module args
2372 `(let* ((process-define-module process-define-module)
2373 (set-current-module set-current-module)
2374 (module (process-define-module ',args)))
2375 (set-current-module module)
2376 module))
2377
33cf699f
MD
2378(defmacro use-modules modules
2379 `(for-each (lambda (module)
2380 (module-use! (current-module)
2381 (resolve-interface module)))
2382 (reverse ',modules)))
2383
0f2d19dd
JB
2384(define define-private define)
2385
2386(defmacro define-public args
2387 (define (syntax)
2388 (error "bad syntax" (list 'define-public args)))
2389 (define (defined-name n)
2390 (cond
2391 ((symbol? n) n)
2392 ((pair? n) (defined-name (car n)))
2393 (else (syntax))))
2394 (cond
2395 ((null? args) (syntax))
2396
2397 (#t (let ((name (defined-name (car args))))
2398 `(begin
2399 (let ((public-i (module-public-interface (current-module))))
2400 ;; Make sure there is a local variable:
2401 ;;
2402 (module-define! (current-module)
2403 ',name
2404 (module-ref (current-module) ',name #f))
2405
2406 ;; Make sure that local is exported:
2407 ;;
2408 (module-add! public-i ',name (module-variable (current-module) ',name)))
2409
2410 ;; Now (re)define the var normally.
2411 ;;
2412 (define-private ,@ args))))))
2413
2414
2415
2416(defmacro defmacro-public args
2417 (define (syntax)
2418 (error "bad syntax" (list 'defmacro-public args)))
2419 (define (defined-name n)
2420 (cond
2421 ((symbol? n) n)
2422 (else (syntax))))
2423 (cond
2424 ((null? args) (syntax))
2425
2426 (#t (let ((name (defined-name (car args))))
2427 `(begin
2428 (let ((public-i (module-public-interface (current-module))))
2429 ;; Make sure there is a local variable:
2430 ;;
2431 (module-define! (current-module)
2432 ',name
2433 (module-ref (current-module) ',name #f))
2434
2435 ;; Make sure that local is exported:
2436 ;;
2437 (module-add! public-i ',name (module-variable (current-module) ',name)))
2438
2439 ;; Now (re)define the var normally.
2440 ;;
2441 (defmacro ,@ args))))))
2442
2443
2444
2445
0f2d19dd 2446(define load load-module)
1c6cd8e8
MD
2447;(define (load . args)
2448; (start-stack 'load-stack (apply load-module args)))
0f2d19dd
JB
2449
2450
2451\f
44cf1f0f 2452;;; {I/O functions for Tcl channels (disabled)}
0f2d19dd
JB
2453
2454;; (define in-ch (get-standard-channel TCL_STDIN))
2455;; (define out-ch (get-standard-channel TCL_STDOUT))
2456;; (define err-ch (get-standard-channel TCL_STDERR))
2457;;
2458;; (define inp (%make-channel-port in-ch "r"))
2459;; (define outp (%make-channel-port out-ch "w"))
2460;; (define errp (%make-channel-port err-ch "w"))
2461;;
2462;; (define %system-char-ready? char-ready?)
2463;;
2464;; (define (char-ready? p)
2465;; (if (not (channel-port? p))
2466;; (%system-char-ready? p)
2467;; (let* ((channel (%channel-port-channel p))
2468;; (old-blocking (channel-option-ref channel :blocking)))
2469;; (dynamic-wind
2470;; (lambda () (set-channel-option the-root-tcl-interpreter channel :blocking "0"))
2471;; (lambda () (not (eof-object? (peek-char p))))
2472;; (lambda () (set-channel-option the-root-tcl-interpreter channel :blocking old-blocking))))))
2473;;
2474;; (define (top-repl)
2475;; (with-input-from-port inp
2476;; (lambda ()
2477;; (with-output-to-port outp
2478;; (lambda ()
2479;; (with-error-to-port errp
2480;; (lambda ()
2481;; (scm-style-repl))))))))
2482;;
2483;; (set-current-input-port inp)
2484;; (set-current-output-port outp)
2485;; (set-current-error-port errp)
2486
8e44e7a0 2487(define (top-repl)
1a36eef2 2488 (scm-style-repl))
0f2d19dd 2489
02b754d3
GH
2490(defmacro false-if-exception (expr)
2491 `(catch #t (lambda () ,expr)
2492 (lambda args #f)))
2493
0f2d19dd 2494\f
44cf1f0f 2495;;; {Calling Conventions}
0f2d19dd
JB
2496(define-module (ice-9 calling))
2497
2498;;;;
0f2d19dd
JB
2499;;;
2500;;; This file contains a number of macros that support
2501;;; common calling conventions.
2502
2503;;;
2504;;; with-excursion-function <vars> proc
2505;;; <vars> is an unevaluated list of names that are bound in the caller.
2506;;; proc is a procedure, called:
2507;;; (proc excursion)
2508;;;
2509;;; excursion is a procedure isolates all changes to <vars>
2510;;; in the dynamic scope of the call to proc. In other words,
2511;;; the values of <vars> are saved when proc is entered, and when
2512;;; proc returns, those values are restored. Values are also restored
2513;;; entering and leaving the call to proc non-locally, such as using
2514;;; call-with-current-continuation, error, or throw.
2515;;;
2516(defmacro-public with-excursion-function (vars proc)
2517 `(,proc ,(excursion-function-syntax vars)))
2518
2519
2520
2521;;; with-getter-and-setter <vars> proc
2522;;; <vars> is an unevaluated list of names that are bound in the caller.
2523;;; proc is a procedure, called:
2524;;; (proc getter setter)
2525;;;
2526;;; getter and setter are procedures used to access
2527;;; or modify <vars>.
2528;;;
2529;;; setter, called with keywords arguments, modifies the named
2530;;; values. If "foo" and "bar" are among <vars>, then:
2531;;;
2532;;; (setter :foo 1 :bar 2)
2533;;; == (set! foo 1 bar 2)
2534;;;
2535;;; getter, called with just keywords, returns
2536;;; a list of the corresponding values. For example,
2537;;; if "foo" and "bar" are among the <vars>, then
2538;;;
2539;;; (getter :foo :bar)
2540;;; => (<value-of-foo> <value-of-bar>)
2541;;;
2542;;; getter, called with no arguments, returns a list of all accepted
2543;;; keywords and the corresponding values. If "foo" and "bar" are
2544;;; the *only* <vars>, then:
2545;;;
2546;;; (getter)
2547;;; => (:foo <value-of-bar> :bar <value-of-foo>)
2548;;;
2549;;; The unusual calling sequence of a getter supports too handy
2550;;; idioms:
2551;;;
2552;;; (apply setter (getter)) ;; save and restore
2553;;;
2554;;; (apply-to-args (getter :foo :bar) ;; fetch and bind
2555;;; (lambda (foo bar) ....))
2556;;;
2557;;; ;; [ "apply-to-args" is just like two-argument "apply" except that it
2558;;; ;; takes its arguments in a different order.
2559;;;
2560;;;
2561(defmacro-public with-getter-and-setter (vars proc)
2562 `(,proc ,@ (getter-and-setter-syntax vars)))
2563
2564;;; with-getter vars proc
2565;;; A short-hand for a call to with-getter-and-setter.
2566;;; The procedure is called:
2567;;; (proc getter)
2568;;;
2569(defmacro-public with-getter (vars proc)
2570 `(,proc ,(car (getter-and-setter-syntax vars))))
2571
2572
2573;;; with-delegating-getter-and-setter <vars> get-delegate set-delegate proc
2574;;; Compose getters and setters.
2575;;;
2576;;; <vars> is an unevaluated list of names that are bound in the caller.
2577;;;
2578;;; get-delegate is called by the new getter to extend the set of
2579;;; gettable variables beyond just <vars>
2580;;; set-delegate is called by the new setter to extend the set of
2581;;; gettable variables beyond just <vars>
2582;;;
2583;;; proc is a procedure that is called
2584;;; (proc getter setter)
2585;;;
2586(defmacro-public with-delegating-getter-and-setter (vars get-delegate set-delegate proc)
2587 `(,proc ,@ (delegating-getter-and-setter-syntax vars get-delegate set-delegate)))
2588
2589
2590;;; with-delegating-getter-and-setter <vars> get-delegate set-delegate proc
2591;;; <vars> is an unevaluated list of names that are bound in the caller.
2592;;; proc is called:
2593;;;
2594;;; (proc excursion getter setter)
2595;;;
2596;;; See also:
2597;;; with-getter-and-setter
2598;;; with-excursion-function
2599;;;
2600(defmacro-public with-excursion-getter-and-setter (vars proc)
2601 `(,proc ,(excursion-function-syntax vars)
2602 ,@ (getter-and-setter-syntax vars)))
2603
2604
2605(define (excursion-function-syntax vars)
2606 (let ((saved-value-names (map gensym vars))
2607 (tmp-var-name (gensym 'temp))
2608 (swap-fn-name (gensym 'swap))
2609 (thunk-name (gensym 'thunk)))
2610 `(lambda (,thunk-name)
2611 (letrec ((,tmp-var-name #f)
2612 (,swap-fn-name
2613 (lambda () ,@ (map (lambda (n sn) `(set! ,tmp-var-name ,n ,n ,sn ,sn ,tmp-var-name))
2614 vars saved-value-names)))
2615 ,@ (map (lambda (sn n) `(,sn ,n)) saved-value-names vars))
2616 (dynamic-wind
2617 ,swap-fn-name
2618 ,thunk-name
2619 ,swap-fn-name)))))
2620
2621
2622(define (getter-and-setter-syntax vars)
2623 (let ((args-name (gensym 'args))
2624 (an-arg-name (gensym 'an-arg))
2625 (new-val-name (gensym 'new-value))
2626 (loop-name (gensym 'loop))
2627 (kws (map symbol->keyword vars)))
2628 (list `(lambda ,args-name
2629 (let ,loop-name ((,args-name ,args-name))
2630 (if (null? ,args-name)
2631 ,(if (null? kws)
2632 ''()
2633 `(let ((all-vals (,loop-name ',kws)))
2634 (let ,loop-name ((vals all-vals)
2635 (kws ',kws))
2636 (if (null? vals)
2637 '()
2638 `(,(car kws) ,(car vals) ,@(,loop-name (cdr vals) (cdr kws)))))))
2639 (map (lambda (,an-arg-name)
2640 (case ,an-arg-name
2641 ,@ (append
2642 (map (lambda (kw v) `((,kw) ,v)) kws vars)
2643 `((else (throw 'bad-get-option ,an-arg-name))))))
2644 ,args-name))))
2645
2646 `(lambda ,args-name
2647 (let ,loop-name ((,args-name ,args-name))
2648 (or (null? ,args-name)
2649 (null? (cdr ,args-name))
2650 (let ((,an-arg-name (car ,args-name))
2651 (,new-val-name (cadr ,args-name)))
2652 (case ,an-arg-name
2653 ,@ (append
2654 (map (lambda (kw v) `((,kw) (set! ,v ,new-val-name))) kws vars)
2655 `((else (throw 'bad-set-option ,an-arg-name)))))
2656 (,loop-name (cddr ,args-name)))))))))
2657
2658(define (delegating-getter-and-setter-syntax vars get-delegate set-delegate)
2659 (let ((args-name (gensym 'args))
2660 (an-arg-name (gensym 'an-arg))
2661 (new-val-name (gensym 'new-value))
2662 (loop-name (gensym 'loop))
2663 (kws (map symbol->keyword vars)))
2664 (list `(lambda ,args-name
2665 (let ,loop-name ((,args-name ,args-name))
2666 (if (null? ,args-name)
2667 (append!
2668 ,(if (null? kws)
2669 ''()
2670 `(let ((all-vals (,loop-name ',kws)))
2671 (let ,loop-name ((vals all-vals)
2672 (kws ',kws))
2673 (if (null? vals)
2674 '()
2675 `(,(car kws) ,(car vals) ,@(,loop-name (cdr vals) (cdr kws)))))))
2676 (,get-delegate))
2677 (map (lambda (,an-arg-name)
2678 (case ,an-arg-name
2679 ,@ (append
2680 (map (lambda (kw v) `((,kw) ,v)) kws vars)
2681 `((else (car (,get-delegate ,an-arg-name)))))))
2682 ,args-name))))
2683
2684 `(lambda ,args-name
2685 (let ,loop-name ((,args-name ,args-name))
2686 (or (null? ,args-name)
2687 (null? (cdr ,args-name))
2688 (let ((,an-arg-name (car ,args-name))
2689 (,new-val-name (cadr ,args-name)))
2690 (case ,an-arg-name
2691 ,@ (append
2692 (map (lambda (kw v) `((,kw) (set! ,v ,new-val-name))) kws vars)
2693 `((else (,set-delegate ,an-arg-name ,new-val-name)))))
2694 (,loop-name (cddr ,args-name)))))))))
2695
2696
2697
2698
2699;;; with-configuration-getter-and-setter <vars-etc> proc
2700;;;
2701;;; Create a getter and setter that can trigger arbitrary computation.
2702;;;
2703;;; <vars-etc> is a list of variable specifiers, explained below.
2704;;; proc is called:
2705;;;
2706;;; (proc getter setter)
2707;;;
2708;;; Each element of the <vars-etc> list is of the form:
2709;;;
2710;;; (<var> getter-hook setter-hook)
2711;;;
2712;;; Both hook elements are evaluated; the variable name is not.
2713;;; Either hook may be #f or procedure.
2714;;;
2715;;; A getter hook is a thunk that returns a value for the corresponding
2716;;; variable. If omitted (#f is passed), the binding of <var> is
2717;;; returned.
2718;;;
2719;;; A setter hook is a procedure of one argument that accepts a new value
2720;;; for the corresponding variable. If omitted, the binding of <var>
2721;;; is simply set using set!.
2722;;;
2723(defmacro-public with-configuration-getter-and-setter (vars-etc proc)
2724 `((lambda (simpler-get simpler-set body-proc)
2725 (with-delegating-getter-and-setter ()
2726 simpler-get simpler-set body-proc))
2727
2728 (lambda (kw)
2729 (case kw
2730 ,@(map (lambda (v) `((,(symbol->keyword (car v)))
2731 ,(cond
2732 ((cadr v) => list)
2733 (else `(list ,(car v))))))
2734 vars-etc)))
2735
2736 (lambda (kw new-val)
2737 (case kw
2738 ,@(map (lambda (v) `((,(symbol->keyword (car v)))
2739 ,(cond
2740 ((caddr v) => (lambda (proc) `(,proc new-val)))
2741 (else `(set! ,(car v) new-val)))))
2742 vars-etc)))
2743
2744 ,proc))
2745
2746(defmacro-public with-delegating-configuration-getter-and-setter (vars-etc delegate-get delegate-set proc)
2747 `((lambda (simpler-get simpler-set body-proc)
2748 (with-delegating-getter-and-setter ()
2749 simpler-get simpler-set body-proc))
2750
2751 (lambda (kw)
2752 (case kw
2753 ,@(append! (map (lambda (v) `((,(symbol->keyword (car v)))
2754 ,(cond
2755 ((cadr v) => list)
2756 (else `(list ,(car v))))))
2757 vars-etc)
2758 `((else (,delegate-get kw))))))
2759
2760 (lambda (kw new-val)
2761 (case kw
2762 ,@(append! (map (lambda (v) `((,(symbol->keyword (car v)))
2763 ,(cond
2764 ((caddr v) => (lambda (proc) `(,proc new-val)))
2765 (else `(set! ,(car v) new-val)))))
2766 vars-etc)
2767 `((else (,delegate-set kw new-val))))))
2768
2769 ,proc))
2770
2771
2772;;; let-configuration-getter-and-setter <vars-etc> proc
2773;;;
2774;;; This procedure is like with-configuration-getter-and-setter (q.v.)
2775;;; except that each element of <vars-etc> is:
2776;;;
2777;;; (<var> initial-value getter-hook setter-hook)
2778;;;
2779;;; Unlike with-configuration-getter-and-setter, let-configuration-getter-and-setter
2780;;; introduces bindings for the variables named in <vars-etc>.
2781;;; It is short-hand for:
2782;;;
2783;;; (let ((<var1> initial-value-1)
2784;;; (<var2> initial-value-2)
2785;;; ...)
2786;;; (with-configuration-getter-and-setter ((<var1> v1-get v1-set) ...) proc))
2787;;;
2788(defmacro-public let-with-configuration-getter-and-setter (vars-etc proc)
2789 `(let ,(map (lambda (v) `(,(car v) ,(cadr v))) vars-etc)
2790 (with-configuration-getter-and-setter ,(map (lambda (v) `(,(car v) ,(caddr v) ,(cadddr v))) vars-etc)
2791 ,proc)))
2792
2793
2794
2795\f
44cf1f0f
JB
2796;;; {Implementation of COMMON LISP list functions for Scheme}
2797
0f2d19dd
JB
2798(define-module (ice-9 common-list))
2799
2800;;"comlist.scm" Implementation of COMMON LISP list functions for Scheme
2801; Copyright (C) 1991, 1993, 1995 Aubrey Jaffer.
2802;
2803;Permission to copy this software, to redistribute it, and to use it
2804;for any purpose is granted, subject to the following restrictions and
2805;understandings.
2806;
2807;1. Any copy made of this software must include this copyright notice
2808;in full.
2809;
2810;2. I have made no warrantee or representation that the operation of
2811;this software will be error-free, and I am under no obligation to
2812;provide any services, by way of maintenance, update, or otherwise.
2813;
2814;3. In conjunction with products arising from the use of this
2815;material, there shall be no use of my name in any advertising,
2816;promotional, or sales literature without prior written consent in
2817;each case.
2818
0f2d19dd
JB
2819;;;From: hugh@ear.mit.edu (Hugh Secker-Walker)
2820(define-public (make-list k . init)
2821 (set! init (if (pair? init) (car init)))
2822 (do ((k k (+ -1 k))
2823 (result '() (cons init result)))
2824 ((<= k 0) result)))
2825
2826(define-public (adjoin e l) (if (memq e l) l (cons e l)))
2827
2828(define-public (union l1 l2)
2829 (cond ((null? l1) l2)
2830 ((null? l2) l1)
2831 (else (union (cdr l1) (adjoin (car l1) l2)))))
2832
2833(define-public (intersection l1 l2)
2834 (cond ((null? l1) l1)
2835 ((null? l2) l2)
2836 ((memv (car l1) l2) (cons (car l1) (intersection (cdr l1) l2)))
2837 (else (intersection (cdr l1) l2))))
2838
2839(define-public (set-difference l1 l2)
2840 (cond ((null? l1) l1)
2841 ((memv (car l1) l2) (set-difference (cdr l1) l2))
2842 (else (cons (car l1) (set-difference (cdr l1) l2)))))
2843
2844(define-public (reduce-init p init l)
2845 (if (null? l)
2846 init
2847 (reduce-init p (p init (car l)) (cdr l))))
2848
2849(define-public (reduce p l)
2850 (cond ((null? l) l)
2851 ((null? (cdr l)) (car l))
2852 (else (reduce-init p (car l) (cdr l)))))
2853
2854(define-public (some pred l . rest)
2855 (cond ((null? rest)
2856 (let mapf ((l l))
2857 (and (not (null? l))
2858 (or (pred (car l)) (mapf (cdr l))))))
2859 (else (let mapf ((l l) (rest rest))
2860 (and (not (null? l))
2861 (or (apply pred (car l) (map car rest))
2862 (mapf (cdr l) (map cdr rest))))))))
2863
2864(define-public (every pred l . rest)
2865 (cond ((null? rest)
2866 (let mapf ((l l))
2867 (or (null? l)
2868 (and (pred (car l)) (mapf (cdr l))))))
2869 (else (let mapf ((l l) (rest rest))
2870 (or (null? l)
2871 (and (apply pred (car l) (map car rest))
2872 (mapf (cdr l) (map cdr rest))))))))
2873
2874(define-public (notany pred . ls) (not (apply some pred ls)))
2875
2876(define-public (notevery pred . ls) (not (apply every pred ls)))
2877
2878(define-public (find-if t l)
2879 (cond ((null? l) #f)
2880 ((t (car l)) (car l))
2881 (else (find-if t (cdr l)))))
2882
2883(define-public (member-if t l)
2884 (cond ((null? l) #f)
2885 ((t (car l)) l)
2886 (else (member-if t (cdr l)))))
2887
2888(define-public (remove-if p l)
2889 (cond ((null? l) '())
2890 ((p (car l)) (remove-if p (cdr l)))
2891 (else (cons (car l) (remove-if p (cdr l))))))
2892
2893(define-public (delete-if! pred list)
2894 (let delete-if ((list list))
2895 (cond ((null? list) '())
2896 ((pred (car list)) (delete-if (cdr list)))
2897 (else
2898 (set-cdr! list (delete-if (cdr list)))
2899 list))))
2900
2901(define-public (delete-if-not! pred list)
2902 (let delete-if ((list list))
2903 (cond ((null? list) '())
2904 ((not (pred (car list))) (delete-if (cdr list)))
2905 (else
2906 (set-cdr! list (delete-if (cdr list)))
2907 list))))
2908
2909(define-public (butlast lst n)
2910 (letrec ((l (- (length lst) n))
2911 (bl (lambda (lst n)
2912 (cond ((null? lst) lst)
2913 ((positive? n)
2914 (cons (car lst) (bl (cdr lst) (+ -1 n))))
2915 (else '())))))
2916 (bl lst (if (negative? n)
2917 (slib:error "negative argument to butlast" n)
2918 l))))
2919
2920(define-public (and? . args)
2921 (cond ((null? args) #t)
2922 ((car args) (apply and? (cdr args)))
2923 (else #f)))
2924
2925(define-public (or? . args)
2926 (cond ((null? args) #f)
2927 ((car args) #t)
2928 (else (apply or? (cdr args)))))
2929
2930(define-public (has-duplicates? lst)
2931 (cond ((null? lst) #f)
2932 ((member (car lst) (cdr lst)) #t)
2933 (else (has-duplicates? (cdr lst)))))
2934
2935(define-public (list* x . y)
2936 (define (list*1 x)
2937 (if (null? (cdr x))
2938 (car x)
2939 (cons (car x) (list*1 (cdr x)))))
2940 (if (null? y)
2941 x
2942 (cons x (list*1 y))))
2943
2944;; pick p l
2945;; Apply P to each element of L, returning a list of elts
2946;; for which P returns a non-#f value.
2947;;
2948(define-public (pick p l)
2949 (let loop ((s '())
2950 (l l))
2951 (cond
2952 ((null? l) s)
2953 ((p (car l)) (loop (cons (car l) s) (cdr l)))
2954 (else (loop s (cdr l))))))
2955
2956;; pick p l
2957;; Apply P to each element of L, returning a list of the
2958;; non-#f return values of P.
2959;;
2960(define-public (pick-mappings p l)
2961 (let loop ((s '())
2962 (l l))
2963 (cond
2964 ((null? l) s)
2965 ((p (car l)) => (lambda (mapping) (loop (cons mapping s) (cdr l))))
2966 (else (loop s (cdr l))))))
2967
2968(define-public (uniq l)
2969 (if (null? l)
2970 '()
2971 (let ((u (uniq (cdr l))))
2972 (if (memq (car l) u)
2973 u
2974 (cons (car l) u)))))
2975
2976\f
44cf1f0f
JB
2977;;; {Functions for browsing modules}
2978
0f2d19dd
JB
2979(define-module (ice-9 ls)
2980 :use-module (ice-9 common-list))
2981
0f2d19dd
JB
2982;;;;
2983;;; local-definitions-in root name
8b718458
JB
2984;;; Returns a list of names defined locally in the named
2985;;; subdirectory of root.
0f2d19dd 2986;;; definitions-in root name
8b718458
JB
2987;;; Returns a list of all names defined in the named
2988;;; subdirectory of root. The list includes alll locally
2989;;; defined names as well as all names inherited from a
2990;;; member of a use-list.
0f2d19dd
JB
2991;;;
2992;;; A convenient interface for examining the nature of things:
2993;;;
2994;;; ls . various-names
2995;;;
8b718458
JB
2996;;; With just one argument, interpret that argument as the
2997;;; name of a subdirectory of the current module and
2998;;; return a list of names defined there.
0f2d19dd 2999;;;
8b718458
JB
3000;;; With more than one argument, still compute
3001;;; subdirectory lists, but return a list:
0f2d19dd
JB
3002;;; ((<subdir-name> . <names-defined-there>)
3003;;; (<subdir-name> . <names-defined-there>)
3004;;; ...)
3005;;;
3006
3007(define-public (local-definitions-in root names)
0dd5491c 3008 (let ((m (nested-ref root names))
0f2d19dd
JB
3009 (answer '()))
3010 (if (not (module? m))
3011 (set! answer m)
3012 (module-for-each (lambda (k v) (set! answer (cons k answer))) m))
3013 answer))
3014
3015(define-public (definitions-in root names)
0dd5491c 3016 (let ((m (nested-ref root names)))
0f2d19dd
JB
3017 (if (not (module? m))
3018 m
3019 (reduce union
3020 (cons (local-definitions-in m '())
8b718458
JB
3021 (map (lambda (m2) (definitions-in m2 '()))
3022 (module-uses m)))))))
0f2d19dd
JB
3023
3024(define-public (ls . various-refs)
3025 (and various-refs
3026 (if (cdr various-refs)
3027 (map (lambda (ref)
3028 (cons ref (definitions-in (current-module) ref)))
3029 various-refs)
3030 (definitions-in (current-module) (car various-refs)))))
3031
3032(define-public (lls . various-refs)
3033 (and various-refs
3034 (if (cdr various-refs)
3035 (map (lambda (ref)
3036 (cons ref (local-definitions-in (current-module) ref)))
3037 various-refs)
3038 (local-definitions-in (current-module) (car various-refs)))))
3039
0dd5491c 3040(define-public (recursive-local-define name value)
0f2d19dd
JB
3041 (let ((parent (reverse! (cdr (reverse name)))))
3042 (and parent (make-modules-in (current-module) parent))
0dd5491c 3043 (local-define name value)))
0f2d19dd 3044\f
44cf1f0f
JB
3045;;; {Queues}
3046
0f2d19dd
JB
3047(define-module (ice-9 q))
3048
3049;;;; Copyright (C) 1995 Free Software Foundation, Inc.
3050;;;;
3051;;;; This program is free software; you can redistribute it and/or modify
3052;;;; it under the terms of the GNU General Public License as published by
3053;;;; the Free Software Foundation; either version 2, or (at your option)
3054;;;; any later version.
3055;;;;
3056;;;; This program is distributed in the hope that it will be useful,
3057;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
3058;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
3059;;;; GNU General Public License for more details.
3060;;;;
3061;;;; You should have received a copy of the GNU General Public License
3062;;;; along with this software; see the file COPYING. If not, write to
3063;;;; the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
3064;;;;
3065
0f2d19dd
JB
3066;;;;
3067;;; Q: Based on the interface to
3068;;;
3069;;; "queue.scm" Queues/Stacks for Scheme
3070;;; Written by Andrew Wilcox (awilcox@astro.psu.edu) on April 1, 1992.
3071;;;
3072
0f2d19dd
JB
3073;;;;
3074;;; {Q}
3075;;;
3076;;; A list is just a bunch of cons pairs that follows some constrains, right?
3077;;; Association lists are the same. Hash tables are just vectors and association
3078;;; lists. You can print them, read them, write them as constants, pun them off as other data
3079;;; structures etc. This is good. This is lisp. These structures are fast and compact
3080;;; and easy to manipulate arbitrarily because of their simple, regular structure and
3081;;; non-disjointedness (associations being lists and so forth).
3082;;;
3083;;; So I figured, queues should be the same -- just a "subtype" of cons-pair
3084;;; structures in general.
3085;;;
3086;;; A queue is a cons pair:
3087;;; ( <the-q> . <last-pair> )
3088;;;
3089;;; <the-q> is a list of things in the q. New elements go at the end of that list.
3090;;;
3091;;; <last-pair> is #f if the q is empty, and otherwise is the last pair of <the-q>.
3092;;;
3093;;; q's print nicely, but alas, they do not read well because the eq?-ness of
3094;;; <last-pair> and (last-pair <the-q>) is lost by read. The procedure
3095;;;
3096;;; (sync-q! q)
3097;;;
3098;;; recomputes and resets the <last-pair> component of a queue.
3099;;;
3100
3101(define-public (sync-q! obj) (set-cdr! obj (and (car obj) (last-pair (car obj)))))
3102
3103;;; make-q
3104;;; return a new q.
3105;;;
3106(define-public (make-q) (cons '() '()))
3107
3108;;; q? obj
3109;;; Return true if obj is a Q.
3110;;; An object is a queue if it is equal? to '(#f . #f) or
3111;;; if it is a pair P with (list? (car P)) and (eq? (cdr P) (last-pair P)).
3112;;;
3113(define-public (q? obj) (and (pair? obj)
3114 (or (and (null? (car obj))
3115 (null? (cdr obj)))
3116 (and
3117 (list? (car obj))
3118 (eq? (cdr obj) (last-pair (car obj)))))))
3119
3120;;; q-empty? obj
3121;;;
3122(define-public (q-empty? obj) (null? (car obj)))
3123
3124;;; q-empty-check q
3125;;; Throw a q-empty exception if Q is empty.
3126(define-public (q-empty-check q) (if (q-empty? q) (throw 'q-empty q)))
3127
3128
3129;;; q-front q
3130;;; Return the first element of Q.
3131(define-public (q-front q) (q-empty-check q) (caar q))
3132
3133;;; q-front q
3134;;; Return the last element of Q.
3135(define-public (q-rear q) (q-empty-check q) (cadr q))
3136
3137;;; q-remove! q obj
3138;;; Remove all occurences of obj from Q.
3139(define-public (q-remove! q obj)
3140 (while (memq obj (car q))
3141 (set-car! q (delq! obj (car q))))
3142 (set-cdr! q (last-pair (car q))))
3143
3144;;; q-push! q obj
3145;;; Add obj to the front of Q
3146(define-public (q-push! q d)
3147 (let ((h (cons d (car q))))
3148 (set-car! q h)
3149 (if (null? (cdr q))
3150 (set-cdr! q h))))
3151
3152;;; enq! q obj
3153;;; Add obj to the rear of Q
3154(define-public (enq! q d)
3155 (let ((h (cons d '())))
3156 (if (not (null? (cdr q)))
3157 (set-cdr! (cdr q) h)
3158 (set-car! q h))
3159 (set-cdr! q h)))
3160
3161;;; q-pop! q
3162;;; Take the front of Q and return it.
3163(define-public (q-pop! q)
3164 (q-empty-check q)
3165 (let ((it (caar q))
3166 (next (cdar q)))
3167 (if (not next)
3168 (set-cdr! q #f))
3169 (set-car! q next)
3170 it))
3171
3172;;; deq! q
3173;;; Take the front of Q and return it.
3174(define-public deq! q-pop!)
3175
3176;;; q-length q
3177;;; Return the number of enqueued elements.
3178;;;
3179(define-public (q-length q) (length (car q)))
3180
3181
3182
3183\f
44cf1f0f
JB
3184;;; {The runq data structure}
3185
0f2d19dd
JB
3186(define-module (ice-9 runq)
3187 :use-module (ice-9 q))
3188
0f2d19dd
JB
3189;;;; Copyright (C) 1996 Free Software Foundation, Inc.
3190;;;;
3191;;;; This program is free software; you can redistribute it and/or modify
3192;;;; it under the terms of the GNU General Public License as published by
3193;;;; the Free Software Foundation; either version 2, or (at your option)
3194;;;; any later version.
3195;;;;
3196;;;; This program is distributed in the hope that it will be useful,
3197;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
3198;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
3199;;;; GNU General Public License for more details.
3200;;;;
3201;;;; You should have received a copy of the GNU General Public License
3202;;;; along with this software; see the file COPYING. If not, write to
3203;;;; the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
3204;;;;
3205
0f2d19dd 3206;;;;
0f2d19dd
JB
3207;;;
3208;;; One way to schedule parallel computations in a serial environment is
3209;;; to explicitly divide each task up into small, finite execution time,
3210;;; strips. Then you interleave the execution of strips from various
3211;;; tasks to achieve a kind of parallelism. Runqs are a handy data
3212;;; structure for this style of programming.
3213;;;
3214;;; We use thunks (nullary procedures) and lists of thunks to represent
3215;;; strips. By convention, the return value of a strip-thunk must either
3216;;; be another strip or the value #f.
3217;;;
3218;;; A runq is a procedure that manages a queue of strips. Called with no
3219;;; arguments, it processes one strip from the queue. Called with
3220;;; arguments, the arguments form a control message for the queue. The
3221;;; first argument is a symbol which is the message selector.
3222;;;
3223;;; A strip is processed this way: If the strip is a thunk, the thunk is
3224;;; called -- if it returns a strip, that strip is added back to the
3225;;; queue. To process a strip which is a list of thunks, the CAR of that
3226;;; list is called. After a call to that CAR, there are 0, 1, or 2 strips
3227;;; -- perhaps one returned by the thunk, and perhaps the CDR of the
3228;;; original strip if that CDR is not nil. The runq puts whichever of
3229;;; these strips exist back on the queue. (The exact order in which
3230;;; strips are put back on the queue determines the scheduling behavior of
3231;;; a particular queue -- it's a parameter.)
3232;;;
3233;;;
3234
3235
3236
3237;;;;
3238;;; (runq-control q msg . args)
3239;;;
3240;;; processes in the default way the control messages that
3241;;; can be sent to a runq. Q should be an ordinary
3242;;; Q (see utils/q.scm).
3243;;;
3244;;; The standard runq messages are:
3245;;;
3246;;; 'add! strip0 strip1... ;; to enqueue one or more strips
3247;;; 'enqueue! strip0 strip1... ;; to enqueue one or more strips
3248;;; 'push! strip0 ... ;; add strips to the front of the queue
3249;;; 'empty? ;; true if it is
3250;;; 'length ;; how many strips in the queue?
3251;;; 'kill! ;; empty the queue
3252;;; else ;; throw 'not-understood
3253;;;
3254(define-public (runq-control q msg . args)
3255 (case msg
3256 ((add!) (for-each (lambda (t) (enq! q t)) args) '*unspecified*)
3257 ((enque!) (for-each (lambda (t) (enq! q t)) args) '*unspecified*)
3258 ((push!) (for-each (lambda (t) (q-push! q t)) args) '*unspecified*)
3259 ((empty?) (q-empty? q))
3260 ((length) (q-length q))
3261 ((kill!) (set! q (make-q)))
3262 (else (throw 'not-understood msg args))))
3263
3264(define (run-strip thunk) (catch #t thunk (lambda ign (warn 'runq-strip thunk ign) #f)))
3265
3266;;;;
3267;;; make-void-runq
3268;;;
3269;;; Make a runq that discards all messages except "length", for which
3270;;; it returns 0.
3271;;;
3272(define-public (make-void-runq)
3273 (lambda opts
3274 (and opts
3275 (apply-to-args opts
3276 (lambda (msg . args)
3277 (case msg
3278 ((length) 0)
3279 (else #f)))))))
3280
3281;;;;
3282;;; (make-fair-runq)
3283;;;
3284;;; Returns a runq procedure.
3285;;; Called with no arguments, the procedure processes one strip from the queue.
3286;;; Called with arguments, it uses runq-control.
3287;;;
3288;;; In a fair runq, if a strip returns a new strip X, X is added
3289;;; to the end of the queue, meaning it will be the last to execute
3290;;; of all the remaining procedures.
3291;;;
3292(define-public (make-fair-runq)
3293 (letrec ((q (make-q))
3294 (self
3295 (lambda ctl
3296 (if ctl
3297 (apply runq-control q ctl)
3298 (and (not (q-empty? q))
3299 (let ((next-strip (deq! q)))
3300 (cond
3301 ((procedure? next-strip) (let ((k (run-strip next-strip)))
3302 (and k (enq! q k))))
3303 ((pair? next-strip) (let ((k (run-strip (car next-strip))))
3304 (and k (enq! q k)))
3305 (if (not (null? (cdr next-strip)))
3306 (enq! q (cdr next-strip)))))
3307 self))))))
3308 self))
3309
3310
3311;;;;
3312;;; (make-exclusive-runq)
3313;;;
3314;;; Returns a runq procedure.
3315;;; Called with no arguments, the procedure processes one strip from the queue.
3316;;; Called with arguments, it uses runq-control.
3317;;;
3318;;; In an exclusive runq, if a strip W returns a new strip X, X is added
3319;;; to the front of the queue, meaning it will be the next to execute
3320;;; of all the remaining procedures.
3321;;;
3322;;; An exception to this occurs if W was the CAR of a list of strips.
3323;;; In that case, after the return value of W is pushed onto the front
3324;;; of the queue, the CDR of the list of strips is pushed in front
3325;;; of that (if the CDR is not nil). This way, the rest of the thunks
3326;;; in the list that contained W have priority over the return value of W.
3327;;;
3328(define-public (make-exclusive-runq)
3329 (letrec ((q (make-q))
3330 (self
3331 (lambda ctl
3332 (if ctl
3333 (apply runq-control q ctl)
3334 (and (not (q-empty? q))
3335 (let ((next-strip (deq! q)))
3336 (cond
3337 ((procedure? next-strip) (let ((k (run-strip next-strip)))
3338 (and k (q-push! q k))))
3339 ((pair? next-strip) (let ((k (run-strip (car next-strip))))
3340 (and k (q-push! q k)))
3341 (if (not (null? (cdr next-strip)))
3342 (q-push! q (cdr next-strip)))))
3343 self))))))
3344 self))
3345
3346
3347;;;;
3348;;; (make-subordinate-runq-to superior basic-inferior)
3349;;;
3350;;; Returns a runq proxy for the runq basic-inferior.
3351;;;
3352;;; The proxy watches for operations on the basic-inferior that cause
3353;;; a transition from a queue length of 0 to a non-zero length and
3354;;; vice versa. While the basic-inferior queue is not empty,
3355;;; the proxy installs a task on the superior runq. Each strip
3356;;; of that task processes N strips from the basic-inferior where
3357;;; N is the length of the basic-inferior queue when the proxy
3358;;; strip is entered. [Countless scheduling variations are possible.]
3359;;;
3360(define-public (make-subordinate-runq-to superior-runq basic-runq)
3361 (let ((runq-task (cons #f #f)))
3362 (set-car! runq-task
3363 (lambda ()
3364 (if (basic-runq 'empty?)
3365 (set-cdr! runq-task #f)
3366 (do ((n (basic-runq 'length) (1- n)))
3367 ((<= n 0) #f)
3368 (basic-runq)))))
3369 (letrec ((self
3370 (lambda ctl
3371 (if (not ctl)
3372 (let ((answer (basic-runq)))
3373 (self 'empty?)
3374 answer)
3375 (begin
3376 (case (car ctl)
3377 ((suspend) (set-cdr! runq-task #f))
3378 (else (let ((answer (apply basic-runq ctl)))
3379 (if (and (not (cdr runq-task)) (not (basic-runq 'empty?)))
3380 (begin
3381 (set-cdr! runq-task runq-task)
3382 (superior-runq 'add! runq-task)))
3383 answer))))))))
3384 self)))
3385
3386;;;;
3387;;; (define fork-strips (lambda args args))
3388;;; Return a strip that starts several strips in
3389;;; parallel. If this strip is enqueued on a fair
3390;;; runq, strips of the parallel subtasks will run
3391;;; round-robin style.
3392;;;
3393(define fork-strips (lambda args args))
3394
3395
3396;;;;
3397;;; (strip-sequence . strips)
3398;;;
3399;;; Returns a new strip which is the concatenation of the argument strips.
3400;;;
3401(define-public ((strip-sequence . strips))
3402 (let loop ((st (let ((a strips)) (set! strips #f) a)))
3403 (and (not (null? st))
3404 (let ((then ((car st))))
3405 (if then
3406 (lambda () (loop (cons then (cdr st))))
3407 (lambda () (loop (cdr st))))))))
3408
3409
3410;;;;
3411;;; (fair-strip-subtask . initial-strips)
3412;;;
3413;;; Returns a new strip which is the synchronos, fair,
3414;;; parallel execution of the argument strips.
3415;;;
3416;;;
3417;;;
3418(define-public (fair-strip-subtask . initial-strips)
3419 (let ((st (make-fair-runq)))
3420 (apply st 'add! initial-strips)
3421 st))
3422
3423\f
44cf1f0f 3424;;; {String Fun}
0f2d19dd 3425
0f2d19dd
JB
3426(define-module (ice-9 string-fun))
3427
0f2d19dd 3428;;;;
0f2d19dd
JB
3429;;;
3430;;; Various string funcitons, particularly those that take
3431;;; advantage of the "shared substring" capability.
3432;;;
3433\f
44cf1f0f 3434;;; {String Fun: Dividing Strings Into Fields}
0f2d19dd
JB
3435;;;
3436;;; The names of these functions are very regular.
3437;;; Here is a grammar of a call to one of these:
3438;;;
3439;;; <string-function-invocation>
3440;;; := (<action>-<seperator-disposition>-<seperator-determination> <seperator-param> <str> <ret>)
3441;;;
3442;;; <str> = the string
3443;;;
3444;;; <ret> = The continuation. String functions generally return
3445;;; multiple values by passing them to this procedure.
3446;;;
3447;;; <action> = split
3448;;; | separate-fields
3449;;;
3450;;; "split" means to divide a string into two parts.
3451;;; <ret> will be called with two arguments.
3452;;;
3453;;; "separate-fields" means to divide a string into as many
3454;;; parts as possible. <ret> will be called with
3455;;; however many fields are found.
3456;;;
3457;;; <seperator-disposition> = before
3458;;; | after
3459;;; | discarding
3460;;;
3461;;; "before" means to leave the seperator attached to
3462;;; the beginning of the field to its right.
3463;;; "after" means to leave the seperator attached to
3464;;; the end of the field to its left.
3465;;; "discarding" means to discard seperators.
3466;;;
3467;;; Other dispositions might be handy. For example, "isolate"
3468;;; could mean to treat the separator as a field unto itself.
3469;;;
3470;;; <seperator-determination> = char
3471;;; | predicate
3472;;;
3473;;; "char" means to use a particular character as field seperator.
3474;;; "predicate" means to check each character using a particular predicate.
3475;;;
3476;;; Other determinations might be handy. For example, "character-set-member".
3477;;;
3478;;; <seperator-param> = A parameter that completes the meaning of the determinations.
3479;;; For example, if the determination is "char", then this parameter
3480;;; says which character. If it is "predicate", the parameter is the
3481;;; predicate.
3482;;;
3483;;;
3484;;; For example:
3485;;;
3486;;; (separate-fields-discarding-char #\, "foo, bar, baz, , bat" list)
3487;;; => ("foo" " bar" " baz" " " " bat")
3488;;;
3489;;; (split-after-char #\- 'an-example-of-split list)
3490;;; => ("an-" "example-of-split")
3491;;;
3492;;; As an alternative to using a determination "predicate", or to trying to do anything
3493;;; complicated with these functions, consider using regular expressions.
3494;;;
3495
3496(define-public (split-after-char char str ret)
3497 (let ((end (cond
3498 ((string-index str char) => 1+)
3499 (else (string-length str)))))
3500 (ret (make-shared-substring str 0 end)
3501 (make-shared-substring str end))))
3502
3503(define-public (split-before-char char str ret)
3504 (let ((end (or (string-index str char)
3505 (string-length str))))
3506 (ret (make-shared-substring str 0 end)
3507 (make-shared-substring str end))))
3508
3509(define-public (split-discarding-char char str ret)
3510 (let ((end (string-index str char)))
3511 (if (not end)
3512 (ret str "")
3513 (ret (make-shared-substring str 0 end)
3514 (make-shared-substring str (1+ end))))))
3515
3516(define-public (split-after-char-last char str ret)
3517 (let ((end (cond
3518 ((string-rindex str char) => 1+)
3519 (else 0))))
3520 (ret (make-shared-substring str 0 end)
3521 (make-shared-substring str end))))
3522
3523(define-public (split-before-char-last char str ret)
3524 (let ((end (or (string-rindex str char) 0)))
3525 (ret (make-shared-substring str 0 end)
3526 (make-shared-substring str end))))
3527
3528(define-public (split-discarding-char-last char str ret)
3529 (let ((end (string-rindex str char)))
3530 (if (not end)
3531 (ret str "")
3532 (ret (make-shared-substring str 0 end)
3533 (make-shared-substring str (1+ end))))))
3534
3535(define (split-before-predicate pred str ret)
3536 (let loop ((n 0))
3537 (cond
3538 ((= n (length str)) (ret str ""))
3539 ((not (pred (string-ref str n))) (loop (1+ n)))
3540 (else (ret (make-shared-substring str 0 n)
3541 (make-shared-substring str n))))))
3542(define (split-after-predicate pred str ret)
3543 (let loop ((n 0))
3544 (cond
3545 ((= n (length str)) (ret str ""))
3546 ((not (pred (string-ref str n))) (loop (1+ n)))
3547 (else (ret (make-shared-substring str 0 (1+ n))
3548 (make-shared-substring str (1+ n)))))))
3549
3550(define (split-discarding-predicate pred str ret)
3551 (let loop ((n 0))
3552 (cond
3553 ((= n (length str)) (ret str ""))
3554 ((not (pred (string-ref str n))) (loop (1+ n)))
3555 (else (ret (make-shared-substring str 0 n)
3556 (make-shared-substring str (1+ n)))))))
3557
21ed9efe 3558(define-public (separate-fields-discarding-char ch str ret)
0f2d19dd
JB
3559 (let loop ((fields '())
3560 (str str))
3561 (cond
3562 ((string-rindex str ch)
3563 => (lambda (pos) (loop (cons (make-shared-substring str (+ 1 w)) fields)
3564 (make-shared-substring str 0 w))))
3565 (else (ret (cons str fields))))))
3566
21ed9efe 3567(define-public (separate-fields-after-char ch str ret)
0f2d19dd
JB
3568 (let loop ((fields '())
3569 (str str))
3570 (cond
3571 ((string-rindex str ch)
3572 => (lambda (pos) (loop (cons (make-shared-substring str (+ 1 w)) fields)
3573 (make-shared-substring str 0 (+ 1 w)))))
3574 (else (ret (cons str fields))))))
3575
21ed9efe 3576(define-public (separate-fields-before-char ch str ret)
0f2d19dd
JB
3577 (let loop ((fields '())
3578 (str str))
3579 (cond
3580 ((string-rindex str ch)
3581 => (lambda (pos) (loop (cons (make-shared-substring str w) fields)
3582 (make-shared-substring str 0 w))))
3583 (else (ret (cons str fields))))))
3584
3585\f
44cf1f0f 3586;;; {String Fun: String Prefix Predicates}
0f2d19dd
JB
3587;;;
3588;;; Very simple:
3589;;;
21ed9efe 3590;;; (define-public ((string-prefix-predicate pred?) prefix str)
0f2d19dd
JB
3591;;; (and (<= (length prefix) (length str))
3592;;; (pred? prefix (make-shared-substring str 0 (length prefix)))))
3593;;;
3594;;; (define-public string-prefix=? (string-prefix-predicate string=?))
3595;;;
3596
3597(define-public ((string-prefix-predicate pred?) prefix str)
3598 (and (<= (length prefix) (length str))
3599 (pred? prefix (make-shared-substring str 0 (length prefix)))))
3600
3601(define-public string-prefix=? (string-prefix-predicate string=?))
3602
3603\f
44cf1f0f 3604;;; {String Fun: Strippers}
0f2d19dd
JB
3605;;;
3606;;; <stripper> = sans-<removable-part>
3607;;;
3608;;; <removable-part> = surrounding-whitespace
3609;;; | trailing-whitespace
3610;;; | leading-whitespace
3611;;; | final-newline
3612;;;
3613
3614(define-public (sans-surrounding-whitespace s)
3615 (let ((st 0)
3616 (end (string-length s)))
3617 (while (and (< st (string-length s))
3618 (char-whitespace? (string-ref s st)))
3619 (set! st (1+ st)))
3620 (while (and (< 0 end)
3621 (char-whitespace? (string-ref s (1- end))))
3622 (set! end (1- end)))
3623 (if (< end st)
3624 ""
3625 (make-shared-substring s st end))))
3626
3627(define-public (sans-trailing-whitespace s)
3628 (let ((st 0)
3629 (end (string-length s)))
3630 (while (and (< 0 end)
3631 (char-whitespace? (string-ref s (1- end))))
3632 (set! end (1- end)))
3633 (if (< end st)
3634 ""
3635 (make-shared-substring s st end))))
3636
3637(define-public (sans-leading-whitespace s)
3638 (let ((st 0)
3639 (end (string-length s)))
3640 (while (and (< st (string-length s))
3641 (char-whitespace? (string-ref s st)))
3642 (set! st (1+ st)))
3643 (if (< end st)
3644 ""
3645 (make-shared-substring s st end))))
3646
3647(define-public (sans-final-newline str)
3648 (cond
3649 ((= 0 (string-length str))
3650 str)
3651
3652 ((char=? #\nl (string-ref str (1- (string-length str))))
3653 (make-shared-substring str 0 (1- (string-length str))))
3654
3655 (else str)))
3656\f
44cf1f0f 3657;;; {String Fun: has-trailing-newline?}
0f2d19dd
JB
3658;;;
3659
3660(define-public (has-trailing-newline? str)
3661 (and (< 0 (string-length str))
3662 (char=? #\nl (string-ref str (1- (string-length str))))))
3663
3664
3665\f
44cf1f0f 3666;;; {String Fun: with-regexp-parts}
0f2d19dd
JB
3667
3668(define-public (with-regexp-parts regexp fields str return fail)
3669 (let ((parts (regexec regexp str fields)))
3670 (if (number? parts)
3671 (fail parts)
3672 (apply return parts))))
3673
3674\f
c56634ba
MD
3675;;; {Load debug extension code if debug extensions present.}
3676;;;
3677;;; *fixme* This is a temporary solution.
3678;;;
0f2d19dd 3679
c56634ba 3680(if (memq 'debug-extensions *features*)
90895e5c
MD
3681 (define-module (guile) :use-module (ice-9 debug)))
3682
3683\f
90d5e280
MD
3684;;; {Load session support if present.}
3685;;;
3686;;; *fixme* This is a temporary solution.
3687;;;
3688
3689(if (%search-load-path "ice-9/session.scm")
3690 (define-module (guile) :use-module (ice-9 session)))
3691
3692\f
90895e5c
MD
3693;;; {Load thread code if threads are present.}
3694;;;
3695;;; *fixme* This is a temporary solution.
3696;;;
3697
3698(if (memq 'threads *features*)
3699 (define-module (guile) :use-module (ice-9 threads)))
3700
21ed9efe
MD
3701\f
3702;;; {Load emacs interface support if emacs option is given.}
3703;;;
3704;;; *fixme* This is a temporary solution.
3705;;;
3706
f3c23298 3707(if use-emacs-interface
21ed9efe
MD
3708 (define-module (guile) :use-module (ice-9 emacs)))
3709
3710\f
3711
90895e5c 3712(define-module (guile))
6fa8995c
GH
3713
3714(append! %load-path (cons "." ()))