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