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