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