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