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