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