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