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