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