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