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