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