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