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