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