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