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