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