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