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