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