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