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