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