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