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