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