remove the-last-stack from boot-9
[bpt/guile.git] / module / ice-9 / boot-9.scm
1 ;;; -*- mode: scheme; coding: utf-8; -*-
2
3 ;;;; Copyright (C) 1995,1996,1997,1998,1999,2000,2001,2002,2003,2004,2005,2006,2007,2008,2009,2010
4 ;;;; Free Software Foundation, Inc.
5 ;;;;
6 ;;;; This library is free software; you can redistribute it and/or
7 ;;;; modify it under the terms of the GNU Lesser General Public
8 ;;;; License as published by the Free Software Foundation; either
9 ;;;; version 3 of the License, or (at your option) any later version.
10 ;;;;
11 ;;;; This library is distributed in the hope that it will be useful,
12 ;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
13 ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 ;;;; Lesser General Public License for more details.
15 ;;;;
16 ;;;; You should have received a copy of the GNU Lesser General Public
17 ;;;; License along with this library; if not, write to the Free Software
18 ;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19 ;;;;
20
21 \f
22
23 ;;; Commentary:
24
25 ;;; This file is the first thing loaded into Guile. It adds many mundane
26 ;;; definitions and a few that are interesting.
27 ;;;
28 ;;; The module system (hence the hierarchical namespace) are defined in this
29 ;;; file.
30 ;;;
31
32 ;;; Code:
33
34 \f
35
36 ;; Before compiling, make sure any symbols are resolved in the (guile)
37 ;; module, the primary location of those symbols, rather than in
38 ;; (guile-user), the default module that we compile in.
39
40 (eval-when (compile)
41 (set-current-module (resolve-module '(guile))))
42
43 \f
44
45 ;;; {Error handling}
46 ;;;
47
48 ;; Define delimited continuation operators, and implement catch and throw in
49 ;; terms of them.
50
51 (define make-prompt-tag
52 (lambda* (#:optional (stem "prompt"))
53 (gensym stem)))
54
55 (define default-prompt-tag
56 ;; not sure if we should expose this to the user as a fluid
57 (let ((%default-prompt-tag (make-prompt-tag)))
58 (lambda ()
59 %default-prompt-tag)))
60
61 (define (call-with-prompt tag thunk handler)
62 (@prompt tag (thunk) handler))
63 (define (abort-to-prompt tag . args)
64 (@abort tag args))
65
66
67 ;; Define catch and with-throw-handler, using some common helper routines and a
68 ;; shared fluid. Hide the helpers in a lexical contour.
69
70 (let ()
71 ;; Ideally we'd like to be able to give these default values for all threads,
72 ;; even threads not created by Guile; but alack, that does not currently seem
73 ;; possible. So wrap the getters in thunks.
74 (define %running-exception-handlers (make-fluid))
75 (define %exception-handler (make-fluid))
76
77 (define (running-exception-handlers)
78 (or (fluid-ref %running-exception-handlers)
79 (begin
80 (fluid-set! %running-exception-handlers '())
81 '())))
82 (define (exception-handler)
83 (or (fluid-ref %exception-handler)
84 (begin
85 (fluid-set! %exception-handler default-exception-handler)
86 default-exception-handler)))
87
88 (define (default-exception-handler k . args)
89 (cond
90 ((eq? k 'quit)
91 (primitive-exit (cond
92 ((not (pair? args)) 0)
93 ((integer? (car args)) (car args))
94 ((not (car args)) 1)
95 (else 0))))
96 (else
97 (format (current-error-port) "guile: uncaught throw to ~a: ~a\n" k args)
98 (primitive-exit 1))))
99
100 (define (default-throw-handler prompt-tag catch-k)
101 (let ((prev (exception-handler)))
102 (lambda (thrown-k . args)
103 (if (or (eq? thrown-k catch-k) (eqv? catch-k #t))
104 (apply abort-to-prompt prompt-tag thrown-k args)
105 (apply prev thrown-k args)))))
106
107 (define (custom-throw-handler prompt-tag catch-k pre)
108 (let ((prev (exception-handler)))
109 (lambda (thrown-k . args)
110 (if (or (eq? thrown-k catch-k) (eqv? catch-k #t))
111 (let ((running (running-exception-handlers)))
112 (with-fluids ((%running-exception-handlers (cons pre running)))
113 (if (not (memq pre running))
114 (apply pre thrown-k args))
115 ;; fall through
116 (if prompt-tag
117 (apply abort-to-prompt prompt-tag thrown-k args)
118 (apply prev thrown-k args))))
119 (apply prev thrown-k args)))))
120
121 (define! 'catch
122 (lambda* (k thunk handler #:optional pre-unwind-handler)
123 "Invoke @var{thunk} in the dynamic context of @var{handler} for
124 exceptions matching @var{key}. If thunk throws to the symbol
125 @var{key}, then @var{handler} is invoked this way:
126 @lisp
127 (handler key args ...)
128 @end lisp
129
130 @var{key} is a symbol or @code{#t}.
131
132 @var{thunk} takes no arguments. If @var{thunk} returns
133 normally, that is the return value of @code{catch}.
134
135 Handler is invoked outside the scope of its own @code{catch}.
136 If @var{handler} again throws to the same key, a new handler
137 from further up the call chain is invoked.
138
139 If the key is @code{#t}, then a throw to @emph{any} symbol will
140 match this call to @code{catch}.
141
142 If a @var{pre-unwind-handler} is given and @var{thunk} throws
143 an exception that matches @var{key}, Guile calls the
144 @var{pre-unwind-handler} before unwinding the dynamic state and
145 invoking the main @var{handler}. @var{pre-unwind-handler} should
146 be a procedure with the same signature as @var{handler}, that
147 is @code{(lambda (key . args))}. It is typically used to save
148 the stack at the point where the exception occurred, but can also
149 query other parts of the dynamic state at that point, such as
150 fluid values.
151
152 A @var{pre-unwind-handler} can exit either normally or non-locally.
153 If it exits normally, Guile unwinds the stack and dynamic context
154 and then calls the normal (third argument) handler. If it exits
155 non-locally, that exit determines the continuation."
156 (if (not (or (symbol? k) (eqv? k #t)))
157 (scm-error "catch" 'wrong-type-arg
158 "Wrong type argument in position ~a: ~a"
159 (list 1 k) (list k)))
160 (let ((tag (make-prompt-tag "catch")))
161 (call-with-prompt
162 tag
163 (lambda ()
164 (with-fluids
165 ((%exception-handler
166 (if pre-unwind-handler
167 (custom-throw-handler tag k pre-unwind-handler)
168 (default-throw-handler tag k))))
169 (thunk)))
170 (lambda (cont k . args)
171 (apply handler k args))))))
172
173 (define! 'with-throw-handler
174 (lambda (k thunk pre-unwind-handler)
175 "Add @var{handler} to the dynamic context as a throw handler
176 for key @var{key}, then invoke @var{thunk}."
177 (if (not (or (symbol? k) (eqv? k #t)))
178 (scm-error "with-throw-handler" 'wrong-type-arg
179 "Wrong type argument in position ~a: ~a"
180 (list 1 k) (list k)))
181 (with-fluids ((%exception-handler
182 (custom-throw-handler #f k pre-unwind-handler)))
183 (thunk))))
184
185 (define! 'throw
186 (lambda (key . args)
187 "Invoke the catch form matching @var{key}, passing @var{args} to the
188 @var{handler}.
189
190 @var{key} is a symbol. It will match catches of the same symbol or of @code{#t}.
191
192 If there is no handler at all, Guile prints an error and then exits."
193 (if (not (symbol? key))
194 ((exception-handler) 'wrong-type-arg "throw"
195 "Wrong type argument in position ~a: ~a" (list 1 key) (list key))
196 (apply (exception-handler) key args)))))
197
198
199 \f
200
201 ;;; {R4RS compliance}
202 ;;;
203
204 (primitive-load-path "ice-9/r4rs")
205
206 \f
207
208 ;;; {Simple Debugging Tools}
209 ;;;
210
211 ;; peek takes any number of arguments, writes them to the
212 ;; current ouput port, and returns the last argument.
213 ;; It is handy to wrap around an expression to look at
214 ;; a value each time is evaluated, e.g.:
215 ;;
216 ;; (+ 10 (troublesome-fn))
217 ;; => (+ 10 (pk 'troublesome-fn-returned (troublesome-fn)))
218 ;;
219
220 (define (peek . stuff)
221 (newline)
222 (display ";;; ")
223 (write stuff)
224 (newline)
225 (car (last-pair stuff)))
226
227 (define pk peek)
228
229
230 (define (warn . stuff)
231 (with-output-to-port (current-error-port)
232 (lambda ()
233 (newline)
234 (display ";;; WARNING ")
235 (display stuff)
236 (newline)
237 (car (last-pair stuff)))))
238
239 \f
240
241 ;;; {Features}
242 ;;;
243
244 (define (provide sym)
245 (if (not (memq sym *features*))
246 (set! *features* (cons sym *features*))))
247
248 ;; Return #t iff FEATURE is available to this Guile interpreter. In SLIB,
249 ;; provided? also checks to see if the module is available. We should do that
250 ;; too, but don't.
251
252 (define (provided? feature)
253 (and (memq feature *features*) #t))
254
255 \f
256
257 ;;; {Structs}
258 ;;;
259
260 (define (make-struct/no-tail vtable . args)
261 (apply make-struct vtable 0 args))
262
263 \f
264
265 ;;; {and-map and or-map}
266 ;;;
267 ;;; (and-map fn lst) is like (and (fn (car lst)) (fn (cadr lst)) (fn...) ...)
268 ;;; (or-map fn lst) is like (or (fn (car lst)) (fn (cadr lst)) (fn...) ...)
269 ;;;
270
271 ;; and-map f l
272 ;;
273 ;; Apply f to successive elements of l until exhaustion or f returns #f.
274 ;; If returning early, return #f. Otherwise, return the last value returned
275 ;; by f. If f has never been called because l is empty, return #t.
276 ;;
277 (define (and-map f lst)
278 (let loop ((result #t)
279 (l lst))
280 (and result
281 (or (and (null? l)
282 result)
283 (loop (f (car l)) (cdr l))))))
284
285 ;; or-map f l
286 ;;
287 ;; Apply f to successive elements of l until exhaustion or while f returns #f.
288 ;; If returning early, return the return value of f.
289 ;;
290 (define (or-map f lst)
291 (let loop ((result #f)
292 (l lst))
293 (or result
294 (and (not (null? l))
295 (loop (f (car l)) (cdr l))))))
296
297 \f
298
299 ;; let format alias simple-format until the more complete version is loaded
300
301 (define format simple-format)
302
303 ;; this is scheme wrapping the C code so the final pred call is a tail call,
304 ;; per SRFI-13 spec
305 (define string-any
306 (lambda* (char_pred s #:optional (start 0) (end (string-length s)))
307 (if (and (procedure? char_pred)
308 (> end start)
309 (<= end (string-length s))) ;; let c-code handle range error
310 (or (string-any-c-code char_pred s start (1- end))
311 (char_pred (string-ref s (1- end))))
312 (string-any-c-code char_pred s start end))))
313
314 ;; this is scheme wrapping the C code so the final pred call is a tail call,
315 ;; per SRFI-13 spec
316 (define string-every
317 (lambda* (char_pred s #:optional (start 0) (end (string-length s)))
318 (if (and (procedure? char_pred)
319 (> end start)
320 (<= end (string-length s))) ;; let c-code handle range error
321 (and (string-every-c-code char_pred s start (1- end))
322 (char_pred (string-ref s (1- end))))
323 (string-every-c-code char_pred s start end))))
324
325 ;; A variant of string-fill! that we keep for compatability
326 ;;
327 (define (substring-fill! str start end fill)
328 (string-fill! str fill start end))
329
330 \f
331
332 ;; Define a minimal stub of the module API for psyntax, before modules
333 ;; have booted.
334 (define (module-name x)
335 '(guile))
336 (define (module-define! module sym val)
337 (let ((v (hashq-ref (%get-pre-modules-obarray) sym)))
338 (if v
339 (variable-set! v val)
340 (hashq-set! (%get-pre-modules-obarray) sym
341 (make-variable val)))))
342 (define (module-ref module sym)
343 (let ((v (module-variable module sym)))
344 (if v (variable-ref v) (error "badness!" (pk module) (pk sym)))))
345 (define (resolve-module . args)
346 #f)
347
348 ;; API provided by psyntax
349 (define syntax-violation #f)
350 (define datum->syntax #f)
351 (define syntax->datum #f)
352 (define syntax-source #f)
353 (define identifier? #f)
354 (define generate-temporaries #f)
355 (define bound-identifier=? #f)
356 (define free-identifier=? #f)
357
358 ;; $sc-dispatch is an implementation detail of psyntax. It is used by
359 ;; expanded macros, to dispatch an input against a set of patterns.
360 (define $sc-dispatch #f)
361
362 ;; Load it up!
363 (primitive-load-path "ice-9/psyntax-pp")
364 ;; The binding for `macroexpand' has now been overridden, making psyntax the
365 ;; expander now.
366
367 (define-syntax and
368 (syntax-rules ()
369 ((_) #t)
370 ((_ x) x)
371 ((_ x y ...) (if x (and y ...) #f))))
372
373 (define-syntax or
374 (syntax-rules ()
375 ((_) #f)
376 ((_ x) x)
377 ((_ x y ...) (let ((t x)) (if t t (or y ...))))))
378
379 ;; The "maybe-more" bits are something of a hack, so that we can support
380 ;; SRFI-61. Rewrites into a standalone syntax-case macro would be
381 ;; appreciated.
382 (define-syntax cond
383 (syntax-rules (=> else)
384 ((_ "maybe-more" test consequent)
385 (if test consequent))
386
387 ((_ "maybe-more" test consequent clause ...)
388 (if test consequent (cond clause ...)))
389
390 ((_ (else else1 else2 ...))
391 (begin else1 else2 ...))
392
393 ((_ (test => receiver) more-clause ...)
394 (let ((t test))
395 (cond "maybe-more" t (receiver t) more-clause ...)))
396
397 ((_ (generator guard => receiver) more-clause ...)
398 (call-with-values (lambda () generator)
399 (lambda t
400 (cond "maybe-more"
401 (apply guard t) (apply receiver t) more-clause ...))))
402
403 ((_ (test => receiver ...) more-clause ...)
404 (syntax-violation 'cond "wrong number of receiver expressions"
405 '(test => receiver ...)))
406 ((_ (generator guard => receiver ...) more-clause ...)
407 (syntax-violation 'cond "wrong number of receiver expressions"
408 '(generator guard => receiver ...)))
409
410 ((_ (test) more-clause ...)
411 (let ((t test))
412 (cond "maybe-more" t t more-clause ...)))
413
414 ((_ (test body1 body2 ...) more-clause ...)
415 (cond "maybe-more"
416 test (begin body1 body2 ...) more-clause ...))))
417
418 (define-syntax case
419 (syntax-rules (else)
420 ((case (key ...)
421 clauses ...)
422 (let ((atom-key (key ...)))
423 (case atom-key clauses ...)))
424 ((case key
425 (else result1 result2 ...))
426 (begin result1 result2 ...))
427 ((case key
428 ((atoms ...) result1 result2 ...))
429 (if (memv key '(atoms ...))
430 (begin result1 result2 ...)))
431 ((case key
432 ((atoms ...) result1 result2 ...)
433 clause clauses ...)
434 (if (memv key '(atoms ...))
435 (begin result1 result2 ...)
436 (case key clause clauses ...)))))
437
438 (define-syntax do
439 (syntax-rules ()
440 ((do ((var init step ...) ...)
441 (test expr ...)
442 command ...)
443 (letrec
444 ((loop
445 (lambda (var ...)
446 (if test
447 (begin
448 (if #f #f)
449 expr ...)
450 (begin
451 command
452 ...
453 (loop (do "step" var step ...)
454 ...))))))
455 (loop init ...)))
456 ((do "step" x)
457 x)
458 ((do "step" x y)
459 y)))
460
461 (define-syntax delay
462 (syntax-rules ()
463 ((_ exp) (make-promise (lambda () exp)))))
464
465 (include-from-path "ice-9/quasisyntax")
466
467 (define-syntax current-source-location
468 (lambda (x)
469 (syntax-case x ()
470 ((_)
471 (with-syntax ((s (datum->syntax x (syntax-source x))))
472 #''s)))))
473
474
475 \f
476
477 ;;; {Defmacros}
478 ;;;
479
480 (define-syntax define-macro
481 (lambda (x)
482 "Define a defmacro."
483 (syntax-case x ()
484 ((_ (macro . args) doc body1 body ...)
485 (string? (syntax->datum #'doc))
486 #'(define-macro macro doc (lambda args body1 body ...)))
487 ((_ (macro . args) body ...)
488 #'(define-macro macro #f (lambda args body ...)))
489 ((_ macro doc transformer)
490 (or (string? (syntax->datum #'doc))
491 (not (syntax->datum #'doc)))
492 #'(define-syntax macro
493 (lambda (y)
494 doc
495 #((macro-type . defmacro)
496 (defmacro-args args))
497 (syntax-case y ()
498 ((_ . args)
499 (let ((v (syntax->datum #'args)))
500 (datum->syntax y (apply transformer v)))))))))))
501
502 (define-syntax defmacro
503 (lambda (x)
504 "Define a defmacro, with the old lispy defun syntax."
505 (syntax-case x ()
506 ((_ macro args doc body1 body ...)
507 (string? (syntax->datum #'doc))
508 #'(define-macro macro doc (lambda args body1 body ...)))
509 ((_ macro args body ...)
510 #'(define-macro macro #f (lambda args body ...))))))
511
512 (provide 'defmacro)
513
514 \f
515
516 ;;; {Deprecation}
517 ;;;
518 ;;; Depends on: defmacro
519 ;;;
520
521 (defmacro begin-deprecated forms
522 (if (include-deprecated-features)
523 `(begin ,@forms)
524 `(begin)))
525
526 \f
527
528 ;;; {Trivial Functions}
529 ;;;
530
531 (define (identity x) x)
532 (define (and=> value procedure) (and value (procedure value)))
533 (define call/cc call-with-current-continuation)
534
535 (define-syntax false-if-exception
536 (syntax-rules ()
537 ((_ expr)
538 (catch #t
539 (lambda () expr)
540 (lambda (k . args) #f)))))
541
542 \f
543
544 ;;; {General Properties}
545 ;;;
546
547 ;; Properties are a lispy way to associate random info with random objects.
548 ;; Traditionally properties are implemented as an alist or a plist actually
549 ;; pertaining to the object in question.
550 ;;
551 ;; These "object properties" have the advantage that they can be associated with
552 ;; any object, even if the object has no plist. Object properties are good when
553 ;; you are extending pre-existing objects in unexpected ways. They also present
554 ;; a pleasing, uniform procedure-with-setter interface. But if you have a data
555 ;; type that always has properties, it's often still best to store those
556 ;; properties within the object itself.
557
558 (define (make-object-property)
559 (let ((prop (primitive-make-property #f)))
560 (make-procedure-with-setter
561 (lambda (obj) (primitive-property-ref prop obj))
562 (lambda (obj val) (primitive-property-set! prop obj val)))))
563
564 \f
565
566 ;;; {Symbol Properties}
567 ;;;
568
569 ;;; Symbol properties are something you see in old Lisp code. In most current
570 ;;; Guile code, symbols are not used as a data structure -- they are used as
571 ;;; keys into other data structures.
572
573 (define (symbol-property sym prop)
574 (let ((pair (assoc prop (symbol-pref sym))))
575 (and pair (cdr pair))))
576
577 (define (set-symbol-property! sym prop val)
578 (let ((pair (assoc prop (symbol-pref sym))))
579 (if pair
580 (set-cdr! pair val)
581 (symbol-pset! sym (acons prop val (symbol-pref sym))))))
582
583 (define (symbol-property-remove! sym prop)
584 (let ((pair (assoc prop (symbol-pref sym))))
585 (if pair
586 (symbol-pset! sym (delq! pair (symbol-pref sym))))))
587
588 \f
589
590 ;;; {Arrays}
591 ;;;
592
593 (define (array-shape a)
594 (map (lambda (ind) (if (number? ind) (list 0 (+ -1 ind)) ind))
595 (array-dimensions a)))
596
597 \f
598
599 ;;; {Keywords}
600 ;;;
601
602 ;;; It's much better if you can use lambda* / define*, of course.
603
604 (define (kw-arg-ref args kw)
605 (let ((rem (member kw args)))
606 (and rem (pair? (cdr rem)) (cadr rem))))
607
608 \f
609
610 ;;; {Structs}
611 ;;;
612
613 (define (struct-layout s)
614 (struct-ref (struct-vtable s) vtable-index-layout))
615
616 \f
617
618 ;;; {Records}
619 ;;;
620
621 ;; Printing records: by default, records are printed as
622 ;;
623 ;; #<type-name field1: val1 field2: val2 ...>
624 ;;
625 ;; You can change that by giving a custom printing function to
626 ;; MAKE-RECORD-TYPE (after the list of field symbols). This function
627 ;; will be called like
628 ;;
629 ;; (<printer> object port)
630 ;;
631 ;; It should print OBJECT to PORT.
632
633 (define (inherit-print-state old-port new-port)
634 (if (get-print-state old-port)
635 (port-with-print-state new-port (get-print-state old-port))
636 new-port))
637
638 ;; 0: type-name, 1: fields, 2: constructor
639 (define record-type-vtable
640 ;; FIXME: This should just call make-vtable, not make-vtable-vtable; but for
641 ;; that we need to expose the bare vtable-vtable to Scheme.
642 (make-vtable-vtable "prprpw" 0
643 (lambda (s p)
644 (cond ((eq? s record-type-vtable)
645 (display "#<record-type-vtable>" p))
646 (else
647 (display "#<record-type " p)
648 (display (record-type-name s) p)
649 (display ">" p))))))
650
651 (define (record-type? obj)
652 (and (struct? obj) (eq? record-type-vtable (struct-vtable obj))))
653
654 (define* (make-record-type type-name fields #:optional printer)
655 ;; Pre-generate constructors for nfields < 20.
656 (define-syntax make-constructor
657 (lambda (x)
658 (define *max-static-argument-count* 20)
659 (define (make-formals n)
660 (let lp ((i 0))
661 (if (< i n)
662 (cons (datum->syntax
663 x
664 (string->symbol
665 (string (integer->char (+ (char->integer #\a) i)))))
666 (lp (1+ i)))
667 '())))
668 (syntax-case x ()
669 ((_ rtd exp) (not (identifier? #'exp))
670 #'(let ((n exp))
671 (make-constructor rtd n)))
672 ((_ rtd nfields)
673 #`(case nfields
674 #,@(let lp ((n 0))
675 (if (< n *max-static-argument-count*)
676 (cons (with-syntax (((formal ...) (make-formals n))
677 (n n))
678 #'((n)
679 (lambda (formal ...)
680 (make-struct rtd 0 formal ...))))
681 (lp (1+ n)))
682 '()))
683 (else
684 (lambda args
685 (if (= (length args) nfields)
686 (apply make-struct rtd 0 args)
687 (scm-error 'wrong-number-of-args
688 (format #f "make-~a" type-name)
689 "Wrong number of arguments" '() #f)))))))))
690
691 (define (default-record-printer s p)
692 (display "#<" p)
693 (display (record-type-name (record-type-descriptor s)) p)
694 (let loop ((fields (record-type-fields (record-type-descriptor s)))
695 (off 0))
696 (cond
697 ((not (null? fields))
698 (display " " p)
699 (display (car fields) p)
700 (display ": " p)
701 (display (struct-ref s off) p)
702 (loop (cdr fields) (+ 1 off)))))
703 (display ">" p))
704
705 (let ((rtd (make-struct record-type-vtable 0
706 (make-struct-layout
707 (apply string-append
708 (map (lambda (f) "pw") fields)))
709 (or printer default-record-printer)
710 type-name
711 (copy-tree fields))))
712 (struct-set! rtd (+ vtable-offset-user 2)
713 (make-constructor rtd (length fields)))
714 ;; Temporary solution: Associate a name to the record type descriptor
715 ;; so that the object system can create a wrapper class for it.
716 (set-struct-vtable-name! rtd (if (symbol? type-name)
717 type-name
718 (string->symbol type-name)))
719 rtd))
720
721 (define (record-type-name obj)
722 (if (record-type? obj)
723 (struct-ref obj vtable-offset-user)
724 (error 'not-a-record-type obj)))
725
726 (define (record-type-fields obj)
727 (if (record-type? obj)
728 (struct-ref obj (+ 1 vtable-offset-user))
729 (error 'not-a-record-type obj)))
730
731 (define* (record-constructor rtd #:optional field-names)
732 (if (not field-names)
733 (struct-ref rtd (+ 2 vtable-offset-user))
734 (primitive-eval
735 `(lambda ,field-names
736 (make-struct ',rtd 0 ,@(map (lambda (f)
737 (if (memq f field-names)
738 f
739 #f))
740 (record-type-fields rtd)))))))
741
742 (define (record-predicate rtd)
743 (lambda (obj) (and (struct? obj) (eq? rtd (struct-vtable obj)))))
744
745 (define (%record-type-error rtd obj) ;; private helper
746 (or (eq? rtd (record-type-descriptor obj))
747 (scm-error 'wrong-type-arg "%record-type-check"
748 "Wrong type record (want `~S'): ~S"
749 (list (record-type-name rtd) obj)
750 #f)))
751
752 (define (record-accessor rtd field-name)
753 (let ((pos (list-index (record-type-fields rtd) field-name)))
754 (if (not pos)
755 (error 'no-such-field field-name))
756 (lambda (obj)
757 (if (eq? (struct-vtable obj) rtd)
758 (struct-ref obj pos)
759 (%record-type-error rtd obj)))))
760
761 (define (record-modifier rtd field-name)
762 (let ((pos (list-index (record-type-fields rtd) field-name)))
763 (if (not pos)
764 (error 'no-such-field field-name))
765 (lambda (obj val)
766 (if (eq? (struct-vtable obj) rtd)
767 (struct-set! obj pos val)
768 (%record-type-error rtd obj)))))
769
770 (define (record? obj)
771 (and (struct? obj) (record-type? (struct-vtable obj))))
772
773 (define (record-type-descriptor obj)
774 (if (struct? obj)
775 (struct-vtable obj)
776 (error 'not-a-record obj)))
777
778 (provide 'record)
779
780 \f
781
782 ;;; {Booleans}
783 ;;;
784
785 (define (->bool x) (not (not x)))
786
787 \f
788
789 ;;; {Symbols}
790 ;;;
791
792 (define (symbol-append . args)
793 (string->symbol (apply string-append (map symbol->string args))))
794
795 (define (list->symbol . args)
796 (string->symbol (apply list->string args)))
797
798 (define (symbol . args)
799 (string->symbol (apply string args)))
800
801 \f
802
803 ;;; {Lists}
804 ;;;
805
806 (define (list-index l k)
807 (let loop ((n 0)
808 (l l))
809 (and (not (null? l))
810 (if (eq? (car l) k)
811 n
812 (loop (+ n 1) (cdr l))))))
813
814 \f
815
816 (if (provided? 'posix)
817 (primitive-load-path "ice-9/posix"))
818
819 (if (provided? 'socket)
820 (primitive-load-path "ice-9/networking"))
821
822 ;; For reference, Emacs file-exists-p uses stat in this same way.
823 (define file-exists?
824 (if (provided? 'posix)
825 (lambda (str)
826 (->bool (stat str #f)))
827 (lambda (str)
828 (let ((port (catch 'system-error (lambda () (open-file str OPEN_READ))
829 (lambda args #f))))
830 (if port (begin (close-port port) #t)
831 #f)))))
832
833 (define file-is-directory?
834 (if (provided? 'posix)
835 (lambda (str)
836 (eq? (stat:type (stat str)) 'directory))
837 (lambda (str)
838 (let ((port (catch 'system-error
839 (lambda () (open-file (string-append str "/.")
840 OPEN_READ))
841 (lambda args #f))))
842 (if port (begin (close-port port) #t)
843 #f)))))
844
845 (define (system-error-errno args)
846 (if (eq? (car args) 'system-error)
847 (car (list-ref args 4))
848 #f))
849
850 \f
851
852 ;;; {Error Handling}
853 ;;;
854
855 (define error
856 (case-lambda
857 (()
858 (scm-error 'misc-error #f "?" #f #f))
859 ((message . args)
860 (let ((msg (string-join (cons "~A" (make-list (length args) "~S")))))
861 (scm-error 'misc-error #f msg (cons message args) #f)))))
862
863 \f
864
865 ;;; {Time Structures}
866 ;;;
867
868 (define (tm:sec obj) (vector-ref obj 0))
869 (define (tm:min obj) (vector-ref obj 1))
870 (define (tm:hour obj) (vector-ref obj 2))
871 (define (tm:mday obj) (vector-ref obj 3))
872 (define (tm:mon obj) (vector-ref obj 4))
873 (define (tm:year obj) (vector-ref obj 5))
874 (define (tm:wday obj) (vector-ref obj 6))
875 (define (tm:yday obj) (vector-ref obj 7))
876 (define (tm:isdst obj) (vector-ref obj 8))
877 (define (tm:gmtoff obj) (vector-ref obj 9))
878 (define (tm:zone obj) (vector-ref obj 10))
879
880 (define (set-tm:sec obj val) (vector-set! obj 0 val))
881 (define (set-tm:min obj val) (vector-set! obj 1 val))
882 (define (set-tm:hour obj val) (vector-set! obj 2 val))
883 (define (set-tm:mday obj val) (vector-set! obj 3 val))
884 (define (set-tm:mon obj val) (vector-set! obj 4 val))
885 (define (set-tm:year obj val) (vector-set! obj 5 val))
886 (define (set-tm:wday obj val) (vector-set! obj 6 val))
887 (define (set-tm:yday obj val) (vector-set! obj 7 val))
888 (define (set-tm:isdst obj val) (vector-set! obj 8 val))
889 (define (set-tm:gmtoff obj val) (vector-set! obj 9 val))
890 (define (set-tm:zone obj val) (vector-set! obj 10 val))
891
892 (define (tms:clock obj) (vector-ref obj 0))
893 (define (tms:utime obj) (vector-ref obj 1))
894 (define (tms:stime obj) (vector-ref obj 2))
895 (define (tms:cutime obj) (vector-ref obj 3))
896 (define (tms:cstime obj) (vector-ref obj 4))
897
898 \f
899
900 ;;; {File Descriptors and Ports}
901 ;;;
902
903 (define file-position ftell)
904 (define* (file-set-position port offset #:optional (whence SEEK_SET))
905 (seek port offset whence))
906
907 (define (move->fdes fd/port fd)
908 (cond ((integer? fd/port)
909 (dup->fdes fd/port fd)
910 (close fd/port)
911 fd)
912 (else
913 (primitive-move->fdes fd/port fd)
914 (set-port-revealed! fd/port 1)
915 fd/port)))
916
917 (define (release-port-handle port)
918 (let ((revealed (port-revealed port)))
919 (if (> revealed 0)
920 (set-port-revealed! port (- revealed 1)))))
921
922 (define dup->port
923 (case-lambda
924 ((port/fd mode)
925 (fdopen (dup->fdes port/fd) mode))
926 ((port/fd mode new-fd)
927 (let ((port (fdopen (dup->fdes port/fd new-fd) mode)))
928 (set-port-revealed! port 1)
929 port))))
930
931 (define dup->inport
932 (case-lambda
933 ((port/fd)
934 (dup->port port/fd "r"))
935 ((port/fd new-fd)
936 (dup->port port/fd "r" new-fd))))
937
938 (define dup->outport
939 (case-lambda
940 ((port/fd)
941 (dup->port port/fd "w"))
942 ((port/fd new-fd)
943 (dup->port port/fd "w" new-fd))))
944
945 (define dup
946 (case-lambda
947 ((port/fd)
948 (if (integer? port/fd)
949 (dup->fdes port/fd)
950 (dup->port port/fd (port-mode port/fd))))
951 ((port/fd new-fd)
952 (if (integer? port/fd)
953 (dup->fdes port/fd new-fd)
954 (dup->port port/fd (port-mode port/fd) new-fd)))))
955
956 (define (duplicate-port port modes)
957 (dup->port port modes))
958
959 (define (fdes->inport fdes)
960 (let loop ((rest-ports (fdes->ports fdes)))
961 (cond ((null? rest-ports)
962 (let ((result (fdopen fdes "r")))
963 (set-port-revealed! result 1)
964 result))
965 ((input-port? (car rest-ports))
966 (set-port-revealed! (car rest-ports)
967 (+ (port-revealed (car rest-ports)) 1))
968 (car rest-ports))
969 (else
970 (loop (cdr rest-ports))))))
971
972 (define (fdes->outport fdes)
973 (let loop ((rest-ports (fdes->ports fdes)))
974 (cond ((null? rest-ports)
975 (let ((result (fdopen fdes "w")))
976 (set-port-revealed! result 1)
977 result))
978 ((output-port? (car rest-ports))
979 (set-port-revealed! (car rest-ports)
980 (+ (port-revealed (car rest-ports)) 1))
981 (car rest-ports))
982 (else
983 (loop (cdr rest-ports))))))
984
985 (define (port->fdes port)
986 (set-port-revealed! port (+ (port-revealed port) 1))
987 (fileno port))
988
989 (define (setenv name value)
990 (if value
991 (putenv (string-append name "=" value))
992 (putenv name)))
993
994 (define (unsetenv name)
995 "Remove the entry for NAME from the environment."
996 (putenv name))
997
998 \f
999
1000 ;;; {Load Paths}
1001 ;;;
1002
1003 (define (in-vicinity vicinity file)
1004 (let ((tail (let ((len (string-length vicinity)))
1005 (if (zero? len)
1006 #f
1007 (string-ref vicinity (- len 1))))))
1008 (string-append vicinity
1009 (if (or (not tail)
1010 (eq? tail #\/))
1011 ""
1012 "/")
1013 file)))
1014
1015 \f
1016
1017 ;;; {Help for scm_shell}
1018 ;;;
1019 ;;; The argument-processing code used by Guile-based shells generates
1020 ;;; Scheme code based on the argument list. This page contains help
1021 ;;; functions for the code it generates.
1022 ;;;
1023
1024 (define (command-line) (program-arguments))
1025
1026 ;; This is mostly for the internal use of the code generated by
1027 ;; scm_compile_shell_switches.
1028
1029 (define (turn-on-debugging)
1030 (debug-enable 'debug)
1031 (debug-enable 'backtrace)
1032 (read-enable 'positions))
1033
1034 (define (load-user-init)
1035 (let* ((home (or (getenv "HOME")
1036 (false-if-exception (passwd:dir (getpwuid (getuid))))
1037 "/")) ;; fallback for cygwin etc.
1038 (init-file (in-vicinity home ".guile")))
1039 (if (file-exists? init-file)
1040 (primitive-load init-file))))
1041
1042 \f
1043
1044 ;;; {The interpreter stack}
1045 ;;;
1046
1047 ;; %stacks defined in stacks.c
1048 (define (%start-stack tag thunk)
1049 (let ((prompt-tag (make-prompt-tag "start-stack")))
1050 (call-with-prompt
1051 prompt-tag
1052 (lambda ()
1053 (with-fluids ((%stacks (acons tag prompt-tag
1054 (or (fluid-ref %stacks) '()))))
1055 (thunk)))
1056 (lambda (k . args)
1057 (%start-stack tag (lambda () (apply k args)))))))
1058 (define-syntax start-stack
1059 (syntax-rules ()
1060 ((_ tag exp)
1061 (%start-stack tag (lambda () exp)))))
1062
1063 \f
1064
1065 ;;; {Loading by paths}
1066 ;;;
1067
1068 ;;; Load a Scheme source file named NAME, searching for it in the
1069 ;;; directories listed in %load-path, and applying each of the file
1070 ;;; name extensions listed in %load-extensions.
1071 (define (load-from-path name)
1072 (start-stack 'load-stack
1073 (primitive-load-path name)))
1074
1075 (define %load-verbosely #f)
1076 (define (assert-load-verbosity v) (set! %load-verbosely v))
1077
1078 (define (%load-announce file)
1079 (if %load-verbosely
1080 (with-output-to-port (current-error-port)
1081 (lambda ()
1082 (display ";;; ")
1083 (display "loading ")
1084 (display file)
1085 (newline)
1086 (force-output)))))
1087
1088 (set! %load-hook %load-announce)
1089
1090 (define* (load name #:optional reader)
1091 ;; Returns the .go file corresponding to `name'. Does not search load
1092 ;; paths, only the fallback path. If the .go file is missing or out of
1093 ;; date, and autocompilation is enabled, will try autocompilation, just
1094 ;; as primitive-load-path does internally. primitive-load is
1095 ;; unaffected. Returns #f if autocompilation failed or was disabled.
1096 ;;
1097 ;; NB: Unless we need to compile the file, this function should not cause
1098 ;; (system base compile) to be loaded up. For that reason compiled-file-name
1099 ;; partially duplicates functionality from (system base compile).
1100 (define (compiled-file-name canon-path)
1101 (and %compile-fallback-path
1102 (string-append
1103 %compile-fallback-path
1104 ;; no need for '/' separator here, canon-path is absolute
1105 canon-path
1106 (cond ((or (null? %load-compiled-extensions)
1107 (string-null? (car %load-compiled-extensions)))
1108 (warn "invalid %load-compiled-extensions"
1109 %load-compiled-extensions)
1110 ".go")
1111 (else (car %load-compiled-extensions))))))
1112 (define (fresh-compiled-file-name go-path)
1113 (catch #t
1114 (lambda ()
1115 (let* ((scmstat (stat name))
1116 (gostat (stat go-path #f)))
1117 (if (and gostat (= (stat:mtime gostat) (stat:mtime scmstat)))
1118 go-path
1119 (begin
1120 (if gostat
1121 (format (current-error-port)
1122 ";;; note: source file ~a\n;;; newer than compiled ~a\n"
1123 name go-path))
1124 (cond
1125 (%load-should-autocompile
1126 (%warn-autocompilation-enabled)
1127 (format (current-error-port) ";;; compiling ~a\n" name)
1128 ;; This use of @ is (ironically?) boot-safe, as modules have
1129 ;; not been booted yet, so the resolve-module call in psyntax
1130 ;; doesn't try to load a module, and compile-file will be
1131 ;; treated as a function, not a macro.
1132 (let ((cfn ((@ (system base compile) compile-file) name
1133 #:env (current-module))))
1134 (format (current-error-port) ";;; compiled ~a\n" cfn)
1135 cfn))
1136 (else #f))))))
1137 (lambda (k . args)
1138 (format (current-error-port)
1139 ";;; WARNING: compilation of ~a failed:\n;;; key ~a, throw_args ~s\n"
1140 name k args)
1141 #f)))
1142 (with-fluids ((current-reader reader))
1143 (let ((cfn (and=> (and=> (false-if-exception (canonicalize-path name))
1144 compiled-file-name)
1145 fresh-compiled-file-name)))
1146 (if cfn
1147 (load-compiled cfn)
1148 (start-stack 'load-stack
1149 (primitive-load name))))))
1150
1151 \f
1152
1153 ;;; {Reader Extensions}
1154 ;;;
1155 ;;; Reader code for various "#c" forms.
1156 ;;;
1157
1158 (define read-eval? (make-fluid))
1159 (fluid-set! read-eval? #f)
1160 (read-hash-extend #\.
1161 (lambda (c port)
1162 (if (fluid-ref read-eval?)
1163 (eval (read port) (interaction-environment))
1164 (error
1165 "#. read expansion found and read-eval? is #f."))))
1166
1167 \f
1168
1169 ;;; {Low Level Modules}
1170 ;;;
1171 ;;; These are the low level data structures for modules.
1172 ;;;
1173 ;;; Every module object is of the type 'module-type', which is a record
1174 ;;; consisting of the following members:
1175 ;;;
1176 ;;; - eval-closure: the function that defines for its module the strategy that
1177 ;;; shall be followed when looking up symbols in the module.
1178 ;;;
1179 ;;; An eval-closure is a function taking two arguments: the symbol to be
1180 ;;; looked up and a boolean value telling whether a binding for the symbol
1181 ;;; should be created if it does not exist yet. If the symbol lookup
1182 ;;; succeeded (either because an existing binding was found or because a new
1183 ;;; binding was created), a variable object representing the binding is
1184 ;;; returned. Otherwise, the value #f is returned. Note that the eval
1185 ;;; closure does not take the module to be searched as an argument: During
1186 ;;; construction of the eval-closure, the eval-closure has to store the
1187 ;;; module it belongs to in its environment. This means, that any
1188 ;;; eval-closure can belong to only one module.
1189 ;;;
1190 ;;; The eval-closure of a module can be defined arbitrarily. However, three
1191 ;;; special cases of eval-closures are to be distinguished: During startup
1192 ;;; the module system is not yet activated. In this phase, no modules are
1193 ;;; defined and all bindings are automatically stored by the system in the
1194 ;;; pre-modules-obarray. Since no eval-closures exist at this time, the
1195 ;;; functions which require an eval-closure as their argument need to be
1196 ;;; passed the value #f.
1197 ;;;
1198 ;;; The other two special cases of eval-closures are the
1199 ;;; standard-eval-closure and the standard-interface-eval-closure. Both
1200 ;;; behave equally for the case that no new binding is to be created. The
1201 ;;; difference between the two comes in, when the boolean argument to the
1202 ;;; eval-closure indicates that a new binding shall be created if it is not
1203 ;;; found.
1204 ;;;
1205 ;;; Given that no new binding shall be created, both standard eval-closures
1206 ;;; define the following standard strategy of searching bindings in the
1207 ;;; module: First, the module's obarray is searched for the symbol. Second,
1208 ;;; if no binding for the symbol was found in the module's obarray, the
1209 ;;; module's binder procedure is exececuted. If this procedure did not
1210 ;;; return a binding for the symbol, the modules referenced in the module's
1211 ;;; uses list are recursively searched for a binding of the symbol. If the
1212 ;;; binding can not be found in these modules also, the symbol lookup has
1213 ;;; failed.
1214 ;;;
1215 ;;; If a new binding shall be created, the standard-interface-eval-closure
1216 ;;; immediately returns indicating failure. That is, it does not even try
1217 ;;; to look up the symbol. In contrast, the standard-eval-closure would
1218 ;;; first search the obarray, and if no binding was found there, would
1219 ;;; create a new binding in the obarray, therefore not calling the binder
1220 ;;; procedure or searching the modules in the uses list.
1221 ;;;
1222 ;;; The explanation of the following members obarray, binder and uses
1223 ;;; assumes that the symbol lookup follows the strategy that is defined in
1224 ;;; the standard-eval-closure and the standard-interface-eval-closure.
1225 ;;;
1226 ;;; - obarray: a hash table that maps symbols to variable objects. In this
1227 ;;; hash table, the definitions are found that are local to the module (that
1228 ;;; is, not imported from other modules). When looking up bindings in the
1229 ;;; module, this hash table is searched first.
1230 ;;;
1231 ;;; - binder: either #f or a function taking a module and a symbol argument.
1232 ;;; If it is a function it is called after the obarray has been
1233 ;;; unsuccessfully searched for a binding. It then can provide bindings
1234 ;;; that would otherwise not be found locally in the module.
1235 ;;;
1236 ;;; - uses: a list of modules from which non-local bindings can be inherited.
1237 ;;; These modules are the third place queried for bindings after the obarray
1238 ;;; has been unsuccessfully searched and the binder function did not deliver
1239 ;;; a result either.
1240 ;;;
1241 ;;; - transformer: either #f or a function taking a scheme expression as
1242 ;;; delivered by read. If it is a function, it will be called to perform
1243 ;;; syntax transformations (e. g. makro expansion) on the given scheme
1244 ;;; expression. The output of the transformer function will then be passed
1245 ;;; to Guile's internal memoizer. This means that the output must be valid
1246 ;;; scheme code. The only exception is, that the output may make use of the
1247 ;;; syntax extensions provided to identify the modules that a binding
1248 ;;; belongs to.
1249 ;;;
1250 ;;; - name: the name of the module. This is used for all kinds of printing
1251 ;;; outputs. In certain places the module name also serves as a way of
1252 ;;; identification. When adding a module to the uses list of another
1253 ;;; module, it is made sure that the new uses list will not contain two
1254 ;;; modules of the same name.
1255 ;;;
1256 ;;; - kind: classification of the kind of module. The value is (currently?)
1257 ;;; only used for printing. It has no influence on how a module is treated.
1258 ;;; Currently the following values are used when setting the module kind:
1259 ;;; 'module, 'directory, 'interface, 'custom-interface. If no explicit kind
1260 ;;; is set, it defaults to 'module.
1261 ;;;
1262 ;;; - duplicates-handlers: a list of procedures that get called to make a
1263 ;;; choice between two duplicate bindings when name clashes occur. See the
1264 ;;; `duplicate-handlers' global variable below.
1265 ;;;
1266 ;;; - observers: a list of procedures that get called when the module is
1267 ;;; modified.
1268 ;;;
1269 ;;; - weak-observers: a weak-key hash table of procedures that get called
1270 ;;; when the module is modified. See `module-observe-weak' for details.
1271 ;;;
1272 ;;; In addition, the module may (must?) contain a binding for
1273 ;;; `%module-public-interface'. This variable should be bound to a module
1274 ;;; representing the exported interface of a module. See the
1275 ;;; `module-public-interface' and `module-export!' procedures.
1276 ;;;
1277 ;;; !!! warning: The interface to lazy binder procedures is going
1278 ;;; to be changed in an incompatible way to permit all the basic
1279 ;;; module ops to be virtualized.
1280 ;;;
1281 ;;; (make-module size use-list lazy-binding-proc) => module
1282 ;;; module-{obarray,uses,binder}[|-set!]
1283 ;;; (module? obj) => [#t|#f]
1284 ;;; (module-locally-bound? module symbol) => [#t|#f]
1285 ;;; (module-bound? module symbol) => [#t|#f]
1286 ;;; (module-symbol-locally-interned? module symbol) => [#t|#f]
1287 ;;; (module-symbol-interned? module symbol) => [#t|#f]
1288 ;;; (module-local-variable module symbol) => [#<variable ...> | #f]
1289 ;;; (module-variable module symbol) => [#<variable ...> | #f]
1290 ;;; (module-symbol-binding module symbol opt-value)
1291 ;;; => [ <obj> | opt-value | an error occurs ]
1292 ;;; (module-make-local-var! module symbol) => #<variable...>
1293 ;;; (module-add! module symbol var) => unspecified
1294 ;;; (module-remove! module symbol) => unspecified
1295 ;;; (module-for-each proc module) => unspecified
1296 ;;; (make-scm-module) => module ; a lazy copy of the symhash module
1297 ;;; (set-current-module module) => unspecified
1298 ;;; (current-module) => #<module...>
1299 ;;;
1300 ;;;
1301
1302 \f
1303
1304 ;;; {Printing Modules}
1305 ;;;
1306
1307 ;; This is how modules are printed. You can re-define it.
1308 (define (%print-module mod port)
1309 (display "#<" port)
1310 (display (or (module-kind mod) "module") port)
1311 (display " " port)
1312 (display (module-name mod) port)
1313 (display " " port)
1314 (display (number->string (object-address mod) 16) port)
1315 (display ">" port))
1316
1317 (letrec-syntax
1318 ;; Locally extend the syntax to allow record accessors to be defined at
1319 ;; compile-time. Cache the rtd locally to the constructor, the getters and
1320 ;; the setters, in order to allow for redefinition of the record type; not
1321 ;; relevant in the case of modules, but perhaps if we make this public, it
1322 ;; could matter.
1323
1324 ((define-record-type
1325 (lambda (x)
1326 (define (make-id scope . fragments)
1327 (datum->syntax #'scope
1328 (apply symbol-append
1329 (map (lambda (x)
1330 (if (symbol? x) x (syntax->datum x)))
1331 fragments))))
1332
1333 (define (getter rtd type-name field slot)
1334 #`(define #,(make-id rtd type-name '- field)
1335 (let ((rtd #,rtd))
1336 (lambda (#,type-name)
1337 (if (eq? (struct-vtable #,type-name) rtd)
1338 (struct-ref #,type-name #,slot)
1339 (%record-type-error rtd #,type-name))))))
1340
1341 (define (setter rtd type-name field slot)
1342 #`(define #,(make-id rtd 'set- type-name '- field '!)
1343 (let ((rtd #,rtd))
1344 (lambda (#,type-name val)
1345 (if (eq? (struct-vtable #,type-name) rtd)
1346 (struct-set! #,type-name #,slot val)
1347 (%record-type-error rtd #,type-name))))))
1348
1349 (define (accessors rtd type-name fields n exp)
1350 (syntax-case fields ()
1351 (() exp)
1352 (((field #:no-accessors) field* ...) (identifier? #'field)
1353 (accessors rtd type-name #'(field* ...) (1+ n)
1354 exp))
1355 (((field #:no-setter) field* ...) (identifier? #'field)
1356 (accessors rtd type-name #'(field* ...) (1+ n)
1357 #`(begin #,exp
1358 #,(getter rtd type-name #'field n))))
1359 (((field #:no-getter) field* ...) (identifier? #'field)
1360 (accessors rtd type-name #'(field* ...) (1+ n)
1361 #`(begin #,exp
1362 #,(setter rtd type-name #'field n))))
1363 ((field field* ...) (identifier? #'field)
1364 (accessors rtd type-name #'(field* ...) (1+ n)
1365 #`(begin #,exp
1366 #,(getter rtd type-name #'field n)
1367 #,(setter rtd type-name #'field n))))))
1368
1369 (define (predicate rtd type-name fields exp)
1370 (accessors
1371 rtd type-name fields 0
1372 #`(begin
1373 #,exp
1374 (define (#,(make-id rtd type-name '?) obj)
1375 (and (struct? obj) (eq? (struct-vtable obj) #,rtd))))))
1376
1377 (define (field-list fields)
1378 (syntax-case fields ()
1379 (() '())
1380 (((f . opts) . rest) (identifier? #'f)
1381 (cons #'f (field-list #'rest)))
1382 ((f . rest) (identifier? #'f)
1383 (cons #'f (field-list #'rest)))))
1384
1385 (define (constructor rtd type-name fields exp)
1386 (let ((ctor (make-id rtd type-name '-constructor))
1387 (args (field-list fields)))
1388 (predicate rtd type-name fields
1389 #`(begin #,exp
1390 (define #,ctor
1391 (let ((rtd #,rtd))
1392 (lambda #,args
1393 (make-struct rtd 0 #,@args))))
1394 (struct-set! #,rtd (+ vtable-offset-user 2)
1395 #,ctor)))))
1396
1397 (define (type type-name printer fields)
1398 (define (make-layout)
1399 (let lp ((fields fields) (slots '()))
1400 (syntax-case fields ()
1401 (() (datum->syntax #'here
1402 (make-struct-layout
1403 (apply string-append slots))))
1404 ((_ . rest) (lp #'rest (cons "pw" slots))))))
1405
1406 (let ((rtd (make-id type-name type-name '-type)))
1407 (constructor rtd type-name fields
1408 #`(begin
1409 (define #,rtd
1410 (make-struct record-type-vtable 0
1411 '#,(make-layout)
1412 #,printer
1413 '#,type-name
1414 '#,(field-list fields)))
1415 (set-struct-vtable-name! #,rtd '#,type-name)))))
1416
1417 (syntax-case x ()
1418 ((_ type-name printer (field ...))
1419 (type #'type-name #'printer #'(field ...)))))))
1420
1421 ;; module-type
1422 ;;
1423 ;; A module is characterized by an obarray in which local symbols
1424 ;; are interned, a list of modules, "uses", from which non-local
1425 ;; bindings can be inherited, and an optional lazy-binder which
1426 ;; is a (CLOSURE module symbol) which, as a last resort, can provide
1427 ;; bindings that would otherwise not be found locally in the module.
1428 ;;
1429 ;; NOTE: If you change the set of fields or their order, you also need to
1430 ;; change the constants in libguile/modules.h.
1431 ;;
1432 ;; NOTE: The getter `module-eval-closure' is used in libguile/modules.c.
1433 ;; NOTE: The getter `module-transfomer' is defined libguile/modules.c.
1434 ;; NOTE: The getter `module-name' is defined later, due to boot reasons.
1435 ;; NOTE: The getter `module-public-interface' is used in libguile/modules.c.
1436 ;;
1437 (define-record-type module
1438 (lambda (obj port) (%print-module obj port))
1439 (obarray
1440 uses
1441 binder
1442 eval-closure
1443 (transformer #:no-getter)
1444 (name #:no-getter)
1445 kind
1446 duplicates-handlers
1447 (import-obarray #:no-setter)
1448 observers
1449 (weak-observers #:no-setter)
1450 version
1451 submodules
1452 submodule-binder
1453 public-interface
1454 filename)))
1455
1456
1457 ;; make-module &opt size uses binder
1458 ;;
1459 ;; Create a new module, perhaps with a particular size of obarray,
1460 ;; initial uses list, or binding procedure.
1461 ;;
1462 (define make-module
1463 (lambda args
1464
1465 (define (parse-arg index default)
1466 (if (> (length args) index)
1467 (list-ref args index)
1468 default))
1469
1470 (define %default-import-size
1471 ;; Typical number of imported bindings actually used by a module.
1472 600)
1473
1474 (if (> (length args) 3)
1475 (error "Too many args to make-module." args))
1476
1477 (let ((size (parse-arg 0 31))
1478 (uses (parse-arg 1 '()))
1479 (binder (parse-arg 2 #f)))
1480
1481 (if (not (integer? size))
1482 (error "Illegal size to make-module." size))
1483 (if (not (and (list? uses)
1484 (and-map module? uses)))
1485 (error "Incorrect use list." uses))
1486 (if (and binder (not (procedure? binder)))
1487 (error
1488 "Lazy-binder expected to be a procedure or #f." binder))
1489
1490 (let ((module (module-constructor (make-hash-table size)
1491 uses binder #f macroexpand
1492 #f #f #f
1493 (make-hash-table %default-import-size)
1494 '()
1495 (make-weak-key-hash-table 31) #f
1496 (make-hash-table 7) #f #f #f)))
1497
1498 ;; We can't pass this as an argument to module-constructor,
1499 ;; because we need it to close over a pointer to the module
1500 ;; itself.
1501 (set-module-eval-closure! module (standard-eval-closure module))
1502
1503 module))))
1504
1505
1506 \f
1507
1508 ;;; {Observer protocol}
1509 ;;;
1510
1511 (define (module-observe module proc)
1512 (set-module-observers! module (cons proc (module-observers module)))
1513 (cons module proc))
1514
1515 (define* (module-observe-weak module observer-id #:optional (proc observer-id))
1516 ;; Register PROC as an observer of MODULE under name OBSERVER-ID (which can
1517 ;; be any Scheme object). PROC is invoked and passed MODULE any time
1518 ;; MODULE is modified. PROC gets unregistered when OBSERVER-ID gets GC'd
1519 ;; (thus, it is never unregistered if OBSERVER-ID is an immediate value,
1520 ;; for instance).
1521
1522 ;; The two-argument version is kept for backward compatibility: when called
1523 ;; with two arguments, the observer gets unregistered when closure PROC
1524 ;; gets GC'd (making it impossible to use an anonymous lambda for PROC).
1525 (hashq-set! (module-weak-observers module) observer-id proc))
1526
1527 (define (module-unobserve token)
1528 (let ((module (car token))
1529 (id (cdr token)))
1530 (if (integer? id)
1531 (hash-remove! (module-weak-observers module) id)
1532 (set-module-observers! module (delq1! id (module-observers module)))))
1533 *unspecified*)
1534
1535 (define module-defer-observers #f)
1536 (define module-defer-observers-mutex (make-mutex 'recursive))
1537 (define module-defer-observers-table (make-hash-table))
1538
1539 (define (module-modified m)
1540 (if module-defer-observers
1541 (hash-set! module-defer-observers-table m #t)
1542 (module-call-observers m)))
1543
1544 ;;; This function can be used to delay calls to observers so that they
1545 ;;; can be called once only in the face of massive updating of modules.
1546 ;;;
1547 (define (call-with-deferred-observers thunk)
1548 (dynamic-wind
1549 (lambda ()
1550 (lock-mutex module-defer-observers-mutex)
1551 (set! module-defer-observers #t))
1552 thunk
1553 (lambda ()
1554 (set! module-defer-observers #f)
1555 (hash-for-each (lambda (m dummy)
1556 (module-call-observers m))
1557 module-defer-observers-table)
1558 (hash-clear! module-defer-observers-table)
1559 (unlock-mutex module-defer-observers-mutex))))
1560
1561 (define (module-call-observers m)
1562 (for-each (lambda (proc) (proc m)) (module-observers m))
1563
1564 ;; We assume that weak observers don't (un)register themselves as they are
1565 ;; called since this would preclude proper iteration over the hash table
1566 ;; elements.
1567 (hash-for-each (lambda (id proc) (proc m)) (module-weak-observers m)))
1568
1569 \f
1570
1571 ;;; {Module Searching in General}
1572 ;;;
1573 ;;; We sometimes want to look for properties of a symbol
1574 ;;; just within the obarray of one module. If the property
1575 ;;; holds, then it is said to hold ``locally'' as in, ``The symbol
1576 ;;; DISPLAY is locally rebound in the module `safe-guile'.''
1577 ;;;
1578 ;;;
1579 ;;; Other times, we want to test for a symbol property in the obarray
1580 ;;; of M and, if it is not found there, try each of the modules in the
1581 ;;; uses list of M. This is the normal way of testing for some
1582 ;;; property, so we state these properties without qualification as
1583 ;;; in: ``The symbol 'fnord is interned in module M because it is
1584 ;;; interned locally in module M2 which is a member of the uses list
1585 ;;; of M.''
1586 ;;;
1587
1588 ;; module-search fn m
1589 ;;
1590 ;; return the first non-#f result of FN applied to M and then to
1591 ;; the modules in the uses of m, and so on recursively. If all applications
1592 ;; return #f, then so does this function.
1593 ;;
1594 (define (module-search fn m v)
1595 (define (loop pos)
1596 (and (pair? pos)
1597 (or (module-search fn (car pos) v)
1598 (loop (cdr pos)))))
1599 (or (fn m v)
1600 (loop (module-uses m))))
1601
1602
1603 ;;; {Is a symbol bound in a module?}
1604 ;;;
1605 ;;; Symbol S in Module M is bound if S is interned in M and if the binding
1606 ;;; of S in M has been set to some well-defined value.
1607 ;;;
1608
1609 ;; module-locally-bound? module symbol
1610 ;;
1611 ;; Is a symbol bound (interned and defined) locally in a given module?
1612 ;;
1613 (define (module-locally-bound? m v)
1614 (let ((var (module-local-variable m v)))
1615 (and var
1616 (variable-bound? var))))
1617
1618 ;; module-bound? module symbol
1619 ;;
1620 ;; Is a symbol bound (interned and defined) anywhere in a given module
1621 ;; or its uses?
1622 ;;
1623 (define (module-bound? m v)
1624 (let ((var (module-variable m v)))
1625 (and var
1626 (variable-bound? var))))
1627
1628 ;;; {Is a symbol interned in a module?}
1629 ;;;
1630 ;;; Symbol S in Module M is interned if S occurs in
1631 ;;; of S in M has been set to some well-defined value.
1632 ;;;
1633 ;;; It is possible to intern a symbol in a module without providing
1634 ;;; an initial binding for the corresponding variable. This is done
1635 ;;; with:
1636 ;;; (module-add! module symbol (make-undefined-variable))
1637 ;;;
1638 ;;; In that case, the symbol is interned in the module, but not
1639 ;;; bound there. The unbound symbol shadows any binding for that
1640 ;;; symbol that might otherwise be inherited from a member of the uses list.
1641 ;;;
1642
1643 (define (module-obarray-get-handle ob key)
1644 ((if (symbol? key) hashq-get-handle hash-get-handle) ob key))
1645
1646 (define (module-obarray-ref ob key)
1647 ((if (symbol? key) hashq-ref hash-ref) ob key))
1648
1649 (define (module-obarray-set! ob key val)
1650 ((if (symbol? key) hashq-set! hash-set!) ob key val))
1651
1652 (define (module-obarray-remove! ob key)
1653 ((if (symbol? key) hashq-remove! hash-remove!) ob key))
1654
1655 ;; module-symbol-locally-interned? module symbol
1656 ;;
1657 ;; is a symbol interned (not neccessarily defined) locally in a given module
1658 ;; or its uses? Interned symbols shadow inherited bindings even if
1659 ;; they are not themselves bound to a defined value.
1660 ;;
1661 (define (module-symbol-locally-interned? m v)
1662 (not (not (module-obarray-get-handle (module-obarray m) v))))
1663
1664 ;; module-symbol-interned? module symbol
1665 ;;
1666 ;; is a symbol interned (not neccessarily defined) anywhere in a given module
1667 ;; or its uses? Interned symbols shadow inherited bindings even if
1668 ;; they are not themselves bound to a defined value.
1669 ;;
1670 (define (module-symbol-interned? m v)
1671 (module-search module-symbol-locally-interned? m v))
1672
1673
1674 ;;; {Mapping modules x symbols --> variables}
1675 ;;;
1676
1677 ;; module-local-variable module symbol
1678 ;; return the local variable associated with a MODULE and SYMBOL.
1679 ;;
1680 ;;; This function is very important. It is the only function that can
1681 ;;; return a variable from a module other than the mutators that store
1682 ;;; new variables in modules. Therefore, this function is the location
1683 ;;; of the "lazy binder" hack.
1684 ;;;
1685 ;;; If symbol is defined in MODULE, and if the definition binds symbol
1686 ;;; to a variable, return that variable object.
1687 ;;;
1688 ;;; If the symbols is not found at first, but the module has a lazy binder,
1689 ;;; then try the binder.
1690 ;;;
1691 ;;; If the symbol is not found at all, return #f.
1692 ;;;
1693 ;;; (This is now written in C, see `modules.c'.)
1694 ;;;
1695
1696 ;;; {Mapping modules x symbols --> bindings}
1697 ;;;
1698 ;;; These are similar to the mapping to variables, except that the
1699 ;;; variable is dereferenced.
1700 ;;;
1701
1702 ;; module-symbol-binding module symbol opt-value
1703 ;;
1704 ;; return the binding of a variable specified by name within
1705 ;; a given module, signalling an error if the variable is unbound.
1706 ;; If the OPT-VALUE is passed, then instead of signalling an error,
1707 ;; return OPT-VALUE.
1708 ;;
1709 (define (module-symbol-local-binding m v . opt-val)
1710 (let ((var (module-local-variable m v)))
1711 (if (and var (variable-bound? var))
1712 (variable-ref var)
1713 (if (not (null? opt-val))
1714 (car opt-val)
1715 (error "Locally unbound variable." v)))))
1716
1717 ;; module-symbol-binding module symbol opt-value
1718 ;;
1719 ;; return the binding of a variable specified by name within
1720 ;; a given module, signalling an error if the variable is unbound.
1721 ;; If the OPT-VALUE is passed, then instead of signalling an error,
1722 ;; return OPT-VALUE.
1723 ;;
1724 (define (module-symbol-binding m v . opt-val)
1725 (let ((var (module-variable m v)))
1726 (if (and var (variable-bound? var))
1727 (variable-ref var)
1728 (if (not (null? opt-val))
1729 (car opt-val)
1730 (error "Unbound variable." v)))))
1731
1732
1733 \f
1734
1735 ;;; {Adding Variables to Modules}
1736 ;;;
1737
1738 ;; module-make-local-var! module symbol
1739 ;;
1740 ;; ensure a variable for V in the local namespace of M.
1741 ;; If no variable was already there, then create a new and uninitialzied
1742 ;; variable.
1743 ;;
1744 ;; This function is used in modules.c.
1745 ;;
1746 (define (module-make-local-var! m v)
1747 (or (let ((b (module-obarray-ref (module-obarray m) v)))
1748 (and (variable? b)
1749 (begin
1750 ;; Mark as modified since this function is called when
1751 ;; the standard eval closure defines a binding
1752 (module-modified m)
1753 b)))
1754
1755 ;; Create a new local variable.
1756 (let ((local-var (make-undefined-variable)))
1757 (module-add! m v local-var)
1758 local-var)))
1759
1760 ;; module-ensure-local-variable! module symbol
1761 ;;
1762 ;; Ensure that there is a local variable in MODULE for SYMBOL. If
1763 ;; there is no binding for SYMBOL, create a new uninitialized
1764 ;; variable. Return the local variable.
1765 ;;
1766 (define (module-ensure-local-variable! module symbol)
1767 (or (module-local-variable module symbol)
1768 (let ((var (make-undefined-variable)))
1769 (module-add! module symbol var)
1770 var)))
1771
1772 ;; module-add! module symbol var
1773 ;;
1774 ;; ensure a particular variable for V in the local namespace of M.
1775 ;;
1776 (define (module-add! m v var)
1777 (if (not (variable? var))
1778 (error "Bad variable to module-add!" var))
1779 (module-obarray-set! (module-obarray m) v var)
1780 (module-modified m))
1781
1782 ;; module-remove!
1783 ;;
1784 ;; make sure that a symbol is undefined in the local namespace of M.
1785 ;;
1786 (define (module-remove! m v)
1787 (module-obarray-remove! (module-obarray m) v)
1788 (module-modified m))
1789
1790 (define (module-clear! m)
1791 (hash-clear! (module-obarray m))
1792 (module-modified m))
1793
1794 ;; MODULE-FOR-EACH -- exported
1795 ;;
1796 ;; Call PROC on each symbol in MODULE, with arguments of (SYMBOL VARIABLE).
1797 ;;
1798 (define (module-for-each proc module)
1799 (hash-for-each proc (module-obarray module)))
1800
1801 (define (module-map proc module)
1802 (hash-map->list proc (module-obarray module)))
1803
1804 ;; Submodules
1805 ;;
1806 ;; Modules exist in a separate namespace from values, because you generally do
1807 ;; not want the name of a submodule, which you might not even use, to collide
1808 ;; with local variables that happen to be named the same as the submodule.
1809 ;;
1810 (define (module-ref-submodule module name)
1811 (or (hashq-ref (module-submodules module) name)
1812 (and (module-submodule-binder module)
1813 ((module-submodule-binder module) module name))))
1814
1815 (define (module-define-submodule! module name submodule)
1816 (hashq-set! (module-submodules module) name submodule))
1817
1818 \f
1819
1820 ;;; {Low Level Bootstrapping}
1821 ;;;
1822
1823 ;; make-root-module
1824
1825 ;; A root module uses the pre-modules-obarray as its obarray. This
1826 ;; special obarray accumulates all bindings that have been established
1827 ;; before the module system is fully booted.
1828 ;;
1829 ;; (The obarray continues to be used by code that has been closed over
1830 ;; before the module system has been booted.)
1831
1832 (define (make-root-module)
1833 (let ((m (make-module 0)))
1834 (set-module-obarray! m (%get-pre-modules-obarray))
1835 m))
1836
1837 ;; make-scm-module
1838
1839 ;; The root interface is a module that uses the same obarray as the
1840 ;; root module. It does not allow new definitions, tho.
1841
1842 (define (make-scm-module)
1843 (let ((m (make-module 0)))
1844 (set-module-obarray! m (%get-pre-modules-obarray))
1845 (set-module-eval-closure! m (standard-interface-eval-closure m))
1846 m))
1847
1848
1849 \f
1850
1851 ;;; {Module-based Loading}
1852 ;;;
1853
1854 (define (save-module-excursion thunk)
1855 (let ((inner-module (current-module))
1856 (outer-module #f))
1857 (dynamic-wind (lambda ()
1858 (set! outer-module (current-module))
1859 (set-current-module inner-module)
1860 (set! inner-module #f))
1861 thunk
1862 (lambda ()
1863 (set! inner-module (current-module))
1864 (set-current-module outer-module)
1865 (set! outer-module #f)))))
1866
1867 (define basic-load load)
1868
1869 (define* (load-module filename #:optional reader)
1870 (save-module-excursion
1871 (lambda ()
1872 (let ((oldname (and (current-load-port)
1873 (port-filename (current-load-port)))))
1874 (basic-load (if (and oldname
1875 (> (string-length filename) 0)
1876 (not (char=? (string-ref filename 0) #\/))
1877 (not (string=? (dirname oldname) ".")))
1878 (string-append (dirname oldname) "/" filename)
1879 filename)
1880 reader)))))
1881
1882
1883 \f
1884
1885 ;;; {MODULE-REF -- exported}
1886 ;;;
1887
1888 ;; Returns the value of a variable called NAME in MODULE or any of its
1889 ;; used modules. If there is no such variable, then if the optional third
1890 ;; argument DEFAULT is present, it is returned; otherwise an error is signaled.
1891 ;;
1892 (define (module-ref module name . rest)
1893 (let ((variable (module-variable module name)))
1894 (if (and variable (variable-bound? variable))
1895 (variable-ref variable)
1896 (if (null? rest)
1897 (error "No variable named" name 'in module)
1898 (car rest) ; default value
1899 ))))
1900
1901 ;; MODULE-SET! -- exported
1902 ;;
1903 ;; Sets the variable called NAME in MODULE (or in a module that MODULE uses)
1904 ;; to VALUE; if there is no such variable, an error is signaled.
1905 ;;
1906 (define (module-set! module name value)
1907 (let ((variable (module-variable module name)))
1908 (if variable
1909 (variable-set! variable value)
1910 (error "No variable named" name 'in module))))
1911
1912 ;; MODULE-DEFINE! -- exported
1913 ;;
1914 ;; Sets the variable called NAME in MODULE to VALUE; if there is no such
1915 ;; variable, it is added first.
1916 ;;
1917 (define (module-define! module name value)
1918 (let ((variable (module-local-variable module name)))
1919 (if variable
1920 (begin
1921 (variable-set! variable value)
1922 (module-modified module))
1923 (let ((variable (make-variable value)))
1924 (module-add! module name variable)))))
1925
1926 ;; MODULE-DEFINED? -- exported
1927 ;;
1928 ;; Return #t iff NAME is defined in MODULE (or in a module that MODULE
1929 ;; uses)
1930 ;;
1931 (define (module-defined? module name)
1932 (let ((variable (module-variable module name)))
1933 (and variable (variable-bound? variable))))
1934
1935 ;; MODULE-USE! module interface
1936 ;;
1937 ;; Add INTERFACE to the list of interfaces used by MODULE.
1938 ;;
1939 (define (module-use! module interface)
1940 (if (not (or (eq? module interface)
1941 (memq interface (module-uses module))))
1942 (begin
1943 ;; Newly used modules must be appended rather than consed, so that
1944 ;; `module-variable' traverses the use list starting from the first
1945 ;; used module.
1946 (set-module-uses! module
1947 (append (filter (lambda (m)
1948 (not
1949 (equal? (module-name m)
1950 (module-name interface))))
1951 (module-uses module))
1952 (list interface)))
1953 (hash-clear! (module-import-obarray module))
1954 (module-modified module))))
1955
1956 ;; MODULE-USE-INTERFACES! module interfaces
1957 ;;
1958 ;; Same as MODULE-USE! but add multiple interfaces and check for duplicates
1959 ;;
1960 (define (module-use-interfaces! module interfaces)
1961 (set-module-uses! module
1962 (append (module-uses module) interfaces))
1963 (hash-clear! (module-import-obarray module))
1964 (module-modified module))
1965
1966 \f
1967
1968 ;;; {Recursive Namespaces}
1969 ;;;
1970 ;;; A hierarchical namespace emerges if we consider some module to be
1971 ;;; root, and submodules of that module to be nested namespaces.
1972 ;;;
1973 ;;; The routines here manage variable names in hierarchical namespace.
1974 ;;; Each variable name is a list of elements, looked up in successively nested
1975 ;;; modules.
1976 ;;;
1977 ;;; (nested-ref some-root-module '(foo bar baz))
1978 ;;; => <value of a variable named baz in the submodule bar of
1979 ;;; the submodule foo of some-root-module>
1980 ;;;
1981 ;;;
1982 ;;; There are:
1983 ;;;
1984 ;;; ;; a-root is a module
1985 ;;; ;; name is a list of symbols
1986 ;;;
1987 ;;; nested-ref a-root name
1988 ;;; nested-set! a-root name val
1989 ;;; nested-define! a-root name val
1990 ;;; nested-remove! a-root name
1991 ;;;
1992 ;;; These functions manipulate values in namespaces. For referencing the
1993 ;;; namespaces themselves, use the following:
1994 ;;;
1995 ;;; nested-ref-module a-root name
1996 ;;; nested-define-module! a-root name mod
1997 ;;;
1998 ;;; (current-module) is a natural choice for a root so for convenience there are
1999 ;;; also:
2000 ;;;
2001 ;;; local-ref name == nested-ref (current-module) name
2002 ;;; local-set! name val == nested-set! (current-module) name val
2003 ;;; local-define name val == nested-define! (current-module) name val
2004 ;;; local-remove name == nested-remove! (current-module) name
2005 ;;; local-ref-module name == nested-ref-module (current-module) name
2006 ;;; local-define-module! name m == nested-define-module! (current-module) name m
2007 ;;;
2008
2009
2010 (define (nested-ref root names)
2011 (if (null? names)
2012 root
2013 (let loop ((cur root)
2014 (head (car names))
2015 (tail (cdr names)))
2016 (if (null? tail)
2017 (module-ref cur head #f)
2018 (let ((cur (module-ref-submodule cur head)))
2019 (and cur
2020 (loop cur (car tail) (cdr tail))))))))
2021
2022 (define (nested-set! root names val)
2023 (let loop ((cur root)
2024 (head (car names))
2025 (tail (cdr names)))
2026 (if (null? tail)
2027 (module-set! cur head val)
2028 (let ((cur (module-ref-submodule cur head)))
2029 (if (not cur)
2030 (error "failed to resolve module" names)
2031 (loop cur (car tail) (cdr tail)))))))
2032
2033 (define (nested-define! root names val)
2034 (let loop ((cur root)
2035 (head (car names))
2036 (tail (cdr names)))
2037 (if (null? tail)
2038 (module-define! cur head val)
2039 (let ((cur (module-ref-submodule cur head)))
2040 (if (not cur)
2041 (error "failed to resolve module" names)
2042 (loop cur (car tail) (cdr tail)))))))
2043
2044 (define (nested-remove! root names)
2045 (let loop ((cur root)
2046 (head (car names))
2047 (tail (cdr names)))
2048 (if (null? tail)
2049 (module-remove! cur head)
2050 (let ((cur (module-ref-submodule cur head)))
2051 (if (not cur)
2052 (error "failed to resolve module" names)
2053 (loop cur (car tail) (cdr tail)))))))
2054
2055
2056 (define (nested-ref-module root names)
2057 (let loop ((cur root)
2058 (names names))
2059 (if (null? names)
2060 cur
2061 (let ((cur (module-ref-submodule cur (car names))))
2062 (and cur
2063 (loop cur (cdr names)))))))
2064
2065 (define (nested-define-module! root names module)
2066 (if (null? names)
2067 (error "can't redefine root module" root module)
2068 (let loop ((cur root)
2069 (head (car names))
2070 (tail (cdr names)))
2071 (if (null? tail)
2072 (module-define-submodule! cur head module)
2073 (let ((cur (or (module-ref-submodule cur head)
2074 (let ((m (make-module 31)))
2075 (set-module-kind! m 'directory)
2076 (set-module-name! m (append (module-name cur)
2077 (list head)))
2078 (module-define-submodule! cur head m)
2079 m))))
2080 (loop cur (car tail) (cdr tail)))))))
2081
2082
2083 (define (local-ref names) (nested-ref (current-module) names))
2084 (define (local-set! names val) (nested-set! (current-module) names val))
2085 (define (local-define names val) (nested-define! (current-module) names val))
2086 (define (local-remove names) (nested-remove! (current-module) names))
2087 (define (local-ref-module names) (nested-ref-module (current-module) names))
2088 (define (local-define-module names mod) (nested-define-module! (current-module) names mod))
2089
2090
2091
2092 \f
2093
2094 ;;; {The (guile) module}
2095 ;;;
2096 ;;; The standard module, which has the core Guile bindings. Also called the
2097 ;;; "root module", as it is imported by many other modules, but it is not
2098 ;;; necessarily the root of anything; and indeed, the module named '() might be
2099 ;;; better thought of as a root.
2100 ;;;
2101
2102 (define (set-system-module! m s)
2103 (set-procedure-property! (module-eval-closure m) 'system-module s))
2104 (define the-root-module (make-root-module))
2105 (define the-scm-module (make-scm-module))
2106 (set-module-public-interface! the-root-module the-scm-module)
2107 (set-module-name! the-root-module '(guile))
2108 (set-module-name! the-scm-module '(guile))
2109 (set-module-kind! the-scm-module 'interface)
2110 (set-system-module! the-root-module #t)
2111 (set-system-module! the-scm-module #t)
2112
2113
2114 \f
2115
2116 ;; Now that we have a root module, even though modules aren't fully booted,
2117 ;; expand the definition of resolve-module.
2118 ;;
2119 (define (resolve-module name . args)
2120 (if (equal? name '(guile))
2121 the-root-module
2122 (error "unexpected module to resolve during module boot" name)))
2123
2124 ;; Cheat. These bindings are needed by modules.c, but we don't want
2125 ;; to move their real definition here because that would be unnatural.
2126 ;;
2127 (define process-define-module #f)
2128 (define process-use-modules #f)
2129 (define module-export! #f)
2130 (define default-duplicate-binding-procedures #f)
2131
2132 ;; This boots the module system. All bindings needed by modules.c
2133 ;; must have been defined by now.
2134 ;;
2135 (set-current-module the-root-module)
2136
2137
2138 \f
2139
2140 ;; Now that modules are booted, give module-name its final definition.
2141 ;;
2142 (define module-name
2143 (let ((accessor (record-accessor module-type 'name)))
2144 (lambda (mod)
2145 (or (accessor mod)
2146 (let ((name (list (gensym))))
2147 ;; Name MOD and bind it in the module root so that it's visible to
2148 ;; `resolve-module'. This is important as `psyntax' stores module
2149 ;; names and relies on being able to `resolve-module' them.
2150 (set-module-name! mod name)
2151 (nested-define-module! (resolve-module '() #f) name mod)
2152 (accessor mod))))))
2153
2154 (define (make-modules-in module name)
2155 (or (nested-ref-module module name)
2156 (let ((m (make-module 31)))
2157 (set-module-kind! m 'directory)
2158 (set-module-name! m (append (module-name module) name))
2159 (nested-define-module! module name m)
2160 m)))
2161
2162 (define (beautify-user-module! module)
2163 (let ((interface (module-public-interface module)))
2164 (if (or (not interface)
2165 (eq? interface module))
2166 (let ((interface (make-module 31)))
2167 (set-module-name! interface (module-name module))
2168 (set-module-version! interface (module-version module))
2169 (set-module-kind! interface 'interface)
2170 (set-module-public-interface! module interface))))
2171 (if (and (not (memq the-scm-module (module-uses module)))
2172 (not (eq? module the-root-module)))
2173 ;; Import the default set of bindings (from the SCM module) in MODULE.
2174 (module-use! module the-scm-module)))
2175
2176 (define (version-matches? version-ref target)
2177 (define (sub-versions-match? v-refs t)
2178 (define (sub-version-matches? v-ref t)
2179 (let ((matches? (lambda (v) (sub-version-matches? v t))))
2180 (cond
2181 ((number? v-ref) (eqv? v-ref t))
2182 ((list? v-ref)
2183 (case (car v-ref)
2184 ((>=) (>= t (cadr v-ref)))
2185 ((<=) (<= t (cadr v-ref)))
2186 ((and) (and-map matches? (cdr v-ref)))
2187 ((or) (or-map matches? (cdr v-ref)))
2188 ((not) (not (matches? (cadr v-ref))))
2189 (else (error "Invalid sub-version reference" v-ref))))
2190 (else (error "Invalid sub-version reference" v-ref)))))
2191 (or (null? v-refs)
2192 (and (not (null? t))
2193 (sub-version-matches? (car v-refs) (car t))
2194 (sub-versions-match? (cdr v-refs) (cdr t)))))
2195
2196 (let ((matches? (lambda (v) (version-matches? v target))))
2197 (or (null? version-ref)
2198 (case (car version-ref)
2199 ((and) (and-map matches? (cdr version-ref)))
2200 ((or) (or-map matches? (cdr version-ref)))
2201 ((not) (not (matches? (cadr version-ref))))
2202 (else (sub-versions-match? version-ref target))))))
2203
2204 (define (make-fresh-user-module)
2205 (let ((m (make-module)))
2206 (beautify-user-module! m)
2207 m))
2208
2209 ;; NOTE: This binding is used in libguile/modules.c.
2210 ;;
2211 (define resolve-module
2212 (let ((root (make-module)))
2213 (set-module-name! root '())
2214 ;; Define the-root-module as '(guile).
2215 (module-define-submodule! root 'guile the-root-module)
2216
2217 (lambda* (name #:optional (autoload #t) (version #f) #:key (ensure #t))
2218 (let ((already (nested-ref-module root name)))
2219 (cond
2220 ((and already
2221 (or (not autoload) (module-public-interface already)))
2222 ;; A hit, a palpable hit.
2223 (if (and version
2224 (not (version-matches? version (module-version already))))
2225 (error "incompatible module version already loaded" name))
2226 already)
2227 (autoload
2228 ;; Try to autoload the module, and recurse.
2229 (try-load-module name version)
2230 (resolve-module name #f #:ensure ensure))
2231 (else
2232 ;; No module found (or if one was, it had no public interface), and
2233 ;; we're not autoloading. Make an empty module if #:ensure is true.
2234 (or already
2235 (and ensure
2236 (make-modules-in root name)))))))))
2237
2238
2239 (define (try-load-module name version)
2240 (try-module-autoload name version))
2241
2242 (define (purify-module! module)
2243 "Removes bindings in MODULE which are inherited from the (guile) module."
2244 (let ((use-list (module-uses module)))
2245 (if (and (pair? use-list)
2246 (eq? (car (last-pair use-list)) the-scm-module))
2247 (set-module-uses! module (reverse (cdr (reverse use-list)))))))
2248
2249 ;; Return a module that is an interface to the module designated by
2250 ;; NAME.
2251 ;;
2252 ;; `resolve-interface' takes four keyword arguments:
2253 ;;
2254 ;; #:select SELECTION
2255 ;;
2256 ;; SELECTION is a list of binding-specs to be imported; A binding-spec
2257 ;; is either a symbol or a pair of symbols (ORIG . SEEN), where ORIG
2258 ;; is the name in the used module and SEEN is the name in the using
2259 ;; module. Note that SEEN is also passed through RENAMER, below. The
2260 ;; default is to select all bindings. If you specify no selection but
2261 ;; a renamer, only the bindings that already exist in the used module
2262 ;; are made available in the interface. Bindings that are added later
2263 ;; are not picked up.
2264 ;;
2265 ;; #:hide BINDINGS
2266 ;;
2267 ;; BINDINGS is a list of bindings which should not be imported.
2268 ;;
2269 ;; #:prefix PREFIX
2270 ;;
2271 ;; PREFIX is a symbol that will be appended to each exported name.
2272 ;; The default is to not perform any renaming.
2273 ;;
2274 ;; #:renamer RENAMER
2275 ;;
2276 ;; RENAMER is a procedure that takes a symbol and returns its new
2277 ;; name. The default is not perform any renaming.
2278 ;;
2279 ;; Signal "no code for module" error if module name is not resolvable
2280 ;; or its public interface is not available. Signal "no binding"
2281 ;; error if selected binding does not exist in the used module.
2282 ;;
2283 (define* (resolve-interface name #:key
2284 (select #f)
2285 (hide '())
2286 (prefix #f)
2287 (renamer (if prefix
2288 (symbol-prefix-proc prefix)
2289 identity))
2290 version)
2291 (let* ((module (resolve-module name #t version #:ensure #f))
2292 (public-i (and module (module-public-interface module))))
2293 (and (or (not module) (not public-i))
2294 (error "no code for module" name))
2295 (if (and (not select) (null? hide) (eq? renamer identity))
2296 public-i
2297 (let ((selection (or select (module-map (lambda (sym var) sym)
2298 public-i)))
2299 (custom-i (make-module 31)))
2300 (set-module-kind! custom-i 'custom-interface)
2301 (set-module-name! custom-i name)
2302 ;; XXX - should use a lazy binder so that changes to the
2303 ;; used module are picked up automatically.
2304 (for-each (lambda (bspec)
2305 (let* ((direct? (symbol? bspec))
2306 (orig (if direct? bspec (car bspec)))
2307 (seen (if direct? bspec (cdr bspec)))
2308 (var (or (module-local-variable public-i orig)
2309 (module-local-variable module orig)
2310 (error
2311 ;; fixme: format manually for now
2312 (simple-format
2313 #f "no binding `~A' in module ~A"
2314 orig name)))))
2315 (if (memq orig hide)
2316 (set! hide (delq! orig hide))
2317 (module-add! custom-i
2318 (renamer seen)
2319 var))))
2320 selection)
2321 ;; Check that we are not hiding bindings which don't exist
2322 (for-each (lambda (binding)
2323 (if (not (module-local-variable public-i binding))
2324 (error
2325 (simple-format
2326 #f "no binding `~A' to hide in module ~A"
2327 binding name))))
2328 hide)
2329 custom-i))))
2330
2331 (define (symbol-prefix-proc prefix)
2332 (lambda (symbol)
2333 (symbol-append prefix symbol)))
2334
2335 ;; This function is called from "modules.c". If you change it, be
2336 ;; sure to update "modules.c" as well.
2337
2338 (define (process-define-module args)
2339 (let* ((module-id (car args))
2340 (module (resolve-module module-id #f))
2341 (kws (cdr args))
2342 (unrecognized (lambda (arg)
2343 (error "unrecognized define-module argument" arg))))
2344 (beautify-user-module! module)
2345 (let loop ((kws kws)
2346 (reversed-interfaces '())
2347 (exports '())
2348 (re-exports '())
2349 (replacements '())
2350 (autoloads '()))
2351
2352 (if (null? kws)
2353 (call-with-deferred-observers
2354 (lambda ()
2355 (module-use-interfaces! module (reverse reversed-interfaces))
2356 (module-export! module exports)
2357 (module-replace! module replacements)
2358 (module-re-export! module re-exports)
2359 (if (not (null? autoloads))
2360 (apply module-autoload! module autoloads))))
2361 (case (car kws)
2362 ((#:use-module #:use-syntax)
2363 (or (pair? (cdr kws))
2364 (unrecognized kws))
2365 (cond
2366 ((equal? (caadr kws) '(ice-9 syncase))
2367 (issue-deprecation-warning
2368 "(ice-9 syncase) is deprecated. Support for syntax-case is now in Guile core.")
2369 (loop (cddr kws)
2370 reversed-interfaces
2371 exports
2372 re-exports
2373 replacements
2374 autoloads))
2375 (else
2376 (let* ((interface-args (cadr kws))
2377 (interface (apply resolve-interface interface-args)))
2378 (and (eq? (car kws) #:use-syntax)
2379 (or (symbol? (caar interface-args))
2380 (error "invalid module name for use-syntax"
2381 (car interface-args)))
2382 (set-module-transformer!
2383 module
2384 (module-ref interface
2385 (car (last-pair (car interface-args)))
2386 #f)))
2387 (loop (cddr kws)
2388 (cons interface reversed-interfaces)
2389 exports
2390 re-exports
2391 replacements
2392 autoloads)))))
2393 ((#:autoload)
2394 (or (and (pair? (cdr kws)) (pair? (cddr kws)))
2395 (unrecognized kws))
2396 (loop (cdddr kws)
2397 reversed-interfaces
2398 exports
2399 re-exports
2400 replacements
2401 (let ((name (cadr kws))
2402 (bindings (caddr kws)))
2403 (cons* name bindings autoloads))))
2404 ((#:no-backtrace)
2405 (set-system-module! module #t)
2406 (loop (cdr kws) reversed-interfaces exports re-exports
2407 replacements autoloads))
2408 ((#:pure)
2409 (purify-module! module)
2410 (loop (cdr kws) reversed-interfaces exports re-exports
2411 replacements autoloads))
2412 ((#:version)
2413 (or (pair? (cdr kws))
2414 (unrecognized kws))
2415 (let ((version (cadr kws)))
2416 (set-module-version! module version)
2417 (set-module-version! (module-public-interface module) version))
2418 (loop (cddr kws) reversed-interfaces exports re-exports
2419 replacements autoloads))
2420 ((#:duplicates)
2421 (if (not (pair? (cdr kws)))
2422 (unrecognized kws))
2423 (set-module-duplicates-handlers!
2424 module
2425 (lookup-duplicates-handlers (cadr kws)))
2426 (loop (cddr kws) reversed-interfaces exports re-exports
2427 replacements autoloads))
2428 ((#:export #:export-syntax)
2429 (or (pair? (cdr kws))
2430 (unrecognized kws))
2431 (loop (cddr kws)
2432 reversed-interfaces
2433 (append (cadr kws) exports)
2434 re-exports
2435 replacements
2436 autoloads))
2437 ((#:re-export #:re-export-syntax)
2438 (or (pair? (cdr kws))
2439 (unrecognized kws))
2440 (loop (cddr kws)
2441 reversed-interfaces
2442 exports
2443 (append (cadr kws) re-exports)
2444 replacements
2445 autoloads))
2446 ((#:replace #:replace-syntax)
2447 (or (pair? (cdr kws))
2448 (unrecognized kws))
2449 (loop (cddr kws)
2450 reversed-interfaces
2451 exports
2452 re-exports
2453 (append (cadr kws) replacements)
2454 autoloads))
2455 ((#:filename)
2456 (or (pair? (cdr kws))
2457 (unrecognized kws))
2458 (set-module-filename! module (cadr kws))
2459 (loop (cddr kws)
2460 reversed-interfaces
2461 exports
2462 re-exports
2463 replacements
2464 autoloads))
2465 (else
2466 (unrecognized kws)))))
2467 (run-hook module-defined-hook module)
2468 module))
2469
2470 ;; `module-defined-hook' is a hook that is run whenever a new module
2471 ;; is defined. Its members are called with one argument, the new
2472 ;; module.
2473 (define module-defined-hook (make-hook 1))
2474
2475 \f
2476
2477 ;;; {Autoload}
2478 ;;;
2479
2480 (define (make-autoload-interface module name bindings)
2481 (let ((b (lambda (a sym definep)
2482 (and (memq sym bindings)
2483 (let ((i (module-public-interface (resolve-module name))))
2484 (if (not i)
2485 (error "missing interface for module" name))
2486 (let ((autoload (memq a (module-uses module))))
2487 ;; Replace autoload-interface with actual interface if
2488 ;; that has not happened yet.
2489 (if (pair? autoload)
2490 (set-car! autoload i)))
2491 (module-local-variable i sym))))))
2492 (module-constructor (make-hash-table 0) '() b #f #f name 'autoload #f
2493 (make-hash-table 0) '() (make-weak-value-hash-table 31) #f
2494 (make-hash-table 0) #f #f #f)))
2495
2496 (define (module-autoload! module . args)
2497 "Have @var{module} automatically load the module named @var{name} when one
2498 of the symbols listed in @var{bindings} is looked up. @var{args} should be a
2499 list of module-name/binding-list pairs, e.g., as in @code{(module-autoload!
2500 module '(ice-9 q) '(make-q q-length))}."
2501 (let loop ((args args))
2502 (cond ((null? args)
2503 #t)
2504 ((null? (cdr args))
2505 (error "invalid name+binding autoload list" args))
2506 (else
2507 (let ((name (car args))
2508 (bindings (cadr args)))
2509 (module-use! module (make-autoload-interface module
2510 name bindings))
2511 (loop (cddr args)))))))
2512
2513
2514 \f
2515
2516 ;;; {Autoloading modules}
2517 ;;;
2518
2519 (define autoloads-in-progress '())
2520
2521 ;; This function is called from "modules.c". If you change it, be
2522 ;; sure to update "modules.c" as well.
2523
2524 (define* (try-module-autoload module-name #:optional version)
2525 (let* ((reverse-name (reverse module-name))
2526 (name (symbol->string (car reverse-name)))
2527 (dir-hint-module-name (reverse (cdr reverse-name)))
2528 (dir-hint (apply string-append
2529 (map (lambda (elt)
2530 (string-append (symbol->string elt) "/"))
2531 dir-hint-module-name))))
2532 (resolve-module dir-hint-module-name #f)
2533 (and (not (autoload-done-or-in-progress? dir-hint name))
2534 (let ((didit #f))
2535 (dynamic-wind
2536 (lambda () (autoload-in-progress! dir-hint name))
2537 (lambda ()
2538 (with-fluids ((current-reader #f))
2539 (save-module-excursion
2540 (lambda ()
2541 ;; The initial environment when loading a module is a fresh
2542 ;; user module.
2543 (set-current-module (make-fresh-user-module))
2544 ;; Here we could allow some other search strategy (other than
2545 ;; primitive-load-path), for example using versions encoded
2546 ;; into the file system -- but then we would have to figure
2547 ;; out how to locate the compiled file, do autocompilation,
2548 ;; etc. Punt for now, and don't use versions when locating
2549 ;; the file.
2550 (primitive-load-path (in-vicinity dir-hint name) #f)
2551 (set! didit #t)))))
2552 (lambda () (set-autoloaded! dir-hint name didit)))
2553 didit))))
2554
2555 \f
2556
2557 ;;; {Dynamic linking of modules}
2558 ;;;
2559
2560 (define autoloads-done '((guile . guile)))
2561
2562 (define (autoload-done-or-in-progress? p m)
2563 (let ((n (cons p m)))
2564 (->bool (or (member n autoloads-done)
2565 (member n autoloads-in-progress)))))
2566
2567 (define (autoload-done! p m)
2568 (let ((n (cons p m)))
2569 (set! autoloads-in-progress
2570 (delete! n autoloads-in-progress))
2571 (or (member n autoloads-done)
2572 (set! autoloads-done (cons n autoloads-done)))))
2573
2574 (define (autoload-in-progress! p m)
2575 (let ((n (cons p m)))
2576 (set! autoloads-done
2577 (delete! n autoloads-done))
2578 (set! autoloads-in-progress (cons n autoloads-in-progress))))
2579
2580 (define (set-autoloaded! p m done?)
2581 (if done?
2582 (autoload-done! p m)
2583 (let ((n (cons p m)))
2584 (set! autoloads-done (delete! n autoloads-done))
2585 (set! autoloads-in-progress (delete! n autoloads-in-progress)))))
2586
2587 \f
2588
2589 ;;; {Run-time options}
2590 ;;;
2591
2592 (define-syntax define-option-interface
2593 (syntax-rules ()
2594 ((_ (interface (options enable disable) (option-set!)))
2595 (begin
2596 (define options
2597 (case-lambda
2598 (() (interface))
2599 ((arg)
2600 (if (list? arg)
2601 (begin (interface arg) (interface))
2602 (for-each
2603 (lambda (option)
2604 (apply (lambda (name value documentation)
2605 (display name)
2606 (if (< (string-length (symbol->string name)) 8)
2607 (display #\tab))
2608 (display #\tab)
2609 (display value)
2610 (display #\tab)
2611 (display documentation)
2612 (newline))
2613 option))
2614 (interface #t))))))
2615 (define (enable . flags)
2616 (interface (append flags (interface)))
2617 (interface))
2618 (define (disable . flags)
2619 (let ((options (interface)))
2620 (for-each (lambda (flag) (set! options (delq! flag options)))
2621 flags)
2622 (interface options)
2623 (interface)))
2624 (define-syntax option-set!
2625 (syntax-rules ()
2626 ((_ opt val)
2627 (options (append (options) (list 'opt val))))))))))
2628
2629 (define-option-interface
2630 (eval-options-interface
2631 (eval-options eval-enable eval-disable)
2632 (eval-set!)))
2633
2634 (define-option-interface
2635 (debug-options-interface
2636 (debug-options debug-enable debug-disable)
2637 (debug-set!)))
2638
2639 (define-option-interface
2640 (evaluator-traps-interface
2641 (traps trap-enable trap-disable)
2642 (trap-set!)))
2643
2644 (define-option-interface
2645 (read-options-interface
2646 (read-options read-enable read-disable)
2647 (read-set!)))
2648
2649 (define-option-interface
2650 (print-options-interface
2651 (print-options print-enable print-disable)
2652 (print-set!)))
2653
2654 \f
2655
2656 ;;; {The Unspecified Value}
2657 ;;;
2658 ;;; Currently Guile represents unspecified values via one particular value,
2659 ;;; which may be obtained by evaluating (if #f #f). It would be nice in the
2660 ;;; future if we could replace this with a return of 0 values, though.
2661 ;;;
2662
2663 (define-syntax *unspecified*
2664 (identifier-syntax (if #f #f)))
2665
2666 (define (unspecified? v) (eq? v *unspecified*))
2667
2668
2669 \f
2670
2671 ;;; {Running Repls}
2672 ;;;
2673
2674 ;; Programs can call `batch-mode?' to see if they are running as part of a
2675 ;; script or if they are running interactively. REPL implementations ensure that
2676 ;; `batch-mode?' returns #f during their extent.
2677 ;;
2678 ;; Programs can re-enter batch mode, for example after a fork, by calling
2679 ;; `ensure-batch-mode!'. This will also restore signal handlers. It's not a
2680 ;; great interface, though; it would be better to abort to the outermost prompt,
2681 ;; and call a thunk there.
2682 (define *repl-level* (make-fluid))
2683 (define (batch-mode?)
2684 (negative? (or (fluid-ref *repl-level*) -1)))
2685 (define (ensure-batch-mode!)
2686 (fluid-set! *repl-level* #f)
2687 (restore-signals))
2688
2689 (define (quit . args)
2690 (apply throw 'quit args))
2691
2692 (define exit quit)
2693
2694 (define (gc-run-time)
2695 (cdr (assq 'gc-time-taken (gc-stats))))
2696
2697 (define abort-hook (make-hook))
2698 (define before-error-hook (make-hook))
2699 (define after-error-hook (make-hook))
2700 (define before-backtrace-hook (make-hook))
2701 (define after-backtrace-hook (make-hook))
2702
2703 (define before-read-hook (make-hook))
2704 (define after-read-hook (make-hook))
2705 (define before-eval-hook (make-hook 1))
2706 (define after-eval-hook (make-hook 1))
2707 (define before-print-hook (make-hook 1))
2708 (define after-print-hook (make-hook 1))
2709
2710 ;;; The default repl-reader function. We may override this if we've
2711 ;;; the readline library.
2712 (define repl-reader
2713 (lambda* (prompt #:optional (reader (fluid-ref current-reader)))
2714 (if (not (char-ready?))
2715 (display (if (string? prompt) prompt (prompt))))
2716 (force-output)
2717 (run-hook before-read-hook)
2718 ((or reader read) (current-input-port))))
2719
2720
2721 \f
2722
2723 ;;; {IOTA functions: generating lists of numbers}
2724 ;;;
2725
2726 (define (iota n)
2727 (let loop ((count (1- n)) (result '()))
2728 (if (< count 0) result
2729 (loop (1- count) (cons count result)))))
2730
2731 \f
2732
2733 ;;; {While}
2734 ;;;
2735 ;;; with `continue' and `break'.
2736 ;;;
2737
2738 ;; The inliner will remove the prompts at compile-time if it finds that
2739 ;; `continue' or `break' are not used.
2740 ;;
2741 (define-syntax while
2742 (lambda (x)
2743 (syntax-case x ()
2744 ((while cond body ...)
2745 #`(let ((break-tag (make-prompt-tag "break"))
2746 (continue-tag (make-prompt-tag "continue")))
2747 (call-with-prompt
2748 break-tag
2749 (lambda ()
2750 (define-syntax #,(datum->syntax #'while 'break)
2751 (lambda (x)
2752 (syntax-case x ()
2753 ((_)
2754 #'(abort-to-prompt break-tag))
2755 ((_ . args)
2756 (syntax-violation 'break "too many arguments" x))
2757 (_
2758 #'(lambda ()
2759 (abort-to-prompt break-tag))))))
2760 (let lp ()
2761 (call-with-prompt
2762 continue-tag
2763 (lambda ()
2764 (define-syntax #,(datum->syntax #'while 'continue)
2765 (lambda (x)
2766 (syntax-case x ()
2767 ((_)
2768 #'(abort-to-prompt continue-tag))
2769 ((_ . args)
2770 (syntax-violation 'continue "too many arguments" x))
2771 (_
2772 #'(lambda args
2773 (apply abort-to-prompt continue-tag args))))))
2774 (do () ((not cond)) body ...))
2775 (lambda (k) (lp)))))
2776 (lambda (k)
2777 #t)))))))
2778
2779
2780 \f
2781
2782 ;;; {Module System Macros}
2783 ;;;
2784
2785 ;; Return a list of expressions that evaluate to the appropriate
2786 ;; arguments for resolve-interface according to SPEC.
2787
2788 (eval-when
2789 (compile)
2790 (if (memq 'prefix (read-options))
2791 (error "boot-9 must be compiled with #:kw, not :kw")))
2792
2793 (define (keyword-like-symbol->keyword sym)
2794 (symbol->keyword (string->symbol (substring (symbol->string sym) 1))))
2795
2796 ;; FIXME: we really need to clean up the guts of the module system.
2797 ;; We can compile to something better than process-define-module.
2798 (define-syntax define-module
2799 (lambda (x)
2800 (define (keyword-like? stx)
2801 (let ((dat (syntax->datum stx)))
2802 (and (symbol? dat)
2803 (eqv? (string-ref (symbol->string dat) 0) #\:))))
2804 (define (->keyword sym)
2805 (symbol->keyword (string->symbol (substring (symbol->string sym) 1))))
2806
2807 (define (quotify-iface args)
2808 (let loop ((in args) (out '()))
2809 (syntax-case in ()
2810 (() (reverse! out))
2811 ;; The user wanted #:foo, but wrote :foo. Fix it.
2812 ((sym . in) (keyword-like? #'sym)
2813 (loop #`(#,(->keyword (syntax->datum #'sym)) . in) out))
2814 ((kw . in) (not (keyword? (syntax->datum #'kw)))
2815 (syntax-violation 'define-module "expected keyword arg" x #'kw))
2816 ((#:renamer renamer . in)
2817 (loop #'in (cons* #'renamer #:renamer out)))
2818 ((kw val . in)
2819 (loop #'in (cons* #''val #'kw out))))))
2820
2821 (define (quotify args)
2822 ;; Just quote everything except #:use-module and #:use-syntax. We
2823 ;; need to know about all arguments regardless since we want to turn
2824 ;; symbols that look like keywords into real keywords, and the
2825 ;; keyword args in a define-module form are not regular
2826 ;; (i.e. no-backtrace doesn't take a value).
2827 (let loop ((in args) (out '()))
2828 (syntax-case in ()
2829 (() (reverse! out))
2830 ;; The user wanted #:foo, but wrote :foo. Fix it.
2831 ((sym . in) (keyword-like? #'sym)
2832 (loop #`(#,(->keyword (syntax->datum #'sym)) . in) out))
2833 ((kw . in) (not (keyword? (syntax->datum #'kw)))
2834 (syntax-violation 'define-module "expected keyword arg" x #'kw))
2835 ((#:no-backtrace . in)
2836 (loop #'in (cons #:no-backtrace out)))
2837 ((#:pure . in)
2838 (loop #'in (cons #:pure out)))
2839 ((kw)
2840 (syntax-violation 'define-module "keyword arg without value" x #'kw))
2841 ((use-module (name name* ...) . in)
2842 (and (memq (syntax->datum #'use-module) '(#:use-module #:use-syntax))
2843 (and-map symbol? (syntax->datum #'(name name* ...))))
2844 (loop #'in
2845 (cons* #''((name name* ...))
2846 #'use-module
2847 out)))
2848 ((use-module ((name name* ...) arg ...) . in)
2849 (and (memq (syntax->datum #'use-module) '(#:use-module #:use-syntax))
2850 (and-map symbol? (syntax->datum #'(name name* ...))))
2851 (loop #'in
2852 (cons* #`(list '(name name* ...) #,@(quotify-iface #'(arg ...)))
2853 #'use-module
2854 out)))
2855 ((#:autoload name bindings . in)
2856 (loop #'in (cons* #''bindings #''name #:autoload out)))
2857 ((kw val . in)
2858 (loop #'in (cons* #''val #'kw out))))))
2859
2860 (syntax-case x ()
2861 ((_ (name name* ...) arg ...)
2862 (with-syntax (((quoted-arg ...) (quotify #'(arg ...))))
2863 #'(eval-when (eval load compile expand)
2864 (let ((m (process-define-module
2865 (list '(name name* ...)
2866 #:filename (assq-ref
2867 (or (current-source-location) '())
2868 'filename)
2869 quoted-arg ...))))
2870 (set-current-module m)
2871 m)))))))
2872
2873 ;; The guts of the use-modules macro. Add the interfaces of the named
2874 ;; modules to the use-list of the current module, in order.
2875
2876 ;; This function is called by "modules.c". If you change it, be sure
2877 ;; to change scm_c_use_module as well.
2878
2879 (define (process-use-modules module-interface-args)
2880 (let ((interfaces (map (lambda (mif-args)
2881 (or (apply resolve-interface mif-args)
2882 (error "no such module" mif-args)))
2883 module-interface-args)))
2884 (call-with-deferred-observers
2885 (lambda ()
2886 (module-use-interfaces! (current-module) interfaces)))))
2887
2888 (define-syntax use-modules
2889 (lambda (x)
2890 (define (keyword-like? stx)
2891 (let ((dat (syntax->datum stx)))
2892 (and (symbol? dat)
2893 (eqv? (string-ref (symbol->string dat) 0) #\:))))
2894 (define (->keyword sym)
2895 (symbol->keyword (string->symbol (substring (symbol->string sym) 1))))
2896
2897 (define (quotify-iface args)
2898 (let loop ((in args) (out '()))
2899 (syntax-case in ()
2900 (() (reverse! out))
2901 ;; The user wanted #:foo, but wrote :foo. Fix it.
2902 ((sym . in) (keyword-like? #'sym)
2903 (loop #`(#,(->keyword (syntax->datum #'sym)) . in) out))
2904 ((kw . in) (not (keyword? (syntax->datum #'kw)))
2905 (syntax-violation 'define-module "expected keyword arg" x #'kw))
2906 ((#:renamer renamer . in)
2907 (loop #'in (cons* #'renamer #:renamer out)))
2908 ((kw val . in)
2909 (loop #'in (cons* #''val #'kw out))))))
2910
2911 (define (quotify specs)
2912 (let lp ((in specs) (out '()))
2913 (syntax-case in ()
2914 (() (reverse out))
2915 (((name name* ...) . in)
2916 (and-map symbol? (syntax->datum #'(name name* ...)))
2917 (lp #'in (cons #''((name name* ...)) out)))
2918 ((((name name* ...) arg ...) . in)
2919 (and-map symbol? (syntax->datum #'(name name* ...)))
2920 (with-syntax (((quoted-arg ...) (quotify-iface #'(arg ...))))
2921 (lp #'in (cons #`(list '(name name* ...) quoted-arg ...)
2922 out)))))))
2923
2924 (syntax-case x ()
2925 ((_ spec ...)
2926 (with-syntax (((quoted-args ...) (quotify #'(spec ...))))
2927 #'(eval-when (eval load compile expand)
2928 (process-use-modules (list quoted-args ...))
2929 *unspecified*))))))
2930
2931 (define-syntax use-syntax
2932 (syntax-rules ()
2933 ((_ spec ...)
2934 (begin
2935 (eval-when (eval load compile expand)
2936 (issue-deprecation-warning
2937 "`use-syntax' is deprecated. Please contact guile-devel for more info."))
2938 (use-modules spec ...)))))
2939
2940 (include-from-path "ice-9/r6rs-libraries")
2941
2942 (define-syntax define-private
2943 (syntax-rules ()
2944 ((_ foo bar)
2945 (define foo bar))))
2946
2947 (define-syntax define-public
2948 (syntax-rules ()
2949 ((_ (name . args) . body)
2950 (define-public name (lambda args . body)))
2951 ((_ name val)
2952 (begin
2953 (define name val)
2954 (export name)))))
2955
2956 (define-syntax defmacro-public
2957 (syntax-rules ()
2958 ((_ name args . body)
2959 (begin
2960 (defmacro name args . body)
2961 (export-syntax name)))))
2962
2963 ;; And now for the most important macro.
2964 (define-syntax λ
2965 (syntax-rules ()
2966 ((_ formals body ...)
2967 (lambda formals body ...))))
2968
2969 \f
2970 ;; Export a local variable
2971
2972 ;; This function is called from "modules.c". If you change it, be
2973 ;; sure to update "modules.c" as well.
2974
2975 (define (module-export! m names)
2976 (let ((public-i (module-public-interface m)))
2977 (for-each (lambda (name)
2978 (let* ((internal-name (if (pair? name) (car name) name))
2979 (external-name (if (pair? name) (cdr name) name))
2980 (var (module-ensure-local-variable! m internal-name)))
2981 (module-add! public-i external-name var)))
2982 names)))
2983
2984 (define (module-replace! m names)
2985 (let ((public-i (module-public-interface m)))
2986 (for-each (lambda (name)
2987 (let* ((internal-name (if (pair? name) (car name) name))
2988 (external-name (if (pair? name) (cdr name) name))
2989 (var (module-ensure-local-variable! m internal-name)))
2990 (set-object-property! var 'replace #t)
2991 (module-add! public-i external-name var)))
2992 names)))
2993
2994 ;; Export all local variables from a module
2995 ;;
2996 (define (module-export-all! mod)
2997 (define (fresh-interface!)
2998 (let ((iface (make-module)))
2999 (set-module-name! iface (module-name mod))
3000 (set-module-version! iface (module-version mod))
3001 (set-module-kind! iface 'interface)
3002 (set-module-public-interface! mod iface)
3003 iface))
3004 (let ((iface (or (module-public-interface mod)
3005 (fresh-interface!))))
3006 (set-module-obarray! iface (module-obarray mod))))
3007
3008 ;; Re-export a imported variable
3009 ;;
3010 (define (module-re-export! m names)
3011 (let ((public-i (module-public-interface m)))
3012 (for-each (lambda (name)
3013 (let* ((internal-name (if (pair? name) (car name) name))
3014 (external-name (if (pair? name) (cdr name) name))
3015 (var (module-variable m internal-name)))
3016 (cond ((not var)
3017 (error "Undefined variable:" internal-name))
3018 ((eq? var (module-local-variable m internal-name))
3019 (error "re-exporting local variable:" internal-name))
3020 (else
3021 (module-add! public-i external-name var)))))
3022 names)))
3023
3024 (define-syntax export
3025 (syntax-rules ()
3026 ((_ name ...)
3027 (eval-when (eval load compile expand)
3028 (call-with-deferred-observers
3029 (lambda ()
3030 (module-export! (current-module) '(name ...))))))))
3031
3032 (define-syntax re-export
3033 (syntax-rules ()
3034 ((_ name ...)
3035 (eval-when (eval load compile expand)
3036 (call-with-deferred-observers
3037 (lambda ()
3038 (module-re-export! (current-module) '(name ...))))))))
3039
3040 (define-syntax export-syntax
3041 (syntax-rules ()
3042 ((_ name ...)
3043 (export name ...))))
3044
3045 (define-syntax re-export-syntax
3046 (syntax-rules ()
3047 ((_ name ...)
3048 (re-export name ...))))
3049
3050 (define load load-module)
3051
3052 \f
3053
3054 ;;; {Parameters}
3055 ;;;
3056
3057 (define make-mutable-parameter
3058 (let ((make (lambda (fluid converter)
3059 (lambda args
3060 (if (null? args)
3061 (fluid-ref fluid)
3062 (fluid-set! fluid (converter (car args))))))))
3063 (lambda* (init #:optional (converter identity))
3064 (let ((fluid (make-fluid)))
3065 (fluid-set! fluid (converter init))
3066 (make fluid converter)))))
3067
3068 \f
3069
3070 ;;; {Handling of duplicate imported bindings}
3071 ;;;
3072
3073 ;; Duplicate handlers take the following arguments:
3074 ;;
3075 ;; module importing module
3076 ;; name conflicting name
3077 ;; int1 old interface where name occurs
3078 ;; val1 value of binding in old interface
3079 ;; int2 new interface where name occurs
3080 ;; val2 value of binding in new interface
3081 ;; var previous resolution or #f
3082 ;; val value of previous resolution
3083 ;;
3084 ;; A duplicate handler can take three alternative actions:
3085 ;;
3086 ;; 1. return #f => leave responsibility to next handler
3087 ;; 2. exit with an error
3088 ;; 3. return a variable resolving the conflict
3089 ;;
3090
3091 (define duplicate-handlers
3092 (let ((m (make-module 7)))
3093
3094 (define (check module name int1 val1 int2 val2 var val)
3095 (scm-error 'misc-error
3096 #f
3097 "~A: `~A' imported from both ~A and ~A"
3098 (list (module-name module)
3099 name
3100 (module-name int1)
3101 (module-name int2))
3102 #f))
3103
3104 (define (warn module name int1 val1 int2 val2 var val)
3105 (format (current-error-port)
3106 "WARNING: ~A: `~A' imported from both ~A and ~A\n"
3107 (module-name module)
3108 name
3109 (module-name int1)
3110 (module-name int2))
3111 #f)
3112
3113 (define (replace module name int1 val1 int2 val2 var val)
3114 (let ((old (or (and var (object-property var 'replace) var)
3115 (module-variable int1 name)))
3116 (new (module-variable int2 name)))
3117 (if (object-property old 'replace)
3118 (and (or (eq? old new)
3119 (not (object-property new 'replace)))
3120 old)
3121 (and (object-property new 'replace)
3122 new))))
3123
3124 (define (warn-override-core module name int1 val1 int2 val2 var val)
3125 (and (eq? int1 the-scm-module)
3126 (begin
3127 (format (current-error-port)
3128 "WARNING: ~A: imported module ~A overrides core binding `~A'\n"
3129 (module-name module)
3130 (module-name int2)
3131 name)
3132 (module-local-variable int2 name))))
3133
3134 (define (first module name int1 val1 int2 val2 var val)
3135 (or var (module-local-variable int1 name)))
3136
3137 (define (last module name int1 val1 int2 val2 var val)
3138 (module-local-variable int2 name))
3139
3140 (define (noop module name int1 val1 int2 val2 var val)
3141 #f)
3142
3143 (set-module-name! m 'duplicate-handlers)
3144 (set-module-kind! m 'interface)
3145 (module-define! m 'check check)
3146 (module-define! m 'warn warn)
3147 (module-define! m 'replace replace)
3148 (module-define! m 'warn-override-core warn-override-core)
3149 (module-define! m 'first first)
3150 (module-define! m 'last last)
3151 (module-define! m 'merge-generics noop)
3152 (module-define! m 'merge-accessors noop)
3153 m))
3154
3155 (define (lookup-duplicates-handlers handler-names)
3156 (and handler-names
3157 (map (lambda (handler-name)
3158 (or (module-symbol-local-binding
3159 duplicate-handlers handler-name #f)
3160 (error "invalid duplicate handler name:"
3161 handler-name)))
3162 (if (list? handler-names)
3163 handler-names
3164 (list handler-names)))))
3165
3166 (define default-duplicate-binding-procedures
3167 (make-mutable-parameter #f))
3168
3169 (define default-duplicate-binding-handler
3170 (make-mutable-parameter '(replace warn-override-core warn last)
3171 (lambda (handler-names)
3172 (default-duplicate-binding-procedures
3173 (lookup-duplicates-handlers handler-names))
3174 handler-names)))
3175
3176 \f
3177
3178 ;;; {`cond-expand' for SRFI-0 support.}
3179 ;;;
3180 ;;; This syntactic form expands into different commands or
3181 ;;; definitions, depending on the features provided by the Scheme
3182 ;;; implementation.
3183 ;;;
3184 ;;; Syntax:
3185 ;;;
3186 ;;; <cond-expand>
3187 ;;; --> (cond-expand <cond-expand-clause>+)
3188 ;;; | (cond-expand <cond-expand-clause>* (else <command-or-definition>))
3189 ;;; <cond-expand-clause>
3190 ;;; --> (<feature-requirement> <command-or-definition>*)
3191 ;;; <feature-requirement>
3192 ;;; --> <feature-identifier>
3193 ;;; | (and <feature-requirement>*)
3194 ;;; | (or <feature-requirement>*)
3195 ;;; | (not <feature-requirement>)
3196 ;;; <feature-identifier>
3197 ;;; --> <a symbol which is the name or alias of a SRFI>
3198 ;;;
3199 ;;; Additionally, this implementation provides the
3200 ;;; <feature-identifier>s `guile' and `r5rs', so that programs can
3201 ;;; determine the implementation type and the supported standard.
3202 ;;;
3203 ;;; Currently, the following feature identifiers are supported:
3204 ;;;
3205 ;;; guile r5rs srfi-0 srfi-4 srfi-6 srfi-13 srfi-14 srfi-55 srfi-61
3206 ;;;
3207 ;;; Remember to update the features list when adding more SRFIs.
3208 ;;;
3209
3210 (define %cond-expand-features
3211 ;; Adjust the above comment when changing this.
3212 '(guile
3213 guile-2
3214 r5rs
3215 srfi-0 ;; cond-expand itself
3216 srfi-4 ;; homogenous numeric vectors
3217 srfi-6 ;; open-input-string etc, in the guile core
3218 srfi-13 ;; string library
3219 srfi-14 ;; character sets
3220 srfi-55 ;; require-extension
3221 srfi-61 ;; general cond clause
3222 ))
3223
3224 ;; This table maps module public interfaces to the list of features.
3225 ;;
3226 (define %cond-expand-table (make-hash-table 31))
3227
3228 ;; Add one or more features to the `cond-expand' feature list of the
3229 ;; module `module'.
3230 ;;
3231 (define (cond-expand-provide module features)
3232 (let ((mod (module-public-interface module)))
3233 (and mod
3234 (hashq-set! %cond-expand-table mod
3235 (append (hashq-ref %cond-expand-table mod '())
3236 features)))))
3237
3238 (define-macro (cond-expand . clauses)
3239 (let ((syntax-error (lambda (cl)
3240 (error "invalid clause in `cond-expand'" cl))))
3241 (letrec
3242 ((test-clause
3243 (lambda (clause)
3244 (cond
3245 ((symbol? clause)
3246 (or (memq clause %cond-expand-features)
3247 (let lp ((uses (module-uses (current-module))))
3248 (if (pair? uses)
3249 (or (memq clause
3250 (hashq-ref %cond-expand-table
3251 (car uses) '()))
3252 (lp (cdr uses)))
3253 #f))))
3254 ((pair? clause)
3255 (cond
3256 ((eq? 'and (car clause))
3257 (let lp ((l (cdr clause)))
3258 (cond ((null? l)
3259 #t)
3260 ((pair? l)
3261 (and (test-clause (car l)) (lp (cdr l))))
3262 (else
3263 (syntax-error clause)))))
3264 ((eq? 'or (car clause))
3265 (let lp ((l (cdr clause)))
3266 (cond ((null? l)
3267 #f)
3268 ((pair? l)
3269 (or (test-clause (car l)) (lp (cdr l))))
3270 (else
3271 (syntax-error clause)))))
3272 ((eq? 'not (car clause))
3273 (cond ((not (pair? (cdr clause)))
3274 (syntax-error clause))
3275 ((pair? (cddr clause))
3276 ((syntax-error clause))))
3277 (not (test-clause (cadr clause))))
3278 (else
3279 (syntax-error clause))))
3280 (else
3281 (syntax-error clause))))))
3282 (let lp ((c clauses))
3283 (cond
3284 ((null? c)
3285 (error "Unfulfilled `cond-expand'"))
3286 ((not (pair? c))
3287 (syntax-error c))
3288 ((not (pair? (car c)))
3289 (syntax-error (car c)))
3290 ((test-clause (caar c))
3291 `(begin ,@(cdar c)))
3292 ((eq? (caar c) 'else)
3293 (if (pair? (cdr c))
3294 (syntax-error c))
3295 `(begin ,@(cdar c)))
3296 (else
3297 (lp (cdr c))))))))
3298
3299 ;; This procedure gets called from the startup code with a list of
3300 ;; numbers, which are the numbers of the SRFIs to be loaded on startup.
3301 ;;
3302 (define (use-srfis srfis)
3303 (process-use-modules
3304 (map (lambda (num)
3305 (list (list 'srfi (string->symbol
3306 (string-append "srfi-" (number->string num))))))
3307 srfis)))
3308
3309 \f
3310
3311 ;;; srfi-55: require-extension
3312 ;;;
3313
3314 (define-macro (require-extension extension-spec)
3315 ;; This macro only handles the srfi extension, which, at present, is
3316 ;; the only one defined by the standard.
3317 (if (not (pair? extension-spec))
3318 (scm-error 'wrong-type-arg "require-extension"
3319 "Not an extension: ~S" (list extension-spec) #f))
3320 (let ((extension (car extension-spec))
3321 (extension-args (cdr extension-spec)))
3322 (case extension
3323 ((srfi)
3324 (let ((use-list '()))
3325 (for-each
3326 (lambda (i)
3327 (if (not (integer? i))
3328 (scm-error 'wrong-type-arg "require-extension"
3329 "Invalid srfi name: ~S" (list i) #f))
3330 (let ((srfi-sym (string->symbol
3331 (string-append "srfi-" (number->string i)))))
3332 (if (not (memq srfi-sym %cond-expand-features))
3333 (set! use-list (cons `(use-modules (srfi ,srfi-sym))
3334 use-list)))))
3335 extension-args)
3336 (if (pair? use-list)
3337 ;; i.e. (begin (use-modules x) (use-modules y) (use-modules z))
3338 `(begin ,@(reverse! use-list)))))
3339 (else
3340 (scm-error
3341 'wrong-type-arg "require-extension"
3342 "Not a recognized extension type: ~S" (list extension) #f)))))
3343
3344 \f
3345
3346 ;;; {Load emacs interface support if emacs option is given.}
3347 ;;;
3348
3349 (define (named-module-use! user usee)
3350 (module-use! (resolve-module user) (resolve-interface usee)))
3351
3352 (define (load-emacs-interface)
3353 (and (provided? 'debug-extensions)
3354 (debug-enable 'backtrace))
3355 (named-module-use! '(guile-user) '(ice-9 emacs)))
3356
3357 \f
3358
3359 (define using-readline?
3360 (let ((using-readline? (make-fluid)))
3361 (make-procedure-with-setter
3362 (lambda () (fluid-ref using-readline?))
3363 (lambda (v) (fluid-set! using-readline? v)))))
3364
3365 (define (top-repl)
3366 (let ((guile-user-module (resolve-module '(guile-user))))
3367
3368 ;; Load emacs interface support if emacs option is given.
3369 (if (and (module-defined? guile-user-module 'use-emacs-interface)
3370 (module-ref guile-user-module 'use-emacs-interface))
3371 (load-emacs-interface))
3372
3373 ;; Use some convenient modules (in reverse order)
3374
3375 (set-current-module guile-user-module)
3376 (process-use-modules
3377 (append
3378 '(((ice-9 r5rs))
3379 ((ice-9 session))
3380 ((ice-9 debug)))
3381 (if (provided? 'regex)
3382 '(((ice-9 regex)))
3383 '())
3384 (if (provided? 'threads)
3385 '(((ice-9 threads)))
3386 '())))
3387 ;; load debugger on demand
3388 (module-autoload! guile-user-module '(system vm debug) '(debug))
3389
3390 ;; Note: SIGFPE, SIGSEGV and SIGBUS are actually "query-only" (see
3391 ;; scmsigs.c scm_sigaction_for_thread), so the handlers setup here have
3392 ;; no effect.
3393 (let ((old-handlers #f)
3394 ;; We can't use @ here, as modules have been booted, but in Guile's
3395 ;; build the srfi-1 helper lib hasn't been built yet, which will
3396 ;; result in an error when (system repl repl) is loaded at compile
3397 ;; time (to see if it is a macro or not).
3398 (start-repl (module-ref (resolve-module '(system repl repl))
3399 'start-repl))
3400 (signals (if (provided? 'posix)
3401 `((,SIGINT . "User interrupt")
3402 (,SIGFPE . "Arithmetic error")
3403 (,SIGSEGV
3404 . "Bad memory access (Segmentation violation)"))
3405 '())))
3406 ;; no SIGBUS on mingw
3407 (if (defined? 'SIGBUS)
3408 (set! signals (acons SIGBUS "Bad memory access (bus error)"
3409 signals)))
3410
3411 (dynamic-wind
3412
3413 ;; call at entry
3414 (lambda ()
3415 (let ((make-handler (lambda (msg)
3416 (lambda (sig)
3417 (scm-error 'signal
3418 #f
3419 msg
3420 #f
3421 (list sig))))))
3422 (set! old-handlers
3423 (map (lambda (sig-msg)
3424 (sigaction (car sig-msg)
3425 (make-handler (cdr sig-msg))))
3426 signals))))
3427
3428 ;; the protected thunk.
3429 (lambda ()
3430 (let ((status (start-repl 'scheme)))
3431 (run-hook exit-hook)
3432 status))
3433
3434 ;; call at exit.
3435 (lambda ()
3436 (map (lambda (sig-msg old-handler)
3437 (if (not (car old-handler))
3438 ;; restore original C handler.
3439 (sigaction (car sig-msg) #f)
3440 ;; restore Scheme handler, SIG_IGN or SIG_DFL.
3441 (sigaction (car sig-msg)
3442 (car old-handler)
3443 (cdr old-handler))))
3444 signals old-handlers))))))
3445
3446 ;;; This hook is run at the very end of an interactive session.
3447 ;;;
3448 (define exit-hook (make-hook))
3449
3450 \f
3451
3452 ;;; {Deprecated stuff}
3453 ;;;
3454
3455 (begin-deprecated
3456 (module-use! the-scm-module (resolve-interface '(ice-9 deprecated))))
3457
3458 \f
3459
3460 ;;; Place the user in the guile-user module.
3461 ;;;
3462
3463 ;; FIXME:
3464 (module-use! the-scm-module (resolve-interface '(srfi srfi-4)))
3465
3466 (define-module (guile-user)
3467 #:autoload (system base compile) (compile))
3468
3469 ;; Remain in the `(guile)' module at compilation-time so that the
3470 ;; `-Wunused-toplevel' warning works as expected.
3471 (eval-when (compile) (set-current-module the-root-module))
3472
3473 ;;; boot-9.scm ends here