*** empty log message ***
[bpt/guile.git] / ice-9 / boot-9.scm
CommitLineData
0f2d19dd
JB
1;;; installed-scm-file
2
6906bd0d 3;;;; Copyright (C) 1995, 1996, 1997, 1998, 1999, 2000 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
50706e94
JB
37;;; Return #t iff FEATURE is available to this Guile interpreter.
38;;; In SLIB, provided? also checks to see if the module is available.
39;;; We should do that too, but don't.
40(define (provided? feature)
41 (and (memq feature *features*) #t))
42
52cfc69b
GH
43;;; presumably deprecated.
44(define feature? provided?)
45
8641dd9e
GB
46;;; let format alias simple-format until the more complete version is loaded
47(define format simple-format)
48
21ed9efe 49\f
79451588
JB
50;;; {R4RS compliance}
51
52(primitive-load-path "ice-9/r4rs.scm")
53
54\f
44cf1f0f 55;;; {Simple Debugging Tools}
0f2d19dd
JB
56;;
57
58
59;; peek takes any number of arguments, writes them to the
60;; current ouput port, and returns the last argument.
61;; It is handy to wrap around an expression to look at
62;; a value each time is evaluated, e.g.:
63;;
64;; (+ 10 (troublesome-fn))
65;; => (+ 10 (pk 'troublesome-fn-returned (troublesome-fn)))
66;;
67
68(define (peek . stuff)
69 (newline)
70 (display ";;; ")
71 (write stuff)
72 (newline)
73 (car (last-pair stuff)))
74
75(define pk peek)
76
77(define (warn . stuff)
78 (with-output-to-port (current-error-port)
79 (lambda ()
80 (newline)
81 (display ";;; WARNING ")
6355358a 82 (display stuff)
0f2d19dd
JB
83 (newline)
84 (car (last-pair stuff)))))
85
86\f
79451588 87;;; {Trivial Functions}
0f2d19dd 88;;;
79451588
JB
89
90(define (id x) x)
91(define (1+ n) (+ n 1))
92(define (-1+ n) (+ n -1))
93(define 1- -1+)
94(define return-it noop)
132e5fac 95(define (and=> value procedure) (and value (procedure value)))
79451588
JB
96(define (make-hash-table k) (make-vector k '()))
97
0f2d19dd
JB
98;;; apply-to-args is functionally redunant with apply and, worse,
99;;; is less general than apply since it only takes two arguments.
100;;;
101;;; On the other hand, apply-to-args is a syntacticly convenient way to
102;;; perform binding in many circumstances when the "let" family of
103;;; of forms don't cut it. E.g.:
104;;;
105;;; (apply-to-args (return-3d-mouse-coords)
106;;; (lambda (x y z)
107;;; ...))
108;;;
109
110(define (apply-to-args args fn) (apply fn args))
111
112\f
0f2d19dd
JB
113;;; {Integer Math}
114;;;
115
0f2d19dd
JB
116(define (ipow-by-squaring x k acc proc)
117 (cond ((zero? k) acc)
118 ((= 1 k) (proc acc x))
52c5a23a
JB
119 (else (ipow-by-squaring (proc x x)
120 (quotient k 2)
121 (if (even? k) acc (proc acc x))
122 proc))))
0f2d19dd
JB
123
124(define string-character-length string-length)
125
126
127
128;; A convenience function for combining flag bits. Like logior, but
129;; handles the cases of 0 and 1 arguments.
130;;
131(define (flags . args)
132 (cond
133 ((null? args) 0)
134 ((null? (cdr args)) (car args))
135 (else (apply logior args))))
136
137\f
0f2d19dd
JB
138;;; {Symbol Properties}
139;;;
140
141(define (symbol-property sym prop)
142 (let ((pair (assoc prop (symbol-pref sym))))
143 (and pair (cdr pair))))
144
145(define (set-symbol-property! sym prop val)
146 (let ((pair (assoc prop (symbol-pref sym))))
147 (if pair
148 (set-cdr! pair val)
149 (symbol-pset! sym (acons prop val (symbol-pref sym))))))
150
151(define (symbol-property-remove! sym prop)
152 (let ((pair (assoc prop (symbol-pref sym))))
153 (if pair
154 (symbol-pset! sym (delq! pair (symbol-pref sym))))))
155
156\f
1e531c3a
GH
157
158;;; {Line and Delimited I/O}
159
160;;; corresponds to SCM_LINE_INCREMENTORS in libguile.
161(define scm-line-incrementors "\n")
162
163(define (read-line! string . maybe-port)
164 (let* ((port (if (pair? maybe-port)
165 (car maybe-port)
166 (current-input-port))))
167 (let* ((rv (%read-delimited! scm-line-incrementors
168 string
169 #t
170 port))
171 (terminator (car rv))
172 (nchars (cdr rv)))
173 (cond ((and (= nchars 0)
174 (eof-object? terminator))
175 terminator)
176 ((not terminator) #f)
177 (else nchars)))))
178
179(define (read-delimited! delims buf . args)
180 (let* ((num-args (length args))
181 (port (if (> num-args 0)
182 (car args)
183 (current-input-port)))
184 (handle-delim (if (> num-args 1)
185 (cadr args)
186 'trim))
187 (start (if (> num-args 2)
188 (caddr args)
189 0))
190 (end (if (> num-args 3)
191 (cadddr args)
192 (string-length buf))))
193 (let* ((rv (%read-delimited! delims
194 buf
195 (not (eq? handle-delim 'peek))
196 port
197 start
198 end))
199 (terminator (car rv))
200 (nchars (cdr rv)))
201 (cond ((or (not terminator) ; buffer filled
202 (eof-object? terminator))
203 (if (zero? nchars)
204 (if (eq? handle-delim 'split)
205 (cons terminator terminator)
206 terminator)
207 (if (eq? handle-delim 'split)
208 (cons nchars terminator)
209 nchars)))
210 (else
211 (case handle-delim
212 ((trim peek) nchars)
e3306d80 213 ((concat) (string-set! buf (+ nchars start) terminator)
1e531c3a
GH
214 (+ nchars 1))
215 ((split) (cons nchars terminator))
216 (else (error "unexpected handle-delim value: "
217 handle-delim))))))))
218
219(define (read-delimited delims . args)
220 (let* ((port (if (pair? args)
221 (let ((pt (car args)))
222 (set! args (cdr args))
223 pt)
224 (current-input-port)))
225 (handle-delim (if (pair? args)
226 (car args)
227 'trim)))
228 (let loop ((substrings ())
229 (total-chars 0)
230 (buf-size 100)) ; doubled each time through.
231 (let* ((buf (make-string buf-size))
232 (rv (%read-delimited! delims
233 buf
234 (not (eq? handle-delim 'peek))
235 port))
236 (terminator (car rv))
237 (nchars (cdr rv))
238 (join-substrings
239 (lambda ()
240 (apply string-append
241 (reverse
242 (cons (if (and (eq? handle-delim 'concat)
243 (not (eof-object? terminator)))
244 (string terminator)
245 "")
246 (cons (make-shared-substring buf 0 nchars)
247 substrings))))))
248 (new-total (+ total-chars nchars)))
249 (cond ((not terminator)
250 ;; buffer filled.
251 (loop (cons (substring buf 0 nchars) substrings)
252 new-total
253 (* buf-size 2)))
254 ((eof-object? terminator)
255 (if (zero? new-total)
256 (if (eq? handle-delim 'split)
257 (cons terminator terminator)
258 terminator)
259 (if (eq? handle-delim 'split)
260 (cons (join-substrings) terminator)
261 (join-substrings))))
262 (else
263 (case handle-delim
264 ((trim peek concat) (join-substrings))
265 ((split) (cons (join-substrings) terminator))
848f2a01
TP
266
267
1e531c3a
GH
268 (else (error "unexpected handle-delim value: "
269 handle-delim)))))))))
848f2a01
TP
270
271;;; read-line [PORT [HANDLE-DELIM]] reads a newline-terminated string
272;;; from PORT. The return value depends on the value of HANDLE-DELIM,
273;;; which may be one of the symbols `trim', `concat', `peek' and
274;;; `split'. If it is `trim' (the default), the trailing newline is
275;;; removed and the string is returned. If `concat', the string is
276;;; returned with the trailing newline intact. If `peek', the newline
277;;; is left in the input port buffer and the string is returned. If
278;;; `split', the newline is split from the string and read-line
279;;; returns a pair consisting of the truncated string and the newline.
280
1e531c3a 281(define (read-line . args)
848f2a01
TP
282 (let* ((port (if (null? args)
283 (current-input-port)
284 (car args)))
285 (handle-delim (if (> (length args) 1)
286 (cadr args)
287 'trim))
288 (line/delim (%read-line port))
289 (line (car line/delim))
290 (delim (cdr line/delim)))
291 (case handle-delim
292 ((trim) line)
293 ((split) line/delim)
294 ((concat) (if (and (string? line) (char? delim))
295 (string-append line (string delim))
296 line))
297 ((peek) (if (char? delim)
298 (unread-char delim port))
299 line)
300 (else
301 (error "unexpected handle-delim value: " handle-delim)))))
1e531c3a
GH
302
303\f
0f2d19dd
JB
304;;; {Arrays}
305;;;
306
afe5177e
GH
307(if (provided? 'array)
308 (primitive-load-path "ice-9/arrays.scm"))
0f2d19dd
JB
309
310\f
311;;; {Keywords}
312;;;
313
314(define (symbol->keyword symbol)
315 (make-keyword-from-dash-symbol (symbol-append '- symbol)))
316
317(define (keyword->symbol kw)
318 (let ((sym (keyword-dash-symbol kw)))
11b05261 319 (string->symbol (substring sym 1 (string-length sym)))))
0f2d19dd
JB
320
321(define (kw-arg-ref args kw)
322 (let ((rem (member kw args)))
323 (and rem (pair? (cdr rem)) (cadr rem))))
324
325\f
fa7e9274 326
9f9aa47b 327;;; {Structs}
fa7e9274
MV
328
329(define (struct-layout s)
9f9aa47b 330 (struct-ref (struct-vtable s) vtable-index-layout))
fa7e9274
MV
331
332\f
0f2d19dd
JB
333;;; {Records}
334;;;
335
fa7e9274
MV
336;; Printing records: by default, records are printed as
337;;
338;; #<type-name field1: val1 field2: val2 ...>
339;;
340;; You can change that by giving a custom printing function to
341;; MAKE-RECORD-TYPE (after the list of field symbols). This function
342;; will be called like
343;;
344;; (<printer> object port)
345;;
346;; It should print OBJECT to PORT.
347
cf8f1a90 348(define (inherit-print-state old-port new-port)
8a30733e
MD
349 (if (get-print-state old-port)
350 (port-with-print-state new-port (get-print-state old-port))
cf8f1a90
MV
351 new-port))
352
9f9aa47b 353;; 0: type-name, 1: fields
fa7e9274 354(define record-type-vtable
9f9aa47b
MD
355 (make-vtable-vtable "prpr" 0
356 (lambda (s p)
357 (cond ((eq? s record-type-vtable)
358 (display "#<record-type-vtable>" p))
359 (else
360 (display "#<record-type " p)
361 (display (record-type-name s) p)
362 (display ">" p))))))
0f2d19dd
JB
363
364(define (record-type? obj)
365 (and (struct? obj) (eq? record-type-vtable (struct-vtable obj))))
366
367(define (make-record-type type-name fields . opt)
8e693424 368 (let ((printer-fn (and (pair? opt) (car opt))))
0f2d19dd 369 (let ((struct (make-struct record-type-vtable 0
c7c03b9f
JB
370 (make-struct-layout
371 (apply symbol-append
372 (map (lambda (f) "pw") fields)))
9f9aa47b
MD
373 (or printer-fn
374 (lambda (s p)
375 (display "#<" p)
376 (display type-name p)
377 (let loop ((fields fields)
378 (off 0))
379 (cond
380 ((not (null? fields))
381 (display " " p)
382 (display (car fields) p)
383 (display ": " p)
384 (display (struct-ref s off) p)
385 (loop (cdr fields) (+ 1 off)))))
386 (display ">" p)))
0f2d19dd
JB
387 type-name
388 (copy-tree fields))))
c8eed875
MD
389 ;; Temporary solution: Associate a name to the record type descriptor
390 ;; so that the object system can create a wrapper class for it.
391 (set-struct-vtable-name! struct (if (symbol? type-name)
392 type-name
393 (string->symbol type-name)))
0f2d19dd
JB
394 struct)))
395
396(define (record-type-name obj)
397 (if (record-type? obj)
9f9aa47b 398 (struct-ref obj vtable-offset-user)
0f2d19dd
JB
399 (error 'not-a-record-type obj)))
400
401(define (record-type-fields obj)
402 (if (record-type? obj)
9f9aa47b 403 (struct-ref obj (+ 1 vtable-offset-user))
0f2d19dd
JB
404 (error 'not-a-record-type obj)))
405
406(define (record-constructor rtd . opt)
8e693424 407 (let ((field-names (if (pair? opt) (car opt) (record-type-fields rtd))))
0f2d19dd
JB
408 (eval `(lambda ,field-names
409 (make-struct ',rtd 0 ,@(map (lambda (f)
410 (if (memq f field-names)
411 f
412 #f))
413 (record-type-fields rtd)))))))
414
415(define (record-predicate rtd)
416 (lambda (obj) (and (struct? obj) (eq? rtd (struct-vtable obj)))))
417
418(define (record-accessor rtd field-name)
419 (let* ((pos (list-index (record-type-fields rtd) field-name)))
420 (if (not pos)
421 (error 'no-such-field field-name))
422 (eval `(lambda (obj)
423 (and (eq? ',rtd (record-type-descriptor obj))
424 (struct-ref obj ,pos))))))
425
426(define (record-modifier rtd field-name)
427 (let* ((pos (list-index (record-type-fields rtd) field-name)))
428 (if (not pos)
429 (error 'no-such-field field-name))
430 (eval `(lambda (obj val)
431 (and (eq? ',rtd (record-type-descriptor obj))
432 (struct-set! obj ,pos val))))))
433
434
435(define (record? obj)
436 (and (struct? obj) (record-type? (struct-vtable obj))))
437
438(define (record-type-descriptor obj)
439 (if (struct? obj)
440 (struct-vtable obj)
441 (error 'not-a-record obj)))
442
21ed9efe
MD
443(provide 'record)
444
0f2d19dd
JB
445\f
446;;; {Booleans}
447;;;
448
449(define (->bool x) (not (not x)))
450
451\f
452;;; {Symbols}
453;;;
454
455(define (symbol-append . args)
456 (string->symbol (apply string-append args)))
457
458(define (list->symbol . args)
459 (string->symbol (apply list->string args)))
460
461(define (symbol . args)
462 (string->symbol (apply string args)))
463
464(define (obarray-symbol-append ob . args)
465 (string->obarray-symbol (apply string-append ob args)))
466
e672f1b5
MD
467(define (obarray-gensym obarray . opt)
468 (if (null? opt)
469 (gensym "%%gensym" obarray)
470 (gensym (car opt) obarray)))
0f2d19dd
JB
471
472\f
473;;; {Lists}
474;;;
475
476(define (list-index l k)
477 (let loop ((n 0)
478 (l l))
479 (and (not (null? l))
480 (if (eq? (car l) k)
481 n
482 (loop (+ n 1) (cdr l))))))
483
75fd4fb6
JB
484(define (make-list n . init)
485 (if (pair? init) (set! init (car init)))
0f2d19dd
JB
486 (let loop ((answer '())
487 (n n))
488 (if (<= n 0)
489 answer
490 (loop (cons init answer) (- n 1)))))
491
492
493\f
1729d8ff
MD
494;;; {Multiple return values}
495
496(define *values-rtd*
497 (make-record-type "values"
498 '(values)))
499
500(define values
501 (let ((make-values (record-constructor *values-rtd*)))
502 (lambda x
503 (if (and (not (null? x))
504 (null? (cdr x)))
505 (car x)
506 (make-values x)))))
507
508(define call-with-values
509 (let ((access-values (record-accessor *values-rtd* 'values))
510 (values-predicate? (record-predicate *values-rtd*)))
511 (lambda (producer consumer)
512 (let ((result (producer)))
513 (if (values-predicate? result)
514 (apply consumer (access-values result))
515 (consumer result))))))
516
87cfc5da 517(provide 'values)
1729d8ff
MD
518
519\f
3e3cec45 520;;; {and-map and or-map}
0f2d19dd
JB
521;;;
522;;; (and-map fn lst) is like (and (fn (car lst)) (fn (cadr lst)) (fn...) ...)
523;;; (or-map fn lst) is like (or (fn (car lst)) (fn (cadr lst)) (fn...) ...)
524;;; (map-in-order fn lst) is like (map fn lst) but definately in order of lst.
525;;;
526
527;; and-map f l
528;;
529;; Apply f to successive elements of l until exhaustion or f returns #f.
530;; If returning early, return #f. Otherwise, return the last value returned
531;; by f. If f has never been called because l is empty, return #t.
532;;
533(define (and-map f lst)
534 (let loop ((result #t)
535 (l lst))
536 (and result
537 (or (and (null? l)
538 result)
539 (loop (f (car l)) (cdr l))))))
540
541;; or-map f l
542;;
543;; Apply f to successive elements of l until exhaustion or while f returns #f.
544;; If returning early, return the return value of f.
545;;
546(define (or-map f lst)
547 (let loop ((result #f)
548 (l lst))
549 (or result
550 (and (not (null? l))
551 (loop (f (car l)) (cdr l))))))
552
59e1116d 553\f
0f2d19dd 554
52cfc69b
GH
555(if (provided? 'posix)
556 (primitive-load-path "ice-9/posix.scm"))
6fa8995c 557
52cfc69b
GH
558(if (provided? 'socket)
559 (primitive-load-path "ice-9/networking.scm"))
3afb28ce 560
6fa8995c 561(define file-exists?
52cfc69b 562 (if (provided? 'posix)
6fa8995c
GH
563 (lambda (str)
564 (access? str F_OK))
565 (lambda (str)
566 (let ((port (catch 'system-error (lambda () (open-file str OPEN_READ))
567 (lambda args #f))))
568 (if port (begin (close-port port) #t)
569 #f)))))
570
571(define file-is-directory?
52cfc69b 572 (if (provided? 'posix)
6fa8995c 573 (lambda (str)
3afb28ce 574 (eq? (stat:type (stat str)) 'directory))
6fa8995c 575 (lambda (str)
6fa8995c
GH
576 (let ((port (catch 'system-error
577 (lambda () (open-file (string-append str "/.")
578 OPEN_READ))
579 (lambda args #f))))
580 (if port (begin (close-port port) #t)
581 #f)))))
0f2d19dd
JB
582
583(define (has-suffix? str suffix)
584 (let ((sufl (string-length suffix))
585 (sl (string-length str)))
586 (and (> sl sufl)
587 (string=? (substring str (- sl sufl) sl) suffix))))
588
0f2d19dd
JB
589\f
590;;; {Error Handling}
591;;;
592
0f2d19dd 593(define (error . args)
21ed9efe 594 (save-stack)
2194b6f0 595 (if (null? args)
5552355a 596 (scm-error 'misc-error #f "?" #f #f)
8641dd9e 597 (let loop ((msg "~A")
2194b6f0
GH
598 (rest (cdr args)))
599 (if (not (null? rest))
8641dd9e 600 (loop (string-append msg " ~S")
2194b6f0 601 (cdr rest))
5552355a 602 (scm-error 'misc-error #f msg args #f)))))
be2d2c70 603
1349bd53 604;; bad-throw is the hook that is called upon a throw to a an unhandled
9a0d70e2
GH
605;; key (unless the throw has four arguments, in which case
606;; it's usually interpreted as an error throw.)
607;; If the key has a default handler (a throw-handler-default property),
0f2d19dd
JB
608;; it is applied to the throw.
609;;
1349bd53 610(define (bad-throw key . args)
0f2d19dd
JB
611 (let ((default (symbol-property key 'throw-handler-default)))
612 (or (and default (apply default key args))
2194b6f0 613 (apply error "unhandled-exception:" key args))))
0f2d19dd 614
0f2d19dd 615\f
bce074ee 616
708bf0f3
GH
617(define (tm:sec obj) (vector-ref obj 0))
618(define (tm:min obj) (vector-ref obj 1))
619(define (tm:hour obj) (vector-ref obj 2))
620(define (tm:mday obj) (vector-ref obj 3))
621(define (tm:mon obj) (vector-ref obj 4))
622(define (tm:year obj) (vector-ref obj 5))
623(define (tm:wday obj) (vector-ref obj 6))
624(define (tm:yday obj) (vector-ref obj 7))
625(define (tm:isdst obj) (vector-ref obj 8))
626(define (tm:gmtoff obj) (vector-ref obj 9))
627(define (tm:zone obj) (vector-ref obj 10))
628
629(define (set-tm:sec obj val) (vector-set! obj 0 val))
630(define (set-tm:min obj val) (vector-set! obj 1 val))
631(define (set-tm:hour obj val) (vector-set! obj 2 val))
632(define (set-tm:mday obj val) (vector-set! obj 3 val))
633(define (set-tm:mon obj val) (vector-set! obj 4 val))
634(define (set-tm:year obj val) (vector-set! obj 5 val))
635(define (set-tm:wday obj val) (vector-set! obj 6 val))
636(define (set-tm:yday obj val) (vector-set! obj 7 val))
637(define (set-tm:isdst obj val) (vector-set! obj 8 val))
638(define (set-tm:gmtoff obj val) (vector-set! obj 9 val))
639(define (set-tm:zone obj val) (vector-set! obj 10 val))
640
6afcd3b2
GH
641(define (tms:clock obj) (vector-ref obj 0))
642(define (tms:utime obj) (vector-ref obj 1))
643(define (tms:stime obj) (vector-ref obj 2))
644(define (tms:cutime obj) (vector-ref obj 3))
645(define (tms:cstime obj) (vector-ref obj 4))
646
bce074ee
GH
647(define (file-position . args) (apply ftell args))
648(define (file-set-position . args) (apply fseek args))
8b13c6b3 649
e38303a2
GH
650(define (move->fdes fd/port fd)
651 (cond ((integer? fd/port)
7a6f1ffa 652 (dup->fdes fd/port fd)
e38303a2
GH
653 (close fd/port)
654 fd)
655 (else
656 (primitive-move->fdes fd/port fd)
657 (set-port-revealed! fd/port 1)
658 fd/port)))
8b13c6b3
GH
659
660(define (release-port-handle port)
661 (let ((revealed (port-revealed port)))
662 (if (> revealed 0)
663 (set-port-revealed! port (- revealed 1)))))
0f2d19dd 664
e38303a2 665(define (dup->port port/fd mode . maybe-fd)
7a6f1ffa 666 (let ((port (fdopen (apply dup->fdes port/fd maybe-fd)
e38303a2
GH
667 mode)))
668 (if (pair? maybe-fd)
669 (set-port-revealed! port 1))
670 port))
671
672(define (dup->inport port/fd . maybe-fd)
673 (apply dup->port port/fd "r" maybe-fd))
674
675(define (dup->outport port/fd . maybe-fd)
676 (apply dup->port port/fd "w" maybe-fd))
677
e38303a2
GH
678(define (dup port/fd . maybe-fd)
679 (if (integer? port/fd)
680 (apply dup->fdes port/fd maybe-fd)
681 (apply dup->port port/fd (port-mode port/fd) maybe-fd)))
682
683(define (duplicate-port port modes)
684 (dup->port port modes))
685
686(define (fdes->inport fdes)
687 (let loop ((rest-ports (fdes->ports fdes)))
688 (cond ((null? rest-ports)
689 (let ((result (fdopen fdes "r")))
690 (set-port-revealed! result 1)
691 result))
692 ((input-port? (car rest-ports))
693 (set-port-revealed! (car rest-ports)
694 (+ (port-revealed (car rest-ports)) 1))
695 (car rest-ports))
696 (else
697 (loop (cdr rest-ports))))))
698
699(define (fdes->outport fdes)
700 (let loop ((rest-ports (fdes->ports fdes)))
701 (cond ((null? rest-ports)
702 (let ((result (fdopen fdes "w")))
703 (set-port-revealed! result 1)
704 result))
705 ((output-port? (car rest-ports))
706 (set-port-revealed! (car rest-ports)
707 (+ (port-revealed (car rest-ports)) 1))
708 (car rest-ports))
709 (else
710 (loop (cdr rest-ports))))))
711
712(define (port->fdes port)
713 (set-port-revealed! port (+ (port-revealed port) 1))
714 (fileno port))
715
956055a9
GH
716(define (setenv name value)
717 (if value
718 (putenv (string-append name "=" value))
719 (putenv name)))
720
0f2d19dd
JB
721\f
722;;; {Load Paths}
723;;;
724
0f2d19dd
JB
725;;; Here for backward compatability
726;;
727(define scheme-file-suffix (lambda () ".scm"))
728
3cab8392
JB
729(define (in-vicinity vicinity file)
730 (let ((tail (let ((len (string-length vicinity)))
534a0099
MD
731 (if (zero? len)
732 #f
3cab8392
JB
733 (string-ref vicinity (- len 1))))))
734 (string-append vicinity
534a0099
MD
735 (if (or (not tail)
736 (eq? tail #\/))
737 ""
738 "/")
3cab8392 739 file)))
02ceadb8 740
0f2d19dd 741\f
ef00e7f4
JB
742;;; {Help for scm_shell}
743;;; The argument-processing code used by Guile-based shells generates
744;;; Scheme code based on the argument list. This page contains help
745;;; functions for the code it generates.
746
ef00e7f4
JB
747(define (command-line) (program-arguments))
748
5aa7fe69
JB
749;; This is mostly for the internal use of the code generated by
750;; scm_compile_shell_switches.
ef00e7f4 751(define (load-user-init)
1f08acd9
GH
752 (let* ((home (or (getenv "HOME")
753 (false-if-exception (passwd:dir (getpwuid (getuid))))
754 "/")) ;; fallback for cygwin etc.
755 (init-file (in-vicinity home ".guile")))
756 (if (file-exists? init-file)
757 (primitive-load init-file))))
ef00e7f4
JB
758
759\f
a06181a2
JB
760;;; {Loading by paths}
761
762;;; Load a Scheme source file named NAME, searching for it in the
763;;; directories listed in %load-path, and applying each of the file
764;;; name extensions listed in %load-extensions.
765(define (load-from-path name)
766 (start-stack 'load-stack
75a97b92 767 (primitive-load-path name)))
0f2d19dd 768
5552355a 769
0f2d19dd 770\f
0f2d19dd
JB
771;;; {Transcendental Functions}
772;;;
773;;; Derived from "Transcen.scm", Complex trancendental functions for SCM.
0543c9b7 774;;; Written by Jerry D. Hedden, (C) FSF.
0f2d19dd
JB
775;;; See the file `COPYING' for terms applying to this program.
776;;;
777
778(define (exp z)
779 (if (real? z) ($exp z)
780 (make-polar ($exp (real-part z)) (imag-part z))))
781
782(define (log z)
783 (if (and (real? z) (>= z 0))
784 ($log z)
785 (make-rectangular ($log (magnitude z)) (angle z))))
786
787(define (sqrt z)
788 (if (real? z)
789 (if (negative? z) (make-rectangular 0 ($sqrt (- z)))
790 ($sqrt z))
791 (make-polar ($sqrt (magnitude z)) (/ (angle z) 2))))
792
793(define expt
794 (let ((integer-expt integer-expt))
795 (lambda (z1 z2)
796 (cond ((exact? z2)
797 (integer-expt z1 z2))
798 ((and (real? z2) (real? z1) (>= z1 0))
799 ($expt z1 z2))
800 (else
801 (exp (* z2 (log z1))))))))
802
803(define (sinh z)
804 (if (real? z) ($sinh z)
805 (let ((x (real-part z)) (y (imag-part z)))
806 (make-rectangular (* ($sinh x) ($cos y))
807 (* ($cosh x) ($sin y))))))
808(define (cosh z)
809 (if (real? z) ($cosh z)
810 (let ((x (real-part z)) (y (imag-part z)))
811 (make-rectangular (* ($cosh x) ($cos y))
812 (* ($sinh x) ($sin y))))))
813(define (tanh z)
814 (if (real? z) ($tanh z)
815 (let* ((x (* 2 (real-part z)))
816 (y (* 2 (imag-part z)))
817 (w (+ ($cosh x) ($cos y))))
818 (make-rectangular (/ ($sinh x) w) (/ ($sin y) w)))))
819
820(define (asinh z)
821 (if (real? z) ($asinh z)
822 (log (+ z (sqrt (+ (* z z) 1))))))
823
824(define (acosh z)
825 (if (and (real? z) (>= z 1))
826 ($acosh z)
827 (log (+ z (sqrt (- (* z z) 1))))))
828
829(define (atanh z)
830 (if (and (real? z) (> z -1) (< z 1))
831 ($atanh z)
832 (/ (log (/ (+ 1 z) (- 1 z))) 2)))
833
834(define (sin z)
835 (if (real? z) ($sin z)
836 (let ((x (real-part z)) (y (imag-part z)))
837 (make-rectangular (* ($sin x) ($cosh y))
838 (* ($cos x) ($sinh y))))))
839(define (cos z)
840 (if (real? z) ($cos z)
841 (let ((x (real-part z)) (y (imag-part z)))
842 (make-rectangular (* ($cos x) ($cosh y))
843 (- (* ($sin x) ($sinh y)))))))
844(define (tan z)
845 (if (real? z) ($tan z)
846 (let* ((x (* 2 (real-part z)))
847 (y (* 2 (imag-part z)))
848 (w (+ ($cos x) ($cosh y))))
849 (make-rectangular (/ ($sin x) w) (/ ($sinh y) w)))))
850
851(define (asin z)
852 (if (and (real? z) (>= z -1) (<= z 1))
853 ($asin z)
854 (* -i (asinh (* +i z)))))
855
856(define (acos z)
857 (if (and (real? z) (>= z -1) (<= z 1))
858 ($acos z)
859 (+ (/ (angle -1) 2) (* +i (asinh (* +i z))))))
860
861(define (atan z . y)
862 (if (null? y)
863 (if (real? z) ($atan z)
864 (/ (log (/ (- +i z) (+ +i z))) +2i))
865 ($atan2 z (car y))))
866
65495221
GH
867(define (log10 arg)
868 (/ (log arg) (log 10)))
869
0f2d19dd 870\f
0f2d19dd
JB
871
872;;; {Reader Extensions}
873;;;
874
875;;; Reader code for various "#c" forms.
876;;;
877
75a97b92
GH
878(read-hash-extend #\' (lambda (c port)
879 (read port)))
880(read-hash-extend #\. (lambda (c port)
881 (eval (read port))))
882
0f2d19dd
JB
883\f
884;;; {Command Line Options}
885;;;
886
887(define (get-option argv kw-opts kw-args return)
888 (cond
889 ((null? argv)
890 (return #f #f argv))
891
892 ((or (not (eq? #\- (string-ref (car argv) 0)))
893 (eq? (string-length (car argv)) 1))
894 (return 'normal-arg (car argv) (cdr argv)))
895
896 ((eq? #\- (string-ref (car argv) 1))
897 (let* ((kw-arg-pos (or (string-index (car argv) #\=)
898 (string-length (car argv))))
899 (kw (symbol->keyword (substring (car argv) 2 kw-arg-pos)))
900 (kw-opt? (member kw kw-opts))
901 (kw-arg? (member kw kw-args))
902 (arg (or (and (not (eq? kw-arg-pos (string-length (car argv))))
903 (substring (car argv)
904 (+ kw-arg-pos 1)
905 (string-length (car argv))))
906 (and kw-arg?
907 (begin (set! argv (cdr argv)) (car argv))))))
908 (if (or kw-opt? kw-arg?)
909 (return kw arg (cdr argv))
910 (return 'usage-error kw (cdr argv)))))
911
912 (else
913 (let* ((char (substring (car argv) 1 2))
914 (kw (symbol->keyword char)))
915 (cond
916
917 ((member kw kw-opts)
918 (let* ((rest-car (substring (car argv) 2 (string-length (car argv))))
919 (new-argv (if (= 0 (string-length rest-car))
920 (cdr argv)
921 (cons (string-append "-" rest-car) (cdr argv)))))
922 (return kw #f new-argv)))
923
924 ((member kw kw-args)
925 (let* ((rest-car (substring (car argv) 2 (string-length (car argv))))
926 (arg (if (= 0 (string-length rest-car))
927 (cadr argv)
928 rest-car))
929 (new-argv (if (= 0 (string-length rest-car))
930 (cddr argv)
931 (cdr argv))))
932 (return kw arg new-argv)))
933
934 (else (return 'usage-error kw argv)))))))
935
936(define (for-next-option proc argv kw-opts kw-args)
937 (let loop ((argv argv))
938 (get-option argv kw-opts kw-args
939 (lambda (opt opt-arg argv)
940 (and opt (proc opt opt-arg argv loop))))))
941
942(define (display-usage-report kw-desc)
943 (for-each
944 (lambda (kw)
945 (or (eq? (car kw) #t)
946 (eq? (car kw) 'else)
947 (let* ((opt-desc kw)
948 (help (cadr opt-desc))
949 (opts (car opt-desc))
950 (opts-proper (if (string? (car opts)) (cdr opts) opts))
951 (arg-name (if (string? (car opts))
952 (string-append "<" (car opts) ">")
953 ""))
954 (left-part (string-append
955 (with-output-to-string
956 (lambda ()
957 (map (lambda (x) (display (keyword-symbol x)) (display " "))
958 opts-proper)))
959 arg-name))
11b05261
MD
960 (middle-part (if (and (< (string-length left-part) 30)
961 (< (string-length help) 40))
962 (make-string (- 30 (string-length left-part)) #\ )
0f2d19dd
JB
963 "\n\t")))
964 (display left-part)
965 (display middle-part)
966 (display help)
967 (newline))))
968 kw-desc))
969
970
971
0f2d19dd
JB
972(define (transform-usage-lambda cases)
973 (let* ((raw-usage (delq! 'else (map car cases)))
974 (usage-sans-specials (map (lambda (x)
975 (or (and (not (list? x)) x)
976 (and (symbol? (car x)) #t)
977 (and (boolean? (car x)) #t)
978 x))
979 raw-usage))
ed440df5 980 (usage-desc (delq! #t usage-sans-specials))
0f2d19dd
JB
981 (kw-desc (map car usage-desc))
982 (kw-opts (apply append (map (lambda (x) (and (not (string? (car x))) x)) kw-desc)))
983 (kw-args (apply append (map (lambda (x) (and (string? (car x)) (cdr x))) kw-desc)))
984 (transmogrified-cases (map (lambda (case)
985 (cons (let ((opts (car case)))
986 (if (or (boolean? opts) (eq? 'else opts))
987 opts
988 (cond
989 ((symbol? (car opts)) opts)
990 ((boolean? (car opts)) opts)
991 ((string? (caar opts)) (cdar opts))
992 (else (car opts)))))
993 (cdr case)))
994 cases)))
995 `(let ((%display-usage (lambda () (display-usage-report ',usage-desc))))
996 (lambda (%argv)
997 (let %next-arg ((%argv %argv))
998 (get-option %argv
999 ',kw-opts
1000 ',kw-args
1001 (lambda (%opt %arg %new-argv)
1002 (case %opt
1003 ,@ transmogrified-cases))))))))
1004
1005
1006\f
1007
1008;;; {Low Level Modules}
1009;;;
1010;;; These are the low level data structures for modules.
1011;;;
1012;;; !!! warning: The interface to lazy binder procedures is going
1013;;; to be changed in an incompatible way to permit all the basic
1014;;; module ops to be virtualized.
1015;;;
1016;;; (make-module size use-list lazy-binding-proc) => module
1017;;; module-{obarray,uses,binder}[|-set!]
1018;;; (module? obj) => [#t|#f]
1019;;; (module-locally-bound? module symbol) => [#t|#f]
1020;;; (module-bound? module symbol) => [#t|#f]
1021;;; (module-symbol-locally-interned? module symbol) => [#t|#f]
1022;;; (module-symbol-interned? module symbol) => [#t|#f]
1023;;; (module-local-variable module symbol) => [#<variable ...> | #f]
1024;;; (module-variable module symbol) => [#<variable ...> | #f]
1025;;; (module-symbol-binding module symbol opt-value)
1026;;; => [ <obj> | opt-value | an error occurs ]
1027;;; (module-make-local-var! module symbol) => #<variable...>
1028;;; (module-add! module symbol var) => unspecified
1029;;; (module-remove! module symbol) => unspecified
1030;;; (module-for-each proc module) => unspecified
1031;;; (make-scm-module) => module ; a lazy copy of the symhash module
1032;;; (set-current-module module) => unspecified
1033;;; (current-module) => #<module...>
1034;;;
1035;;;
1036
1037\f
44cf1f0f
JB
1038;;; {Printing Modules}
1039;; This is how modules are printed. You can re-define it.
fa7e9274
MV
1040;; (Redefining is actually more complicated than simply redefining
1041;; %print-module because that would only change the binding and not
1042;; the value stored in the vtable that determines how record are
1043;; printed. Sigh.)
1044
1045(define (%print-module mod port) ; unused args: depth length style table)
0f2d19dd
JB
1046 (display "#<" port)
1047 (display (or (module-kind mod) "module") port)
1048 (let ((name (module-name mod)))
1049 (if name
1050 (begin
1051 (display " " port)
1052 (display name port))))
1053 (display " " port)
1054 (display (number->string (object-address mod) 16) port)
1055 (display ">" port))
1056
1057;; module-type
1058;;
1059;; A module is characterized by an obarray in which local symbols
1060;; are interned, a list of modules, "uses", from which non-local
1061;; bindings can be inherited, and an optional lazy-binder which
31d50456 1062;; is a (CLOSURE module symbol) which, as a last resort, can provide
0f2d19dd
JB
1063;; bindings that would otherwise not be found locally in the module.
1064;;
1065(define module-type
7a0ff2f8 1066 (make-record-type 'module
1777c18b
MD
1067 '(obarray uses binder eval-closure transformer name kind
1068 observers weak-observers observer-id)
8b718458 1069 %print-module))
0f2d19dd 1070
8b718458 1071;; make-module &opt size uses binder
0f2d19dd 1072;;
8b718458
JB
1073;; Create a new module, perhaps with a particular size of obarray,
1074;; initial uses list, or binding procedure.
0f2d19dd 1075;;
0f2d19dd
JB
1076(define make-module
1077 (lambda args
0f2d19dd 1078
8b718458
JB
1079 (define (parse-arg index default)
1080 (if (> (length args) index)
1081 (list-ref args index)
1082 default))
1083
1084 (if (> (length args) 3)
1085 (error "Too many args to make-module." args))
0f2d19dd 1086
8b718458
JB
1087 (let ((size (parse-arg 0 1021))
1088 (uses (parse-arg 1 '()))
1089 (binder (parse-arg 2 #f)))
0f2d19dd 1090
8b718458
JB
1091 (if (not (integer? size))
1092 (error "Illegal size to make-module." size))
1093 (if (not (and (list? uses)
1094 (and-map module? uses)))
1095 (error "Incorrect use list." uses))
0f2d19dd
JB
1096 (if (and binder (not (procedure? binder)))
1097 (error
1098 "Lazy-binder expected to be a procedure or #f." binder))
1099
8b718458 1100 (let ((module (module-constructor (make-vector size '())
1777c18b
MD
1101 uses binder #f #f #f #f
1102 '()
1103 (make-weak-value-hash-table 31)
1104 0)))
8b718458
JB
1105
1106 ;; We can't pass this as an argument to module-constructor,
1107 ;; because we need it to close over a pointer to the module
1108 ;; itself.
6906bd0d 1109 (set-module-eval-closure! module (standard-eval-closure module))
8b718458
JB
1110
1111 module))))
0f2d19dd 1112
8b718458 1113(define module-constructor (record-constructor module-type))
0f2d19dd
JB
1114(define module-obarray (record-accessor module-type 'obarray))
1115(define set-module-obarray! (record-modifier module-type 'obarray))
1116(define module-uses (record-accessor module-type 'uses))
1117(define set-module-uses! (record-modifier module-type 'uses))
1118(define module-binder (record-accessor module-type 'binder))
1119(define set-module-binder! (record-modifier module-type 'binder))
631c1902
MD
1120
1121;; NOTE: This binding is used in libguile/modules.c.
31d50456 1122(define module-eval-closure (record-accessor module-type 'eval-closure))
631c1902 1123
7a0ff2f8
MD
1124(define module-transformer (record-accessor module-type 'transformer))
1125(define set-module-transformer! (record-modifier module-type 'transformer))
0f2d19dd
JB
1126(define module-name (record-accessor module-type 'name))
1127(define set-module-name! (record-modifier module-type 'name))
1128(define module-kind (record-accessor module-type 'kind))
1129(define set-module-kind! (record-modifier module-type 'kind))
1777c18b
MD
1130(define module-observers (record-accessor module-type 'observers))
1131(define set-module-observers! (record-modifier module-type 'observers))
1132(define module-weak-observers (record-accessor module-type 'weak-observers))
1133(define module-observer-id (record-accessor module-type 'observer-id))
1134(define set-module-observer-id! (record-modifier module-type 'observer-id))
0f2d19dd
JB
1135(define module? (record-predicate module-type))
1136
edc185c7
MD
1137(define set-module-eval-closure!
1138 (let ((setter (record-modifier module-type 'eval-closure)))
1139 (lambda (module closure)
1140 (setter module closure)
1141 ;; Make it possible to lookup the module from the environment.
1142 ;; This implementation is correct since an eval closure can belong
1143 ;; to maximally one module.
1144 (set-procedure-property! closure 'module module))))
8b718458 1145
0f2d19dd 1146(define (eval-in-module exp module)
31d50456 1147 (eval2 exp (module-eval-closure module)))
0f2d19dd
JB
1148
1149\f
1777c18b
MD
1150;;; {Observer protocol}
1151;;;
1152
1153(define (module-observe module proc)
1154 (set-module-observers! module (cons proc (module-observers module)))
1155 (cons module proc))
1156
1157(define (module-observe-weak module proc)
1158 (let ((id (module-observer-id module)))
1159 (hash-set! (module-weak-observers module) id proc)
1160 (set-module-observer-id! module (+ 1 id))
1161 (cons module id)))
1162
1163(define (module-unobserve token)
1164 (let ((module (car token))
1165 (id (cdr token)))
1166 (if (integer? id)
1167 (hash-remove! (module-weak-observers module) id)
1168 (set-module-observers! module (delq1! id (module-observers module)))))
1169 *unspecified*)
1170
1a961d7e 1171(define (module-modified m)
1777c18b
MD
1172 (for-each (lambda (proc) (proc m)) (module-observers m))
1173 (hash-fold (lambda (id proc res) (proc m)) #f (module-weak-observers m)))
1174
1175\f
0f2d19dd
JB
1176;;; {Module Searching in General}
1177;;;
1178;;; We sometimes want to look for properties of a symbol
1179;;; just within the obarray of one module. If the property
1180;;; holds, then it is said to hold ``locally'' as in, ``The symbol
1181;;; DISPLAY is locally rebound in the module `safe-guile'.''
1182;;;
1183;;;
1184;;; Other times, we want to test for a symbol property in the obarray
1185;;; of M and, if it is not found there, try each of the modules in the
1186;;; uses list of M. This is the normal way of testing for some
1187;;; property, so we state these properties without qualification as
1188;;; in: ``The symbol 'fnord is interned in module M because it is
1189;;; interned locally in module M2 which is a member of the uses list
1190;;; of M.''
1191;;;
1192
1193;; module-search fn m
1194;;
1195;; return the first non-#f result of FN applied to M and then to
1196;; the modules in the uses of m, and so on recursively. If all applications
1197;; return #f, then so does this function.
1198;;
1199(define (module-search fn m v)
1200 (define (loop pos)
1201 (and (pair? pos)
1202 (or (module-search fn (car pos) v)
1203 (loop (cdr pos)))))
1204 (or (fn m v)
1205 (loop (module-uses m))))
1206
1207
1208;;; {Is a symbol bound in a module?}
1209;;;
1210;;; Symbol S in Module M is bound if S is interned in M and if the binding
1211;;; of S in M has been set to some well-defined value.
1212;;;
1213
1214;; module-locally-bound? module symbol
1215;;
1216;; Is a symbol bound (interned and defined) locally in a given module?
1217;;
1218(define (module-locally-bound? m v)
1219 (let ((var (module-local-variable m v)))
1220 (and var
1221 (variable-bound? var))))
1222
1223;; module-bound? module symbol
1224;;
1225;; Is a symbol bound (interned and defined) anywhere in a given module
1226;; or its uses?
1227;;
1228(define (module-bound? m v)
1229 (module-search module-locally-bound? m v))
1230
1231;;; {Is a symbol interned in a module?}
1232;;;
1233;;; Symbol S in Module M is interned if S occurs in
1234;;; of S in M has been set to some well-defined value.
1235;;;
1236;;; It is possible to intern a symbol in a module without providing
1237;;; an initial binding for the corresponding variable. This is done
1238;;; with:
1239;;; (module-add! module symbol (make-undefined-variable))
1240;;;
1241;;; In that case, the symbol is interned in the module, but not
1242;;; bound there. The unbound symbol shadows any binding for that
1243;;; symbol that might otherwise be inherited from a member of the uses list.
1244;;;
1245
1246(define (module-obarray-get-handle ob key)
1247 ((if (symbol? key) hashq-get-handle hash-get-handle) ob key))
1248
1249(define (module-obarray-ref ob key)
1250 ((if (symbol? key) hashq-ref hash-ref) ob key))
1251
1252(define (module-obarray-set! ob key val)
1253 ((if (symbol? key) hashq-set! hash-set!) ob key val))
1254
1255(define (module-obarray-remove! ob key)
1256 ((if (symbol? key) hashq-remove! hash-remove!) ob key))
1257
1258;; module-symbol-locally-interned? module symbol
1259;;
1260;; is a symbol interned (not neccessarily defined) locally in a given module
1261;; or its uses? Interned symbols shadow inherited bindings even if
1262;; they are not themselves bound to a defined value.
1263;;
1264(define (module-symbol-locally-interned? m v)
1265 (not (not (module-obarray-get-handle (module-obarray m) v))))
1266
1267;; module-symbol-interned? module symbol
1268;;
1269;; is a symbol interned (not neccessarily defined) anywhere in a given module
1270;; or its uses? Interned symbols shadow inherited bindings even if
1271;; they are not themselves bound to a defined value.
1272;;
1273(define (module-symbol-interned? m v)
1274 (module-search module-symbol-locally-interned? m v))
1275
1276
1277;;; {Mapping modules x symbols --> variables}
1278;;;
1279
1280;; module-local-variable module symbol
1281;; return the local variable associated with a MODULE and SYMBOL.
1282;;
1283;;; This function is very important. It is the only function that can
1284;;; return a variable from a module other than the mutators that store
1285;;; new variables in modules. Therefore, this function is the location
1286;;; of the "lazy binder" hack.
1287;;;
1288;;; If symbol is defined in MODULE, and if the definition binds symbol
1289;;; to a variable, return that variable object.
1290;;;
1291;;; If the symbols is not found at first, but the module has a lazy binder,
1292;;; then try the binder.
1293;;;
1294;;; If the symbol is not found at all, return #f.
1295;;;
1296(define (module-local-variable m v)
6fa8995c
GH
1297; (caddr
1298; (list m v
0f2d19dd
JB
1299 (let ((b (module-obarray-ref (module-obarray m) v)))
1300 (or (and (variable? b) b)
1301 (and (module-binder m)
6fa8995c
GH
1302 ((module-binder m) m v #f)))))
1303;))
0f2d19dd
JB
1304
1305;; module-variable module symbol
1306;;
1307;; like module-local-variable, except search the uses in the
1308;; case V is not found in M.
1309;;
6906bd0d
MD
1310;; NOTE: This function is superseded with C code (see modules.c)
1311;;; when using the standard eval closure.
1312;;
0f2d19dd
JB
1313(define (module-variable m v)
1314 (module-search module-local-variable m v))
1315
1316
1317;;; {Mapping modules x symbols --> bindings}
1318;;;
1319;;; These are similar to the mapping to variables, except that the
1320;;; variable is dereferenced.
1321;;;
1322
1323;; module-symbol-binding module symbol opt-value
1324;;
1325;; return the binding of a variable specified by name within
1326;; a given module, signalling an error if the variable is unbound.
1327;; If the OPT-VALUE is passed, then instead of signalling an error,
1328;; return OPT-VALUE.
1329;;
1330(define (module-symbol-local-binding m v . opt-val)
1331 (let ((var (module-local-variable m v)))
1332 (if var
1333 (variable-ref var)
1334 (if (not (null? opt-val))
1335 (car opt-val)
1336 (error "Locally unbound variable." v)))))
1337
1338;; module-symbol-binding module symbol opt-value
1339;;
1340;; return the binding of a variable specified by name within
1341;; a given module, signalling an error if the variable is unbound.
1342;; If the OPT-VALUE is passed, then instead of signalling an error,
1343;; return OPT-VALUE.
1344;;
1345(define (module-symbol-binding m v . opt-val)
1346 (let ((var (module-variable m v)))
1347 (if var
1348 (variable-ref var)
1349 (if (not (null? opt-val))
1350 (car opt-val)
1351 (error "Unbound variable." v)))))
1352
1353
1354\f
1355;;; {Adding Variables to Modules}
1356;;;
1357;;;
1358
1359
1360;; module-make-local-var! module symbol
1361;;
1362;; ensure a variable for V in the local namespace of M.
1363;; If no variable was already there, then create a new and uninitialzied
1364;; variable.
1365;;
1366(define (module-make-local-var! m v)
1367 (or (let ((b (module-obarray-ref (module-obarray m) v)))
1777c18b
MD
1368 (and (variable? b)
1369 (begin
1a961d7e 1370 (module-modified m)
1777c18b 1371 b)))
0f2d19dd
JB
1372 (and (module-binder m)
1373 ((module-binder m) m v #t))
1374 (begin
1375 (let ((answer (make-undefined-variable v)))
1376 (module-obarray-set! (module-obarray m) v answer)
1a961d7e 1377 (module-modified m)
0f2d19dd
JB
1378 answer))))
1379
1380;; module-add! module symbol var
1381;;
1382;; ensure a particular variable for V in the local namespace of M.
1383;;
1384(define (module-add! m v var)
1385 (if (not (variable? var))
1386 (error "Bad variable to module-add!" var))
1777c18b 1387 (module-obarray-set! (module-obarray m) v var)
1a961d7e 1388 (module-modified m))
0f2d19dd
JB
1389
1390;; module-remove!
1391;;
1392;; make sure that a symbol is undefined in the local namespace of M.
1393;;
1394(define (module-remove! m v)
1777c18b 1395 (module-obarray-remove! (module-obarray m) v)
1a961d7e 1396 (module-modified m))
0f2d19dd
JB
1397
1398(define (module-clear! m)
1777c18b 1399 (vector-fill! (module-obarray m) '())
1a961d7e 1400 (module-modified m))
0f2d19dd
JB
1401
1402;; MODULE-FOR-EACH -- exported
1403;;
1404;; Call PROC on each symbol in MODULE, with arguments of (SYMBOL VARIABLE).
1405;;
1406(define (module-for-each proc module)
1407 (let ((obarray (module-obarray module)))
1408 (do ((index 0 (+ index 1))
1409 (end (vector-length obarray)))
1410 ((= index end))
1411 (for-each
1412 (lambda (bucket)
1413 (proc (car bucket) (cdr bucket)))
1414 (vector-ref obarray index)))))
1415
1416
1417(define (module-map proc module)
1418 (let* ((obarray (module-obarray module))
1419 (end (vector-length obarray)))
1420
1421 (let loop ((i 0)
1422 (answer '()))
1423 (if (= i end)
1424 answer
1425 (loop (+ 1 i)
1426 (append!
1427 (map (lambda (bucket)
1428 (proc (car bucket) (cdr bucket)))
1429 (vector-ref obarray i))
1430 answer))))))
1431\f
1432
1433;;; {Low Level Bootstrapping}
1434;;;
1435
1436;; make-root-module
1437
21ed9efe 1438;; A root module uses the symhash table (the system's privileged
0f2d19dd
JB
1439;; obarray). Being inside a root module is like using SCM without
1440;; any module system.
1441;;
1442
1443
31d50456 1444(define (root-module-closure m s define?)
0f2d19dd
JB
1445 (let ((bi (and (symbol-interned? #f s)
1446 (builtin-variable s))))
1447 (and bi
1448 (or define? (variable-bound? bi))
1449 (begin
1450 (module-add! m s bi)
1451 bi))))
1452
1453(define (make-root-module)
31d50456 1454 (make-module 1019 '() root-module-closure))
0f2d19dd
JB
1455
1456
1457;; make-scm-module
1458
1459;; An scm module is a module into which the lazy binder copies
1460;; variable bindings from the system symhash table. The mapping is
1461;; one way only; newly introduced bindings in an scm module are not
1462;; copied back into the system symhash table (and can be used to override
1463;; bindings from the symhash table).
1464;;
1465
6906bd0d
MD
1466(define (scm-module-closure m s define?)
1467 (let ((bi (and (symbol-interned? #f s)
1468 (builtin-variable s))))
1469 (and bi
1470 (variable-bound? bi)
1471 (begin
1472 (module-add! m s bi)
1473 bi))))
0f2d19dd 1474
6906bd0d
MD
1475(define (make-scm-module)
1476 (make-module 1019 '() scm-module-closure))
0f2d19dd
JB
1477
1478
1479
1480;; the-module
631c1902
MD
1481;;
1482;; NOTE: This binding is used in libguile/modules.c.
1483;;
bd0fb3cf 1484(define the-module (make-fluid))
0f2d19dd 1485
7a0ff2f8 1486;; scm:eval-transformer
d43f8c97 1487;;
bd0fb3cf 1488;;(define scm:eval-transformer (make-fluid)) ; initialized in eval.c.
d43f8c97 1489
0f2d19dd
JB
1490;; set-current-module module
1491;;
1492;; set the current module as viewed by the normalizer.
1493;;
631c1902
MD
1494;; NOTE: This binding is used in libguile/modules.c.
1495;;
0f2d19dd 1496(define (set-current-module m)
bd0fb3cf 1497 (fluid-set! the-module m)
7a0ff2f8
MD
1498 (if m
1499 (begin
bd0fb3cf
MD
1500 (fluid-set! *top-level-lookup-closure*
1501 (module-eval-closure (fluid-ref the-module)))
1502 (fluid-set! scm:eval-transformer (module-transformer (fluid-ref the-module))))
1503 (fluid-set! *top-level-lookup-closure* #f)))
0f2d19dd
JB
1504
1505
1506;; current-module
1507;;
1508;; return the current module as viewed by the normalizer.
1509;;
bd0fb3cf 1510(define (current-module) (fluid-ref the-module))
0f2d19dd
JB
1511\f
1512;;; {Module-based Loading}
1513;;;
1514
1515(define (save-module-excursion thunk)
1516 (let ((inner-module (current-module))
1517 (outer-module #f))
1518 (dynamic-wind (lambda ()
1519 (set! outer-module (current-module))
1520 (set-current-module inner-module)
1521 (set! inner-module #f))
1522 thunk
1523 (lambda ()
1524 (set! inner-module (current-module))
1525 (set-current-module outer-module)
1526 (set! outer-module #f)))))
1527
0f2d19dd
JB
1528(define basic-load load)
1529
c6775c40
MD
1530(define (load-module filename)
1531 (save-module-excursion
1532 (lambda ()
1533 (let ((oldname (and (current-load-port)
1534 (port-filename (current-load-port)))))
1535 (basic-load (if (and oldname
1536 (> (string-length filename) 0)
1537 (not (char=? (string-ref filename 0) #\/))
1538 (not (string=? (dirname oldname) ".")))
1539 (string-append (dirname oldname) "/" filename)
1540 filename))))))
0f2d19dd
JB
1541
1542
1543\f
44cf1f0f 1544;;; {MODULE-REF -- exported}
0f2d19dd
JB
1545;;
1546;; Returns the value of a variable called NAME in MODULE or any of its
1547;; used modules. If there is no such variable, then if the optional third
1548;; argument DEFAULT is present, it is returned; otherwise an error is signaled.
1549;;
1550(define (module-ref module name . rest)
1551 (let ((variable (module-variable module name)))
1552 (if (and variable (variable-bound? variable))
1553 (variable-ref variable)
1554 (if (null? rest)
1555 (error "No variable named" name 'in module)
1556 (car rest) ; default value
1557 ))))
1558
1559;; MODULE-SET! -- exported
1560;;
1561;; Sets the variable called NAME in MODULE (or in a module that MODULE uses)
1562;; to VALUE; if there is no such variable, an error is signaled.
1563;;
1564(define (module-set! module name value)
1565 (let ((variable (module-variable module name)))
1566 (if variable
1567 (variable-set! variable value)
1568 (error "No variable named" name 'in module))))
1569
1570;; MODULE-DEFINE! -- exported
1571;;
1572;; Sets the variable called NAME in MODULE to VALUE; if there is no such
1573;; variable, it is added first.
1574;;
1575(define (module-define! module name value)
1576 (let ((variable (module-local-variable module name)))
1577 (if variable
1777c18b
MD
1578 (begin
1579 (variable-set! variable value)
1a961d7e 1580 (module-modified module))
0f2d19dd
JB
1581 (module-add! module name (make-variable value name)))))
1582
ed218d98
MV
1583;; MODULE-DEFINED? -- exported
1584;;
1585;; Return #t iff NAME is defined in MODULE (or in a module that MODULE
1586;; uses)
1587;;
1588(define (module-defined? module name)
1589 (let ((variable (module-variable module name)))
1590 (and variable (variable-bound? variable))))
1591
0f2d19dd
JB
1592;; MODULE-USE! module interface
1593;;
1594;; Add INTERFACE to the list of interfaces used by MODULE.
1595;;
1596(define (module-use! module interface)
1597 (set-module-uses! module
1777c18b 1598 (cons interface (delq! interface (module-uses module))))
1a961d7e 1599 (module-modified module))
0f2d19dd
JB
1600
1601\f
0f2d19dd
JB
1602;;; {Recursive Namespaces}
1603;;;
1604;;;
1605;;; A hierarchical namespace emerges if we consider some module to be
1606;;; root, and variables bound to modules as nested namespaces.
1607;;;
1608;;; The routines in this file manage variable names in hierarchical namespace.
1609;;; Each variable name is a list of elements, looked up in successively nested
1610;;; modules.
1611;;;
0dd5491c 1612;;; (nested-ref some-root-module '(foo bar baz))
0f2d19dd
JB
1613;;; => <value of a variable named baz in the module bound to bar in
1614;;; the module bound to foo in some-root-module>
1615;;;
1616;;;
1617;;; There are:
1618;;;
1619;;; ;; a-root is a module
1620;;; ;; name is a list of symbols
1621;;;
0dd5491c
MD
1622;;; nested-ref a-root name
1623;;; nested-set! a-root name val
1624;;; nested-define! a-root name val
1625;;; nested-remove! a-root name
0f2d19dd
JB
1626;;;
1627;;;
1628;;; (current-module) is a natural choice for a-root so for convenience there are
1629;;; also:
1630;;;
0dd5491c
MD
1631;;; local-ref name == nested-ref (current-module) name
1632;;; local-set! name val == nested-set! (current-module) name val
1633;;; local-define! name val == nested-define! (current-module) name val
1634;;; local-remove! name == nested-remove! (current-module) name
0f2d19dd
JB
1635;;;
1636
1637
0dd5491c 1638(define (nested-ref root names)
0f2d19dd
JB
1639 (let loop ((cur root)
1640 (elts names))
1641 (cond
1642 ((null? elts) cur)
1643 ((not (module? cur)) #f)
1644 (else (loop (module-ref cur (car elts) #f) (cdr elts))))))
1645
0dd5491c 1646(define (nested-set! root names val)
0f2d19dd
JB
1647 (let loop ((cur root)
1648 (elts names))
1649 (if (null? (cdr elts))
1650 (module-set! cur (car elts) val)
1651 (loop (module-ref cur (car elts)) (cdr elts)))))
1652
0dd5491c 1653(define (nested-define! root names val)
0f2d19dd
JB
1654 (let loop ((cur root)
1655 (elts names))
1656 (if (null? (cdr elts))
1657 (module-define! cur (car elts) val)
1658 (loop (module-ref cur (car elts)) (cdr elts)))))
1659
0dd5491c 1660(define (nested-remove! root names)
0f2d19dd
JB
1661 (let loop ((cur root)
1662 (elts names))
1663 (if (null? (cdr elts))
1664 (module-remove! cur (car elts))
1665 (loop (module-ref cur (car elts)) (cdr elts)))))
1666
0dd5491c
MD
1667(define (local-ref names) (nested-ref (current-module) names))
1668(define (local-set! names val) (nested-set! (current-module) names val))
1669(define (local-define names val) (nested-define! (current-module) names val))
1670(define (local-remove names) (nested-remove! (current-module) names))
0f2d19dd
JB
1671
1672
1673\f
8bb7330c 1674;;; {The (app) module}
0f2d19dd
JB
1675;;;
1676;;; The root of conventionally named objects not directly in the top level.
1677;;;
8bb7330c
JB
1678;;; (app modules)
1679;;; (app modules guile)
0f2d19dd
JB
1680;;;
1681;;; The directory of all modules and the standard root module.
1682;;;
1683
edc185c7
MD
1684(define (module-public-interface m)
1685 (module-ref m '%module-public-interface #f))
1686(define (set-module-public-interface! m i)
1687 (module-define! m '%module-public-interface i))
1688(define (set-system-module! m s)
1689 (set-procedure-property! (module-eval-closure m) 'system-module s))
0f2d19dd
JB
1690(define the-root-module (make-root-module))
1691(define the-scm-module (make-scm-module))
1692(set-module-public-interface! the-root-module the-scm-module)
d5504515
MD
1693(set-module-name! the-root-module '(guile))
1694(set-module-name! the-scm-module '(guile))
1695(set-module-kind! the-scm-module 'interface)
edc185c7 1696(for-each set-system-module! (list the-root-module the-scm-module) '(#t #t))
0f2d19dd
JB
1697
1698(set-current-module the-root-module)
1699
1700(define app (make-module 31))
0dd5491c
MD
1701(local-define '(app modules) (make-module 31))
1702(local-define '(app modules guile) the-root-module)
0f2d19dd
JB
1703
1704;; (define-special-value '(app modules new-ws) (lambda () (make-scm-module)))
1705
432558b9
MD
1706(define (try-load-module name)
1707 (or (try-module-linked name)
1708 (try-module-autoload name)
1709 (try-module-dynamic-link name)))
1710
1f60d9d2
MD
1711;; NOTE: This binding is used in libguile/modules.c.
1712;;
0209ca9a 1713(define (resolve-module name . maybe-autoload)
0f2d19dd 1714 (let ((full-name (append '(app modules) name)))
0dd5491c 1715 (let ((already (local-ref full-name)))
432558b9
MD
1716 (if already
1717 ;; The module already exists...
1718 (if (and (or (null? maybe-autoload) (car maybe-autoload))
1719 (not (module-ref already '%module-public-interface #f)))
1720 ;; ...but we are told to load and it doesn't contain source, so
1721 (begin
1722 (try-load-module name)
1723 already)
1724 ;; simply return it.
1725 already)
3e3cec45 1726 (begin
432558b9 1727 ;; Try to autoload it if we are told so
3e3cec45 1728 (if (or (null? maybe-autoload) (car maybe-autoload))
432558b9
MD
1729 (try-load-module name))
1730 ;; Get/create it.
3e3cec45 1731 (make-modules-in (current-module) full-name))))))
0f2d19dd
JB
1732
1733(define (beautify-user-module! module)
3e3cec45
MD
1734 (let ((interface (module-public-interface module)))
1735 (if (or (not interface)
1736 (eq? interface module))
1737 (let ((interface (make-module 31)))
1738 (set-module-name! interface (module-name module))
1739 (set-module-kind! interface 'interface)
1740 (set-module-public-interface! module interface))))
cc7f066c
MD
1741 (if (and (not (memq the-scm-module (module-uses module)))
1742 (not (eq? module the-root-module)))
0f2d19dd
JB
1743 (set-module-uses! module (append (module-uses module) (list the-scm-module)))))
1744
90847923
MD
1745(define (purify-module! module)
1746 "Removes bindings in MODULE which are inherited from the (guile) module."
1747 (let ((use-list (module-uses module)))
1748 (if (and (pair? use-list)
1749 (eq? (car (last-pair use-list)) the-scm-module))
1750 (set-module-uses! module (reverse (cdr (reverse use-list)))))))
1751
631c1902
MD
1752;; NOTE: This binding is used in libguile/modules.c.
1753;;
0f2d19dd
JB
1754(define (make-modules-in module name)
1755 (if (null? name)
1756 module
1757 (cond
3e3cec45
MD
1758 ((module-ref module (car name) #f)
1759 => (lambda (m) (make-modules-in m (cdr name))))
0f2d19dd
JB
1760 (else (let ((m (make-module 31)))
1761 (set-module-kind! m 'directory)
d5504515
MD
1762 (set-module-name! m (append (or (module-name module)
1763 '())
1764 (list (car name))))
0f2d19dd
JB
1765 (module-define! module (car name) m)
1766 (make-modules-in m (cdr name)))))))
1767
1768(define (resolve-interface name)
1769 (let ((module (resolve-module name)))
1770 (and module (module-public-interface module))))
1771
1772
1773(define %autoloader-developer-mode #t)
1774
1775(define (process-define-module args)
1776 (let* ((module-id (car args))
0209ca9a 1777 (module (resolve-module module-id #f))
0f2d19dd
JB
1778 (kws (cdr args)))
1779 (beautify-user-module! module)
0209ca9a
MV
1780 (let loop ((kws kws)
1781 (reversed-interfaces '()))
1782 (if (null? kws)
1783 (for-each (lambda (interface)
1784 (module-use! module interface))
1785 reversed-interfaces)
f714ca8e
MD
1786 (let ((keyword (cond ((keyword? (car kws))
1787 (keyword->symbol (car kws)))
1788 ((and (symbol? (car kws))
1789 (eq? (string-ref (car kws) 0) #\:))
1790 (string->symbol (substring (car kws) 1)))
1791 (else #f))))
1792 (case keyword
1793 ((use-module use-syntax)
1794 (if (not (pair? (cdr kws)))
1795 (error "unrecognized defmodule argument" kws))
1796 (let* ((used-name (cadr kws))
1797 (used-module (resolve-module used-name)))
45a02a29
MD
1798 (if (not (module-ref used-module
1799 '%module-public-interface
1800 #f))
3e3cec45 1801 (begin
45a02a29
MD
1802 ((if %autoloader-developer-mode warn error)
1803 "no code for module" (module-name used-module))
1804 (beautify-user-module! used-module)))
1805 (let ((interface (module-public-interface used-module)))
1806 (if (not interface)
1807 (error "missing interface for use-module"
1808 used-module))
1809 (if (eq? keyword 'use-syntax)
7cbaee0c
MD
1810 (set-module-transformer!
1811 module
45a02a29
MD
1812 (module-ref interface (car (last-pair used-name))
1813 #f)))
1814 (loop (cddr kws)
1815 (cons interface reversed-interfaces)))))
71225060
MD
1816 ((autoload)
1817 (if (not (and (pair? (cdr kws)) (pair? (cddr kws))))
1818 (error "unrecognized defmodule argument" kws))
1819 (loop (cdddr kws)
1820 (cons (make-autoload-interface module
1821 (cadr kws)
1822 (caddr kws))
1823 reversed-interfaces)))
edc185c7
MD
1824 ((no-backtrace)
1825 (set-system-module! module #t)
1826 (loop (cdr kws) reversed-interfaces))
90847923
MD
1827 ((pure)
1828 (purify-module! module)
1829 (loop (cdr kws) reversed-interfaces))
1830 ((export)
1831 (if (not (and (pair? (cdr kws)) (pair? (cddr kws))))
1832 (error "unrecognized defmodule argument" kws))
1833 (module-export! module (cadr kws))
1834 (loop (cddr kws) reversed-interfaces))
f714ca8e
MD
1835 (else
1836 (error "unrecognized defmodule argument" kws))))))
0f2d19dd 1837 module))
71225060
MD
1838
1839;;; {Autoload}
1840
1841(define (make-autoload-interface module name bindings)
1842 (let ((b (lambda (a sym definep)
1843 (and (memq sym bindings)
1844 (let ((i (module-public-interface (resolve-module name))))
1845 (if (not i)
1846 (error "missing interface for module" name))
1847 ;; Replace autoload-interface with interface
1848 (set-car! (memq a (module-uses module)) i)
1849 (module-local-variable i sym))))))
d5504515 1850 (module-constructor #() '() b #f #f name 'autoload
6b64c19b 1851 '() (make-weak-value-hash-table 31) 0)))
71225060 1852
0f2d19dd 1853\f
44cf1f0f 1854;;; {Autoloading modules}
0f2d19dd
JB
1855
1856(define autoloads-in-progress '())
1857
1858(define (try-module-autoload module-name)
0f2d19dd
JB
1859 (let* ((reverse-name (reverse module-name))
1860 (name (car reverse-name))
1861 (dir-hint-module-name (reverse (cdr reverse-name)))
1862 (dir-hint (apply symbol-append (map (lambda (elt) (symbol-append elt "/")) dir-hint-module-name))))
0209ca9a 1863 (resolve-module dir-hint-module-name #f)
0f2d19dd
JB
1864 (and (not (autoload-done-or-in-progress? dir-hint name))
1865 (let ((didit #f))
1866 (dynamic-wind
1867 (lambda () (autoload-in-progress! dir-hint name))
defed517
MD
1868 (lambda ()
1869 (let ((full (%search-load-path (in-vicinity dir-hint name))))
1870 (if full
1871 (begin
1872 (save-module-excursion (lambda () (primitive-load full)))
1873 (set! didit #t)))))
0f2d19dd
JB
1874 (lambda () (set-autoloaded! dir-hint name didit)))
1875 didit))))
1876
71225060 1877\f
d0cbd20c
MV
1878;;; Dynamic linking of modules
1879
1880;; Initializing a module that is written in C is a two step process.
1881;; First the module's `module init' function is called. This function
1882;; is expected to call `scm_register_module_xxx' to register the `real
1883;; init' function. Later, when the module is referenced for the first
1884;; time, this real init function is called in the right context. See
1885;; gtcltk-lib/gtcltk-module.c for an example.
1886;;
1887;; The code for the module can be in a regular shared library (so that
1888;; the `module init' function will be called when libguile is
1889;; initialized). Or it can be dynamically linked.
1890;;
1891;; You can safely call `scm_register_module_xxx' before libguile
1892;; itself is initialized. You could call it from an C++ constructor
1893;; of a static object, for example.
1894;;
1895;; To make your Guile extension into a dynamic linkable module, follow
1896;; these easy steps:
1897;;
8bb7330c 1898;; - Find a name for your module, like (ice-9 gtcltk)
d0cbd20c
MV
1899;; - Write a function with a name like
1900;;
1901;; scm_init_ice_9_gtcltk_module
1902;;
1903;; This is your `module init' function. It should call
1904;;
1905;; scm_register_module_xxx ("ice-9 gtcltk", scm_init_gtcltk);
1906;;
1907;; "ice-9 gtcltk" is the C version of the module name. Slashes are
1908;; replaced by spaces, the rest is untouched. `scm_init_gtcltk' is
ed218d98 1909;; the real init function that executes the usual initializations
d0cbd20c
MV
1910;; like making new smobs, etc.
1911;;
1912;; - Make a shared library with your code and a name like
1913;;
1914;; ice-9/libgtcltk.so
1915;;
1916;; and put it somewhere in %load-path.
1917;;
8bb7330c 1918;; - Then you can simply write `:use-module (ice-9 gtcltk)' and it
d0cbd20c
MV
1919;; will be linked automatically.
1920;;
1921;; This is all very experimental.
1922
1923(define (split-c-module-name str)
1924 (let loop ((rev '())
1925 (start 0)
1926 (pos 0)
1927 (end (string-length str)))
1928 (cond
1929 ((= pos end)
1930 (reverse (cons (string->symbol (substring str start pos)) rev)))
1931 ((eq? (string-ref str pos) #\space)
1932 (loop (cons (string->symbol (substring str start pos)) rev)
1933 (+ pos 1)
1934 (+ pos 1)
1935 end))
1936 (else
1937 (loop rev start (+ pos 1) end)))))
1938
1939(define (convert-c-registered-modules dynobj)
1940 (let ((res (map (lambda (c)
1941 (list (split-c-module-name (car c)) (cdr c) dynobj))
1942 (c-registered-modules))))
1943 (c-clear-registered-modules)
1944 res))
1945
3e3cec45
MD
1946(define registered-modules '())
1947
1948(define (register-modules dynobj)
1949 (set! registered-modules
1950 (append! (convert-c-registered-modules dynobj)
1951 registered-modules)))
1952
d0cbd20c 1953(define (init-dynamic-module modname)
3e3cec45
MD
1954 ;; Register any linked modules which has been registered on the C level
1955 (register-modules #f)
d0cbd20c
MV
1956 (or-map (lambda (modinfo)
1957 (if (equal? (car modinfo) modname)
c04e89c7
MD
1958 (begin
1959 (set! registered-modules (delq! modinfo registered-modules))
1960 (let ((mod (resolve-module modname #f)))
1961 (save-module-excursion
1962 (lambda ()
1963 (set-current-module mod)
1964 (set-module-public-interface! mod mod)
1965 (dynamic-call (cadr modinfo) (caddr modinfo))
1966 ))
1967 #t))
d0cbd20c
MV
1968 #f))
1969 registered-modules))
1970
1971(define (dynamic-maybe-call name dynobj)
1972 (catch #t ; could use false-if-exception here
1973 (lambda ()
1974 (dynamic-call name dynobj))
1975 (lambda args
1976 #f)))
1977
ed218d98
MV
1978(define (dynamic-maybe-link filename)
1979 (catch #t ; could use false-if-exception here
1980 (lambda ()
1981 (dynamic-link filename))
1982 (lambda args
1983 #f)))
1984
d0cbd20c
MV
1985(define (find-and-link-dynamic-module module-name)
1986 (define (make-init-name mod-name)
bd9e24b3 1987 (string-append "scm_init"
d0cbd20c
MV
1988 (list->string (map (lambda (c)
1989 (if (or (char-alphabetic? c)
1990 (char-numeric? c))
1991 c
1992 #\_))
1993 (string->list mod-name)))
bd9e24b3 1994 "_module"))
ebd79f62
TP
1995
1996 ;; Put the subdirectory for this module in the car of SUBDIR-AND-LIBNAME,
1997 ;; and the `libname' (the name of the module prepended by `lib') in the cdr
1998 ;; field. For example, if MODULE-NAME is the list (inet tcp-ip udp), then
1999 ;; SUBDIR-AND-LIBNAME will be the pair ("inet/tcp-ip" . "libudp").
2000 (let ((subdir-and-libname
d0cbd20c
MV
2001 (let loop ((dirs "")
2002 (syms module-name))
ebd79f62
TP
2003 (if (null? (cdr syms))
2004 (cons dirs (string-append "lib" (car syms)))
2005 (loop (string-append dirs (car syms) "/") (cdr syms)))))
d0cbd20c
MV
2006 (init (make-init-name (apply string-append
2007 (map (lambda (s)
2008 (string-append "_" s))
2009 module-name)))))
ebd79f62
TP
2010 (let ((subdir (car subdir-and-libname))
2011 (libname (cdr subdir-and-libname)))
2012
2013 ;; Now look in each dir in %LOAD-PATH for `subdir/libfoo.la'. If that
2014 ;; file exists, fetch the dlname from that file and attempt to link
2015 ;; against it. If `subdir/libfoo.la' does not exist, or does not seem
2016 ;; to name any shared library, look for `subdir/libfoo.so' instead and
2017 ;; link against that.
2018 (let check-dirs ((dir-list %load-path))
2019 (if (null? dir-list)
2020 #f
2021 (let* ((dir (in-vicinity (car dir-list) subdir))
2022 (sharlib-full
2023 (or (try-using-libtool-name dir libname)
2024 (try-using-sharlib-name dir libname))))
2025 (if (and sharlib-full (file-exists? sharlib-full))
2026 (link-dynamic-module sharlib-full init)
2027 (check-dirs (cdr dir-list)))))))))
2028
2029(define (try-using-libtool-name libdir libname)
ebd79f62
TP
2030 (let ((libtool-filename (in-vicinity libdir
2031 (string-append libname ".la"))))
2032 (and (file-exists? libtool-filename)
352d134c 2033 libtool-filename)))
ebd79f62
TP
2034
2035(define (try-using-sharlib-name libdir libname)
2036 (in-vicinity libdir (string-append libname ".so")))
d0cbd20c
MV
2037
2038(define (link-dynamic-module filename initname)
3e3cec45
MD
2039 ;; Register any linked modules which has been registered on the C level
2040 (register-modules #f)
6b856182
MV
2041 (let ((dynobj (dynamic-link filename)))
2042 (dynamic-call initname dynobj)
3e3cec45 2043 (register-modules dynobj)))
a4f9b1f6
MD
2044
2045(define (try-module-linked module-name)
2046 (init-dynamic-module module-name))
2047
d0cbd20c 2048(define (try-module-dynamic-link module-name)
a4f9b1f6
MD
2049 (and (find-and-link-dynamic-module module-name)
2050 (init-dynamic-module module-name)))
d0cbd20c 2051
ed218d98
MV
2052
2053
0f2d19dd
JB
2054(define autoloads-done '((guile . guile)))
2055
2056(define (autoload-done-or-in-progress? p m)
2057 (let ((n (cons p m)))
2058 (->bool (or (member n autoloads-done)
2059 (member n autoloads-in-progress)))))
2060
2061(define (autoload-done! p m)
2062 (let ((n (cons p m)))
2063 (set! autoloads-in-progress
2064 (delete! n autoloads-in-progress))
2065 (or (member n autoloads-done)
2066 (set! autoloads-done (cons n autoloads-done)))))
2067
2068(define (autoload-in-progress! p m)
2069 (let ((n (cons p m)))
2070 (set! autoloads-done
2071 (delete! n autoloads-done))
2072 (set! autoloads-in-progress (cons n autoloads-in-progress))))
2073
2074(define (set-autoloaded! p m done?)
2075 (if done?
2076 (autoload-done! p m)
2077 (let ((n (cons p m)))
2078 (set! autoloads-done (delete! n autoloads-done))
2079 (set! autoloads-in-progress (delete! n autoloads-in-progress)))))
2080
2081
2082
2083
2084\f
2085;;; {Macros}
2086;;;
2087
7a0ff2f8
MD
2088(define (primitive-macro? m)
2089 (and (macro? m)
2090 (not (macro-transformer m))))
2091
2092;;; {Defmacros}
2093;;;
9591db87
MD
2094(define macro-table (make-weak-key-hash-table 523))
2095(define xformer-table (make-weak-key-hash-table 523))
0f2d19dd
JB
2096
2097(define (defmacro? m) (hashq-ref macro-table m))
2098(define (assert-defmacro?! m) (hashq-set! macro-table m #t))
2099(define (defmacro-transformer m) (hashq-ref xformer-table m))
2100(define (set-defmacro-transformer! m t) (hashq-set! xformer-table m t))
2101
2102(define defmacro:transformer
2103 (lambda (f)
2104 (let* ((xform (lambda (exp env)
2105 (copy-tree (apply f (cdr exp)))))
2106 (a (procedure->memoizing-macro xform)))
2107 (assert-defmacro?! a)
2108 (set-defmacro-transformer! a f)
2109 a)))
2110
2111
2112(define defmacro
2113 (let ((defmacro-transformer
2114 (lambda (name parms . body)
2115 (let ((transformer `(lambda ,parms ,@body)))
2116 `(define ,name
2117 (,(lambda (transformer)
2118 (defmacro:transformer transformer))
2119 ,transformer))))))
2120 (defmacro:transformer defmacro-transformer)))
2121
2122(define defmacro:syntax-transformer
2123 (lambda (f)
2124 (procedure->syntax
2125 (lambda (exp env)
2126 (copy-tree (apply f (cdr exp)))))))
2127
ed218d98
MV
2128
2129;; XXX - should the definition of the car really be looked up in the
2130;; current module?
2131
0f2d19dd
JB
2132(define (macroexpand-1 e)
2133 (cond
2134 ((pair? e) (let* ((a (car e))
ed218d98 2135 (val (and (symbol? a) (local-ref (list a)))))
0f2d19dd
JB
2136 (if (defmacro? val)
2137 (apply (defmacro-transformer val) (cdr e))
2138 e)))
2139 (#t e)))
2140
2141(define (macroexpand e)
2142 (cond
2143 ((pair? e) (let* ((a (car e))
ed218d98 2144 (val (and (symbol? a) (local-ref (list a)))))
0f2d19dd
JB
2145 (if (defmacro? val)
2146 (macroexpand (apply (defmacro-transformer val) (cdr e)))
2147 e)))
2148 (#t e)))
2149
e672f1b5
MD
2150(define (gentemp)
2151 (gensym "scm:G"))
0f2d19dd 2152
534a0099 2153(provide 'defmacro)
0f2d19dd
JB
2154
2155\f
2156
83b38198
MD
2157;;; {Run-time options}
2158
16b8ebbe
MD
2159((let* ((names '((eval-options-interface
2160 (eval-options eval-enable eval-disable)
2161 (eval-set!))
2162
2163 (debug-options-interface
83b38198
MD
2164 (debug-options debug-enable debug-disable)
2165 (debug-set!))
2166
2167 (evaluator-traps-interface
2168 (traps trap-enable trap-disable)
2169 (trap-set!))
2170
2171 (read-options-interface
2172 (read-options read-enable read-disable)
2173 (read-set!))
2174
2175 (print-options-interface
2176 (print-options print-enable print-disable)
2177 (print-set!))
e586be78
MD
2178
2179 (readline-options-interface
2180 (readline-options readline-enable readline-disable)
2181 (readline-set!))
83b38198
MD
2182 ))
2183 (option-name car)
2184 (option-value cadr)
2185 (option-documentation caddr)
2186
2187 (print-option (lambda (option)
2188 (display (option-name option))
2189 (if (< (string-length
2190 (symbol->string (option-name option)))
2191 8)
2192 (display #\tab))
2193 (display #\tab)
2194 (display (option-value option))
2195 (display #\tab)
2196 (display (option-documentation option))
2197 (newline)))
2198
2199 ;; Below follows the macros defining the run-time option interfaces.
2200
2201 (make-options (lambda (interface)
2202 `(lambda args
2203 (cond ((null? args) (,interface))
45456413 2204 ((list? (car args))
83b38198 2205 (,interface (car args)) (,interface))
2f110c3c 2206 (else (for-each ,print-option
83b38198
MD
2207 (,interface #t)))))))
2208
2209 (make-enable (lambda (interface)
2210 `(lambda flags
2211 (,interface (append flags (,interface)))
2212 (,interface))))
2213
2214 (make-disable (lambda (interface)
2215 `(lambda flags
2216 (let ((options (,interface)))
2217 (for-each (lambda (flag)
2218 (set! options (delq! flag options)))
2219 flags)
2220 (,interface options)
2221 (,interface)))))
2222
2223 (make-set! (lambda (interface)
2224 `((name exp)
2225 (,'quasiquote
2226 (begin (,interface (append (,interface)
2227 (list '(,'unquote name)
2228 (,'unquote exp))))
2229 (,interface))))))
2230 )
2231 (procedure->macro
2232 (lambda (exp env)
2233 (cons 'begin
2234 (apply append
2235 (map (lambda (group)
2236 (let ((interface (car group)))
2237 (append (map (lambda (name constructor)
2238 `(define ,name
2239 ,(constructor interface)))
2240 (cadr group)
2241 (list make-options
2242 make-enable
2243 make-disable))
2244 (map (lambda (name constructor)
2245 `(defmacro ,name
2246 ,@(constructor interface)))
2247 (caddr group)
2248 (list make-set!)))))
2249 names)))))))
2250
2251\f
2252
0f2d19dd
JB
2253;;; {Running Repls}
2254;;;
2255
2256(define (repl read evaler print)
75a97b92 2257 (let loop ((source (read (current-input-port))))
0f2d19dd 2258 (print (evaler source))
75a97b92 2259 (loop (read (current-input-port)))))
0f2d19dd
JB
2260
2261;; A provisional repl that acts like the SCM repl:
2262;;
2263(define scm-repl-silent #f)
2264(define (assert-repl-silence v) (set! scm-repl-silent v))
2265
21ed9efe
MD
2266(define *unspecified* (if #f #f))
2267(define (unspecified? v) (eq? v *unspecified*))
2268
2269(define scm-repl-print-unspecified #f)
2270(define (assert-repl-print-unspecified v) (set! scm-repl-print-unspecified v))
2271
79451588 2272(define scm-repl-verbose #f)
0f2d19dd
JB
2273(define (assert-repl-verbosity v) (set! scm-repl-verbose v))
2274
e6875011 2275(define scm-repl-prompt "guile> ")
0f2d19dd 2276
e6875011
MD
2277(define (set-repl-prompt! v) (set! scm-repl-prompt v))
2278
d5d34fa1
MD
2279(define (default-lazy-handler key . args)
2280 (save-stack lazy-handler-dispatch)
2281 (apply throw key args))
2282
45456413 2283(define enter-frame-handler default-lazy-handler)
d5d34fa1
MD
2284(define apply-frame-handler default-lazy-handler)
2285(define exit-frame-handler default-lazy-handler)
2286
2287(define (lazy-handler-dispatch key . args)
2288 (case key
2289 ((apply-frame)
2290 (apply apply-frame-handler key args))
2291 ((exit-frame)
2292 (apply exit-frame-handler key args))
45456413
MD
2293 ((enter-frame)
2294 (apply enter-frame-handler key args))
d5d34fa1
MD
2295 (else
2296 (apply default-lazy-handler key args))))
0f2d19dd 2297
3e3cec45 2298(define abort-hook (make-hook))
59e1116d 2299
28d8ab3c
GH
2300;; these definitions are used if running a script.
2301;; otherwise redefined in error-catching-loop.
2302(define (set-batch-mode?! arg) #t)
2303(define (batch-mode?) #t)
4bbbcd5c 2304
0f2d19dd 2305(define (error-catching-loop thunk)
4bbbcd5c
GH
2306 (let ((status #f)
2307 (interactive #t))
8e44e7a0
GH
2308 (define (loop first)
2309 (let ((next
2310 (catch #t
9a0d70e2 2311
8e44e7a0
GH
2312 (lambda ()
2313 (lazy-catch #t
2314 (lambda ()
2315 (dynamic-wind
2316 (lambda () (unmask-signals))
2317 (lambda ()
45456413
MD
2318 (with-traps
2319 (lambda ()
2320 (first)
8e44e7a0 2321
45456413
MD
2322 ;; This line is needed because mark
2323 ;; doesn't do closures quite right.
2324 ;; Unreferenced locals should be
2325 ;; collected.
2326 ;;
2327 (set! first #f)
2328 (let loop ((v (thunk)))
2329 (loop (thunk)))
2330 #f)))
8e44e7a0
GH
2331 (lambda () (mask-signals))))
2332
2333 lazy-handler-dispatch))
2334
2335 (lambda (key . args)
2336 (case key
2337 ((quit)
8e44e7a0
GH
2338 (set! status args)
2339 #f)
2340
2341 ((switch-repl)
2342 (apply throw 'switch-repl args))
2343
2344 ((abort)
2345 ;; This is one of the closures that require
2346 ;; (set! first #f) above
2347 ;;
2348 (lambda ()
04efd24d 2349 (run-hook abort-hook)
e13c54c4 2350 (force-output (current-output-port))
8e44e7a0
GH
2351 (display "ABORT: " (current-error-port))
2352 (write args (current-error-port))
2353 (newline (current-error-port))
4bbbcd5c 2354 (if interactive
e13c54c4
JB
2355 (begin
2356 (if (and
2357 (not has-shown-debugger-hint?)
2358 (not (memq 'backtrace
2359 (debug-options-interface)))
2360 (stack? (fluid-ref the-last-stack)))
2361 (begin
2362 (newline (current-error-port))
2363 (display
cb546c61 2364 "Type \"(backtrace)\" to get more information or \"(debug)\" to enter the debugger.\n"
e13c54c4
JB
2365 (current-error-port))
2366 (set! has-shown-debugger-hint? #t)))
2367 (force-output (current-error-port)))
2368 (begin
2369 (primitive-exit 1)))
8e44e7a0
GH
2370 (set! stack-saved? #f)))
2371
2372 (else
2373 ;; This is the other cons-leak closure...
2374 (lambda ()
2375 (cond ((= (length args) 4)
2376 (apply handle-system-error key args))
2377 (else
2378 (apply bad-throw key args))))))))))
2379 (if next (loop next) status)))
5f5f2642
MD
2380 (set! set-batch-mode?! (lambda (arg)
2381 (cond (arg
2382 (set! interactive #f)
2383 (restore-signals))
2384 (#t
2385 (error "sorry, not implemented")))))
2386 (set! batch-mode? (lambda () (not interactive)))
8e44e7a0 2387 (loop (lambda () #t))))
0f2d19dd 2388
8bb7f646 2389;;(define the-last-stack (make-fluid)) Defined by scm_init_backtrace ()
8087b6be 2390(define before-signal-stack (make-fluid))
21ed9efe
MD
2391(define stack-saved? #f)
2392
2393(define (save-stack . narrowing)
edc185c7
MD
2394 (or stack-saved?
2395 (cond ((not (memq 'debug (debug-options-interface)))
2396 (fluid-set! the-last-stack #f)
2397 (set! stack-saved? #t))
2398 (else
2399 (fluid-set!
2400 the-last-stack
2401 (case (stack-id #t)
2402 ((repl-stack)
2403 (apply make-stack #t save-stack eval #t 0 narrowing))
2404 ((load-stack)
2405 (apply make-stack #t save-stack 0 #t 0 narrowing))
2406 ((tk-stack)
2407 (apply make-stack #t save-stack tk-stack-mark #t 0 narrowing))
2408 ((#t)
2409 (apply make-stack #t save-stack 0 1 narrowing))
2410 (else
2411 (let ((id (stack-id #t)))
2412 (and (procedure? id)
2413 (apply make-stack #t save-stack id #t 0 narrowing))))))
2414 (set! stack-saved? #t)))))
1c6cd8e8 2415
3e3cec45
MD
2416(define before-error-hook (make-hook))
2417(define after-error-hook (make-hook))
2418(define before-backtrace-hook (make-hook))
2419(define after-backtrace-hook (make-hook))
1c6cd8e8 2420
21ed9efe
MD
2421(define has-shown-debugger-hint? #f)
2422
35c5db87
GH
2423(define (handle-system-error key . args)
2424 (let ((cep (current-error-port)))
8bb7f646 2425 (cond ((not (stack? (fluid-ref the-last-stack))))
21ed9efe 2426 ((memq 'backtrace (debug-options-interface))
04efd24d 2427 (run-hook before-backtrace-hook)
21ed9efe 2428 (newline cep)
755457ec 2429 (display "Backtrace:\n")
8bb7f646 2430 (display-backtrace (fluid-ref the-last-stack) cep)
21ed9efe 2431 (newline cep)
04efd24d
MD
2432 (run-hook after-backtrace-hook)))
2433 (run-hook before-error-hook)
8bb7f646 2434 (apply display-error (fluid-ref the-last-stack) cep args)
04efd24d 2435 (run-hook after-error-hook)
35c5db87
GH
2436 (force-output cep)
2437 (throw 'abort key)))
21ed9efe 2438
0f2d19dd
JB
2439(define (quit . args)
2440 (apply throw 'quit args))
2441
7950df7c
GH
2442(define exit quit)
2443
d590bbf6
MD
2444;;(define has-shown-backtrace-hint? #f) Defined by scm_init_backtrace ()
2445
2446;; Replaced by C code:
2447;;(define (backtrace)
8bb7f646 2448;; (if (fluid-ref the-last-stack)
d590bbf6
MD
2449;; (begin
2450;; (newline)
8bb7f646 2451;; (display-backtrace (fluid-ref the-last-stack) (current-output-port))
d590bbf6
MD
2452;; (newline)
2453;; (if (and (not has-shown-backtrace-hint?)
2454;; (not (memq 'backtrace (debug-options-interface))))
2455;; (begin
2456;; (display
2457;;"Type \"(debug-enable 'backtrace)\" if you would like a backtrace
2458;;automatically if an error occurs in the future.\n")
2459;; (set! has-shown-backtrace-hint? #t))))
2460;; (display "No backtrace available.\n")))
21ed9efe 2461
0f2d19dd
JB
2462(define (error-catching-repl r e p)
2463 (error-catching-loop (lambda () (p (e (r))))))
2464
2465(define (gc-run-time)
2466 (cdr (assq 'gc-time-taken (gc-stats))))
2467
3e3cec45
MD
2468(define before-read-hook (make-hook))
2469(define after-read-hook (make-hook))
1c6cd8e8 2470
dc5c2038
MD
2471;;; The default repl-reader function. We may override this if we've
2472;;; the readline library.
2473(define repl-reader
2474 (lambda (prompt)
2475 (display prompt)
2476 (force-output)
04efd24d 2477 (run-hook before-read-hook)
dc5c2038
MD
2478 (read (current-input-port))))
2479
0f2d19dd
JB
2480(define (scm-style-repl)
2481 (letrec (
2482 (start-gc-rt #f)
2483 (start-rt #f)
0f2d19dd
JB
2484 (repl-report-start-timing (lambda ()
2485 (set! start-gc-rt (gc-run-time))
2486 (set! start-rt (get-internal-run-time))))
2487 (repl-report (lambda ()
2488 (display ";;; ")
2489 (display (inexact->exact
2490 (* 1000 (/ (- (get-internal-run-time) start-rt)
2491 internal-time-units-per-second))))
2492 (display " msec (")
2493 (display (inexact->exact
2494 (* 1000 (/ (- (gc-run-time) start-gc-rt)
2495 internal-time-units-per-second))))
2496 (display " msec in gc)\n")))
480977d0
JB
2497
2498 (consume-trailing-whitespace
2499 (lambda ()
2500 (let ((ch (peek-char)))
2501 (cond
2502 ((eof-object? ch))
2503 ((or (char=? ch #\space) (char=? ch #\tab))
2504 (read-char)
2505 (consume-trailing-whitespace))
2506 ((char=? ch #\newline)
2507 (read-char))))))
0f2d19dd 2508 (-read (lambda ()
dc5c2038
MD
2509 (let ((val
2510 (let ((prompt (cond ((string? scm-repl-prompt)
2511 scm-repl-prompt)
2512 ((thunk? scm-repl-prompt)
2513 (scm-repl-prompt))
2514 (scm-repl-prompt "> ")
2515 (else ""))))
2516 (repl-reader prompt))))
2517
480977d0 2518 ;; As described in R4RS, the READ procedure updates the
e13c54c4 2519 ;; port to point to the first character past the end of
480977d0
JB
2520 ;; the external representation of the object. This
2521 ;; means that it doesn't consume the newline typically
2522 ;; found after an expression. This means that, when
2523 ;; debugging Guile with GDB, GDB gets the newline, which
2524 ;; it often interprets as a "continue" command, making
2525 ;; breakpoints kind of useless. So, consume any
2526 ;; trailing newline here, as well as any whitespace
2527 ;; before it.
e13c54c4
JB
2528 ;; But not if EOF, for control-D.
2529 (if (not (eof-object? val))
2530 (consume-trailing-whitespace))
04efd24d 2531 (run-hook after-read-hook)
0f2d19dd
JB
2532 (if (eof-object? val)
2533 (begin
7950df7c 2534 (repl-report-start-timing)
0f2d19dd
JB
2535 (if scm-repl-verbose
2536 (begin
2537 (newline)
2538 (display ";;; EOF -- quitting")
2539 (newline)))
2540 (quit 0)))
2541 val)))
2542
2543 (-eval (lambda (sourc)
2544 (repl-report-start-timing)
4cdee789 2545 (start-stack 'repl-stack (eval sourc))))
0f2d19dd
JB
2546
2547 (-print (lambda (result)
2548 (if (not scm-repl-silent)
2549 (begin
21ed9efe
MD
2550 (if (or scm-repl-print-unspecified
2551 (not (unspecified? result)))
2552 (begin
2553 (write result)
2554 (newline)))
0f2d19dd
JB
2555 (if scm-repl-verbose
2556 (repl-report))
2557 (force-output)))))
2558
8e44e7a0 2559 (-quit (lambda (args)
0f2d19dd
JB
2560 (if scm-repl-verbose
2561 (begin
2562 (display ";;; QUIT executed, repl exitting")
2563 (newline)
2564 (repl-report)))
8e44e7a0 2565 args))
0f2d19dd
JB
2566
2567 (-abort (lambda ()
2568 (if scm-repl-verbose
2569 (begin
2570 (display ";;; ABORT executed.")
2571 (newline)
2572 (repl-report)))
2573 (repl -read -eval -print))))
2574
8e44e7a0
GH
2575 (let ((status (error-catching-repl -read
2576 -eval
2577 -print)))
2578 (-quit status))))
2579
0f2d19dd 2580
0f2d19dd 2581\f
44cf1f0f 2582;;; {IOTA functions: generating lists of numbers}
0f2d19dd 2583
e69cd299
MD
2584(define (iota n)
2585 (let loop ((count (1- n)) (result '()))
2586 (if (< count 0) result
2587 (loop (1- count) (cons count result)))))
0f2d19dd
JB
2588
2589\f
2590;;; {While}
2591;;;
2592;;; with `continue' and `break'.
2593;;;
2594
2595(defmacro while (cond . body)
2596 `(letrec ((continue (lambda () (or (not ,cond) (begin (begin ,@ body) (continue)))))
2597 (break (lambda val (apply throw 'break val))))
2598 (catch 'break
2599 (lambda () (continue))
2600 (lambda v (cadr v)))))
2601
7398c2c2
MD
2602;;; {collect}
2603;;;
2604;;; Similar to `begin' but returns a list of the results of all constituent
2605;;; forms instead of the result of the last form.
2606;;; (The definition relies on the current left-to-right
2607;;; order of evaluation of operands in applications.)
2608
2609(defmacro collect forms
2610 (cons 'list forms))
0f2d19dd 2611
8a6a8671
MV
2612;;; {with-fluids}
2613
2614;; with-fluids is a convenience wrapper for the builtin procedure
2615;; `with-fluids*'. The syntax is just like `let':
2616;;
2617;; (with-fluids ((fluid val)
2618;; ...)
2619;; body)
2620
2621(defmacro with-fluids (bindings . body)
2622 `(with-fluids* (list ,@(map car bindings)) (list ,@(map cadr bindings))
2623 (lambda () ,@body)))
2624
dc61592f
MD
2625;;; Environments
2626
2627(define the-environment
2628 (procedure->syntax
2629 (lambda (x e)
2630 e)))
2631
9705d5c2 2632(define (environment-module env)
baa47a94 2633 (let ((closure (and (pair? env) (car (last-pair env)))))
edc185c7 2634 (and closure (procedure-property closure 'module))))
bf3c93d1 2635
0f2d19dd
JB
2636\f
2637
2638;;; {Macros}
2639;;;
2640
2641;; actually....hobbit might be able to hack these with a little
2642;; coaxing
2643;;
2644
2645(defmacro define-macro (first . rest)
2646 (let ((name (if (symbol? first) first (car first)))
2647 (transformer
2648 (if (symbol? first)
2649 (car rest)
2650 `(lambda ,(cdr first) ,@rest))))
2651 `(define ,name (defmacro:transformer ,transformer))))
2652
2653
2654(defmacro define-syntax-macro (first . rest)
2655 (let ((name (if (symbol? first) first (car first)))
2656 (transformer
2657 (if (symbol? first)
2658 (car rest)
2659 `(lambda ,(cdr first) ,@rest))))
2660 `(define ,name (defmacro:syntax-transformer ,transformer))))
2661\f
2662;;; {Module System Macros}
2663;;;
2664
2665(defmacro define-module args
2666 `(let* ((process-define-module process-define-module)
2667 (set-current-module set-current-module)
2668 (module (process-define-module ',args)))
2669 (set-current-module module)
2670 module))
2671
89da9036
MV
2672;; the guts of the use-modules macro. add the interfaces of the named
2673;; modules to the use-list of the current module, in order
2674(define (process-use-modules module-names)
2675 (for-each (lambda (module-name)
2676 (let ((mod-iface (resolve-interface module-name)))
2677 (or mod-iface
2678 (error "no such module" module-name))
2679 (module-use! (current-module) mod-iface)))
2680 (reverse module-names)))
2681
33cf699f 2682(defmacro use-modules modules
89da9036 2683 `(process-use-modules ',modules))
33cf699f 2684
cf266109 2685(defmacro use-syntax (spec)
7cbaee0c
MD
2686 `(begin
2687 ,@(if (pair? spec)
2688 `((process-use-modules ',(list spec))
2689 (set-module-transformer! (current-module)
2690 ,(car (last-pair spec))))
2691 `((set-module-transformer! (current-module) ,spec)))
bd0fb3cf 2692 (fluid-set! scm:eval-transformer (module-transformer (current-module)))))
7a0ff2f8 2693
0f2d19dd
JB
2694(define define-private define)
2695
2696(defmacro define-public args
2697 (define (syntax)
2698 (error "bad syntax" (list 'define-public args)))
2699 (define (defined-name n)
2700 (cond
3c5af9ef
JB
2701 ((symbol? n) n)
2702 ((pair? n) (defined-name (car n)))
2703 (else (syntax))))
0f2d19dd 2704 (cond
3c5af9ef
JB
2705 ((null? args) (syntax))
2706
2707 (#t (let ((name (defined-name (car args))))
2708 `(begin
2709 (let ((public-i (module-public-interface (current-module))))
2710 ;; Make sure there is a local variable:
2711 ;;
2712 (module-define! (current-module)
2713 ',name
2714 (module-ref (current-module) ',name #f))
0f2d19dd 2715
3c5af9ef
JB
2716 ;; Make sure that local is exported:
2717 ;;
2718 (module-add! public-i ',name
2719 (module-variable (current-module) ',name)))
0f2d19dd 2720
3c5af9ef
JB
2721 ;; Now (re)define the var normally. Bernard URBAN
2722 ;; suggests we use eval here to accomodate Hobbit; it lets
2723 ;; the interpreter handle the define-private form, which
2724 ;; Hobbit can't digest.
2725 (eval '(define-private ,@ args)))))))
0f2d19dd
JB
2726
2727
2728
2729(defmacro defmacro-public args
2730 (define (syntax)
2731 (error "bad syntax" (list 'defmacro-public args)))
2732 (define (defined-name n)
2733 (cond
2734 ((symbol? n) n)
2735 (else (syntax))))
2736 (cond
2737 ((null? args) (syntax))
2738
2739 (#t (let ((name (defined-name (car args))))
2740 `(begin
2741 (let ((public-i (module-public-interface (current-module))))
2742 ;; Make sure there is a local variable:
2743 ;;
2744 (module-define! (current-module)
2745 ',name
2746 (module-ref (current-module) ',name #f))
2747
2748 ;; Make sure that local is exported:
2749 ;;
2750 (module-add! public-i ',name (module-variable (current-module) ',name)))
2751
2752 ;; Now (re)define the var normally.
2753 ;;
2754 (defmacro ,@ args))))))
2755
2756
90847923
MD
2757(define (module-export! m names)
2758 (let ((public-i (module-public-interface m)))
2759 (for-each (lambda (name)
2760 ;; Make sure there is a local variable:
2761 (module-define! m name (module-ref m name #f))
2762 ;; Make sure that local is exported:
2763 (module-add! public-i name (module-variable m name)))
2764 names)))
2765
a0cc0a01 2766(defmacro export names
90847923 2767 `(module-export! (current-module) ',names))
a0cc0a01
MD
2768
2769(define export-syntax export)
2770
2771
0f2d19dd
JB
2772(define load load-module)
2773
2774
2775\f
9aca88c3
JB
2776;;; {Load emacs interface support if emacs option is given.}
2777
2778(define (load-emacs-interface)
2779 (if (memq 'debug-extensions *features*)
2780 (debug-enable 'backtrace))
2781 (define-module (guile-user) :use-module (ice-9 emacs)))
2782
2783\f
0f2d19dd 2784
755457ec
MD
2785(define using-readline?
2786 (let ((using-readline? (make-fluid)))
2787 (make-procedure-with-setter
2788 (lambda () (fluid-ref using-readline?))
2789 (lambda (v) (fluid-set! using-readline? v)))))
2790
e1a191a8
GH
2791;; this is just (scm-style-repl) with a wrapper to install and remove
2792;; signal handlers.
8e44e7a0 2793(define (top-repl)
9aca88c3
JB
2794
2795 ;; Load emacs interface support if emacs option is given.
2796 (if (and (module-defined? the-root-module 'use-emacs-interface)
2797 use-emacs-interface)
2798 (load-emacs-interface))
2799
4fdf8b2c 2800 ;; Place the user in the guile-user module.
00b33968 2801 (define-module (guile-user)
6b64c19b 2802 :use-module (guile) ;so that bindings will be checked here first
00b33968
MD
2803 :use-module (ice-9 session)
2804 :use-module (ice-9 debug)
6b64c19b 2805 :autoload (ice-9 debugger) (debug)) ;load debugger on demand
00b33968
MD
2806 (if (memq 'threads *features*)
2807 (define-module (guile-user) :use-module (ice-9 threads)))
2808 (if (memq 'regex *features*)
2809 (define-module (guile-user) :use-module (ice-9 regex)))
4fdf8b2c 2810
e1a191a8 2811 (let ((old-handlers #f)
52cfc69b
GH
2812 (signals (if (provided? 'posix)
2813 `((,SIGINT . "User interrupt")
2814 (,SIGFPE . "Arithmetic error")
2815 (,SIGBUS . "Bad memory access (bus error)")
2816 (,SIGSEGV .
2817 "Bad memory access (Segmentation violation)"))
2818 '())))
e1a191a8
GH
2819
2820 (dynamic-wind
2821
2822 ;; call at entry
2823 (lambda ()
2824 (let ((make-handler (lambda (msg)
2825 (lambda (sig)
8087b6be
MD
2826 ;; Make a backup copy of the stack
2827 (fluid-set! before-signal-stack
2828 (fluid-ref the-last-stack))
096d5f90 2829 (save-stack %deliver-signals)
e1a191a8
GH
2830 (scm-error 'signal
2831 #f
2832 msg
2833 #f
2834 (list sig))))))
2835 (set! old-handlers
2836 (map (lambda (sig-msg)
2837 (sigaction (car sig-msg)
2838 (make-handler (cdr sig-msg))))
2839 signals))))
2840
2841 ;; the protected thunk.
2842 (lambda ()
2055a1bc 2843 (let ((status (scm-style-repl)))
04efd24d 2844 (run-hook exit-hook)
2055a1bc 2845 status))
e1a191a8
GH
2846
2847 ;; call at exit.
2848 (lambda ()
2849 (map (lambda (sig-msg old-handler)
2850 (if (not (car old-handler))
2851 ;; restore original C handler.
2852 (sigaction (car sig-msg) #f)
2853 ;; restore Scheme handler, SIG_IGN or SIG_DFL.
2854 (sigaction (car sig-msg)
2855 (car old-handler)
2856 (cdr old-handler))))
bd9e24b3 2857 signals old-handlers)))))
0f2d19dd 2858
02b754d3
GH
2859(defmacro false-if-exception (expr)
2860 `(catch #t (lambda () ,expr)
2861 (lambda args #f)))
2862
2055a1bc
MD
2863;;; This hook is run at the very end of an interactive session.
2864;;;
3e3cec45 2865(define exit-hook (make-hook))
2055a1bc 2866
4d31f0da
JB
2867\f
2868(define-module (guile))
9946dd45 2869
13e341bb 2870(append! %load-path (cons "." ()))