remove a number of debug options
[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 'backtrace)
1033 (read-enable 'positions))
1034
1035 (define (load-user-init)
1036 (let* ((home (or (getenv "HOME")
1037 (false-if-exception (passwd:dir (getpwuid (getuid))))
1038 "/")) ;; fallback for cygwin etc.
1039 (init-file (in-vicinity home ".guile")))
1040 (if (file-exists? init-file)
1041 (primitive-load init-file))))
1042
1043 \f
1044
1045 ;;; {The interpreter stack}
1046 ;;;
1047
1048 ;; %stacks defined in stacks.c
1049 (define (%start-stack tag thunk)
1050 (let ((prompt-tag (make-prompt-tag "start-stack")))
1051 (call-with-prompt
1052 prompt-tag
1053 (lambda ()
1054 (with-fluids ((%stacks (acons tag prompt-tag
1055 (or (fluid-ref %stacks) '()))))
1056 (thunk)))
1057 (lambda (k . args)
1058 (%start-stack tag (lambda () (apply k args)))))))
1059 (define-syntax start-stack
1060 (syntax-rules ()
1061 ((_ tag exp)
1062 (%start-stack tag (lambda () exp)))))
1063
1064 \f
1065
1066 ;;; {Loading by paths}
1067 ;;;
1068
1069 ;;; Load a Scheme source file named NAME, searching for it in the
1070 ;;; directories listed in %load-path, and applying each of the file
1071 ;;; name extensions listed in %load-extensions.
1072 (define (load-from-path name)
1073 (start-stack 'load-stack
1074 (primitive-load-path name)))
1075
1076 (define %load-verbosely #f)
1077 (define (assert-load-verbosity v) (set! %load-verbosely v))
1078
1079 (define (%load-announce file)
1080 (if %load-verbosely
1081 (with-output-to-port (current-error-port)
1082 (lambda ()
1083 (display ";;; ")
1084 (display "loading ")
1085 (display file)
1086 (newline)
1087 (force-output)))))
1088
1089 (set! %load-hook %load-announce)
1090
1091 (define* (load name #:optional reader)
1092 ;; Returns the .go file corresponding to `name'. Does not search load
1093 ;; paths, only the fallback path. If the .go file is missing or out of
1094 ;; date, and autocompilation is enabled, will try autocompilation, just
1095 ;; as primitive-load-path does internally. primitive-load is
1096 ;; unaffected. Returns #f if autocompilation failed or was disabled.
1097 ;;
1098 ;; NB: Unless we need to compile the file, this function should not cause
1099 ;; (system base compile) to be loaded up. For that reason compiled-file-name
1100 ;; partially duplicates functionality from (system base compile).
1101 (define (compiled-file-name canon-path)
1102 (and %compile-fallback-path
1103 (string-append
1104 %compile-fallback-path
1105 ;; no need for '/' separator here, canon-path is absolute
1106 canon-path
1107 (cond ((or (null? %load-compiled-extensions)
1108 (string-null? (car %load-compiled-extensions)))
1109 (warn "invalid %load-compiled-extensions"
1110 %load-compiled-extensions)
1111 ".go")
1112 (else (car %load-compiled-extensions))))))
1113 (define (fresh-compiled-file-name go-path)
1114 (catch #t
1115 (lambda ()
1116 (let* ((scmstat (stat name))
1117 (gostat (stat go-path #f)))
1118 (if (and gostat
1119 (or (> (stat:mtime gostat) (stat:mtime scmstat))
1120 (and (= (stat:mtime gostat) (stat:mtime scmstat))
1121 (>= (stat:mtimensec gostat)
1122 (stat:mtimensec scmstat)))))
1123 go-path
1124 (begin
1125 (if gostat
1126 (format (current-error-port)
1127 ";;; note: source file ~a\n;;; newer than compiled ~a\n"
1128 name go-path))
1129 (cond
1130 (%load-should-autocompile
1131 (%warn-autocompilation-enabled)
1132 (format (current-error-port) ";;; compiling ~a\n" name)
1133 ;; This use of @ is (ironically?) boot-safe, as modules have
1134 ;; not been booted yet, so the resolve-module call in psyntax
1135 ;; doesn't try to load a module, and compile-file will be
1136 ;; treated as a function, not a macro.
1137 (let ((cfn ((@ (system base compile) compile-file) name
1138 #:env (current-module))))
1139 (format (current-error-port) ";;; compiled ~a\n" cfn)
1140 cfn))
1141 (else #f))))))
1142 (lambda (k . args)
1143 (format (current-error-port)
1144 ";;; WARNING: compilation of ~a failed:\n;;; key ~a, throw_args ~s\n"
1145 name k args)
1146 #f)))
1147 (with-fluids ((current-reader reader))
1148 (let ((cfn (and=> (and=> (false-if-exception (canonicalize-path name))
1149 compiled-file-name)
1150 fresh-compiled-file-name)))
1151 (if cfn
1152 (load-compiled cfn)
1153 (start-stack 'load-stack
1154 (primitive-load name))))))
1155
1156 \f
1157
1158 ;;; {Reader Extensions}
1159 ;;;
1160 ;;; Reader code for various "#c" forms.
1161 ;;;
1162
1163 (define read-eval? (make-fluid))
1164 (fluid-set! read-eval? #f)
1165 (read-hash-extend #\.
1166 (lambda (c port)
1167 (if (fluid-ref read-eval?)
1168 (eval (read port) (interaction-environment))
1169 (error
1170 "#. read expansion found and read-eval? is #f."))))
1171
1172 \f
1173
1174 ;;; {Low Level Modules}
1175 ;;;
1176 ;;; These are the low level data structures for modules.
1177 ;;;
1178 ;;; Every module object is of the type 'module-type', which is a record
1179 ;;; consisting of the following members:
1180 ;;;
1181 ;;; - eval-closure: the function that defines for its module the strategy that
1182 ;;; shall be followed when looking up symbols in the module.
1183 ;;;
1184 ;;; An eval-closure is a function taking two arguments: the symbol to be
1185 ;;; looked up and a boolean value telling whether a binding for the symbol
1186 ;;; should be created if it does not exist yet. If the symbol lookup
1187 ;;; succeeded (either because an existing binding was found or because a new
1188 ;;; binding was created), a variable object representing the binding is
1189 ;;; returned. Otherwise, the value #f is returned. Note that the eval
1190 ;;; closure does not take the module to be searched as an argument: During
1191 ;;; construction of the eval-closure, the eval-closure has to store the
1192 ;;; module it belongs to in its environment. This means, that any
1193 ;;; eval-closure can belong to only one module.
1194 ;;;
1195 ;;; The eval-closure of a module can be defined arbitrarily. However, three
1196 ;;; special cases of eval-closures are to be distinguished: During startup
1197 ;;; the module system is not yet activated. In this phase, no modules are
1198 ;;; defined and all bindings are automatically stored by the system in the
1199 ;;; pre-modules-obarray. Since no eval-closures exist at this time, the
1200 ;;; functions which require an eval-closure as their argument need to be
1201 ;;; passed the value #f.
1202 ;;;
1203 ;;; The other two special cases of eval-closures are the
1204 ;;; standard-eval-closure and the standard-interface-eval-closure. Both
1205 ;;; behave equally for the case that no new binding is to be created. The
1206 ;;; difference between the two comes in, when the boolean argument to the
1207 ;;; eval-closure indicates that a new binding shall be created if it is not
1208 ;;; found.
1209 ;;;
1210 ;;; Given that no new binding shall be created, both standard eval-closures
1211 ;;; define the following standard strategy of searching bindings in the
1212 ;;; module: First, the module's obarray is searched for the symbol. Second,
1213 ;;; if no binding for the symbol was found in the module's obarray, the
1214 ;;; module's binder procedure is exececuted. If this procedure did not
1215 ;;; return a binding for the symbol, the modules referenced in the module's
1216 ;;; uses list are recursively searched for a binding of the symbol. If the
1217 ;;; binding can not be found in these modules also, the symbol lookup has
1218 ;;; failed.
1219 ;;;
1220 ;;; If a new binding shall be created, the standard-interface-eval-closure
1221 ;;; immediately returns indicating failure. That is, it does not even try
1222 ;;; to look up the symbol. In contrast, the standard-eval-closure would
1223 ;;; first search the obarray, and if no binding was found there, would
1224 ;;; create a new binding in the obarray, therefore not calling the binder
1225 ;;; procedure or searching the modules in the uses list.
1226 ;;;
1227 ;;; The explanation of the following members obarray, binder and uses
1228 ;;; assumes that the symbol lookup follows the strategy that is defined in
1229 ;;; the standard-eval-closure and the standard-interface-eval-closure.
1230 ;;;
1231 ;;; - obarray: a hash table that maps symbols to variable objects. In this
1232 ;;; hash table, the definitions are found that are local to the module (that
1233 ;;; is, not imported from other modules). When looking up bindings in the
1234 ;;; module, this hash table is searched first.
1235 ;;;
1236 ;;; - binder: either #f or a function taking a module and a symbol argument.
1237 ;;; If it is a function it is called after the obarray has been
1238 ;;; unsuccessfully searched for a binding. It then can provide bindings
1239 ;;; that would otherwise not be found locally in the module.
1240 ;;;
1241 ;;; - uses: a list of modules from which non-local bindings can be inherited.
1242 ;;; These modules are the third place queried for bindings after the obarray
1243 ;;; has been unsuccessfully searched and the binder function did not deliver
1244 ;;; a result either.
1245 ;;;
1246 ;;; - transformer: either #f or a function taking a scheme expression as
1247 ;;; delivered by read. If it is a function, it will be called to perform
1248 ;;; syntax transformations (e. g. makro expansion) on the given scheme
1249 ;;; expression. The output of the transformer function will then be passed
1250 ;;; to Guile's internal memoizer. This means that the output must be valid
1251 ;;; scheme code. The only exception is, that the output may make use of the
1252 ;;; syntax extensions provided to identify the modules that a binding
1253 ;;; belongs to.
1254 ;;;
1255 ;;; - name: the name of the module. This is used for all kinds of printing
1256 ;;; outputs. In certain places the module name also serves as a way of
1257 ;;; identification. When adding a module to the uses list of another
1258 ;;; module, it is made sure that the new uses list will not contain two
1259 ;;; modules of the same name.
1260 ;;;
1261 ;;; - kind: classification of the kind of module. The value is (currently?)
1262 ;;; only used for printing. It has no influence on how a module is treated.
1263 ;;; Currently the following values are used when setting the module kind:
1264 ;;; 'module, 'directory, 'interface, 'custom-interface. If no explicit kind
1265 ;;; is set, it defaults to 'module.
1266 ;;;
1267 ;;; - duplicates-handlers: a list of procedures that get called to make a
1268 ;;; choice between two duplicate bindings when name clashes occur. See the
1269 ;;; `duplicate-handlers' global variable below.
1270 ;;;
1271 ;;; - observers: a list of procedures that get called when the module is
1272 ;;; modified.
1273 ;;;
1274 ;;; - weak-observers: a weak-key hash table of procedures that get called
1275 ;;; when the module is modified. See `module-observe-weak' for details.
1276 ;;;
1277 ;;; In addition, the module may (must?) contain a binding for
1278 ;;; `%module-public-interface'. This variable should be bound to a module
1279 ;;; representing the exported interface of a module. See the
1280 ;;; `module-public-interface' and `module-export!' procedures.
1281 ;;;
1282 ;;; !!! warning: The interface to lazy binder procedures is going
1283 ;;; to be changed in an incompatible way to permit all the basic
1284 ;;; module ops to be virtualized.
1285 ;;;
1286 ;;; (make-module size use-list lazy-binding-proc) => module
1287 ;;; module-{obarray,uses,binder}[|-set!]
1288 ;;; (module? obj) => [#t|#f]
1289 ;;; (module-locally-bound? module symbol) => [#t|#f]
1290 ;;; (module-bound? module symbol) => [#t|#f]
1291 ;;; (module-symbol-locally-interned? module symbol) => [#t|#f]
1292 ;;; (module-symbol-interned? module symbol) => [#t|#f]
1293 ;;; (module-local-variable module symbol) => [#<variable ...> | #f]
1294 ;;; (module-variable module symbol) => [#<variable ...> | #f]
1295 ;;; (module-symbol-binding module symbol opt-value)
1296 ;;; => [ <obj> | opt-value | an error occurs ]
1297 ;;; (module-make-local-var! module symbol) => #<variable...>
1298 ;;; (module-add! module symbol var) => unspecified
1299 ;;; (module-remove! module symbol) => unspecified
1300 ;;; (module-for-each proc module) => unspecified
1301 ;;; (make-scm-module) => module ; a lazy copy of the symhash module
1302 ;;; (set-current-module module) => unspecified
1303 ;;; (current-module) => #<module...>
1304 ;;;
1305 ;;;
1306
1307 \f
1308
1309 ;;; {Printing Modules}
1310 ;;;
1311
1312 ;; This is how modules are printed. You can re-define it.
1313 (define (%print-module mod port)
1314 (display "#<" port)
1315 (display (or (module-kind mod) "module") port)
1316 (display " " port)
1317 (display (module-name mod) port)
1318 (display " " port)
1319 (display (number->string (object-address mod) 16) port)
1320 (display ">" port))
1321
1322 (letrec-syntax
1323 ;; Locally extend the syntax to allow record accessors to be defined at
1324 ;; compile-time. Cache the rtd locally to the constructor, the getters and
1325 ;; the setters, in order to allow for redefinition of the record type; not
1326 ;; relevant in the case of modules, but perhaps if we make this public, it
1327 ;; could matter.
1328
1329 ((define-record-type
1330 (lambda (x)
1331 (define (make-id scope . fragments)
1332 (datum->syntax #'scope
1333 (apply symbol-append
1334 (map (lambda (x)
1335 (if (symbol? x) x (syntax->datum x)))
1336 fragments))))
1337
1338 (define (getter rtd type-name field slot)
1339 #`(define #,(make-id rtd type-name '- field)
1340 (let ((rtd #,rtd))
1341 (lambda (#,type-name)
1342 (if (eq? (struct-vtable #,type-name) rtd)
1343 (struct-ref #,type-name #,slot)
1344 (%record-type-error rtd #,type-name))))))
1345
1346 (define (setter rtd type-name field slot)
1347 #`(define #,(make-id rtd 'set- type-name '- field '!)
1348 (let ((rtd #,rtd))
1349 (lambda (#,type-name val)
1350 (if (eq? (struct-vtable #,type-name) rtd)
1351 (struct-set! #,type-name #,slot val)
1352 (%record-type-error rtd #,type-name))))))
1353
1354 (define (accessors rtd type-name fields n exp)
1355 (syntax-case fields ()
1356 (() exp)
1357 (((field #:no-accessors) field* ...) (identifier? #'field)
1358 (accessors rtd type-name #'(field* ...) (1+ n)
1359 exp))
1360 (((field #:no-setter) field* ...) (identifier? #'field)
1361 (accessors rtd type-name #'(field* ...) (1+ n)
1362 #`(begin #,exp
1363 #,(getter rtd type-name #'field n))))
1364 (((field #:no-getter) field* ...) (identifier? #'field)
1365 (accessors rtd type-name #'(field* ...) (1+ n)
1366 #`(begin #,exp
1367 #,(setter rtd type-name #'field n))))
1368 ((field field* ...) (identifier? #'field)
1369 (accessors rtd type-name #'(field* ...) (1+ n)
1370 #`(begin #,exp
1371 #,(getter rtd type-name #'field n)
1372 #,(setter rtd type-name #'field n))))))
1373
1374 (define (predicate rtd type-name fields exp)
1375 (accessors
1376 rtd type-name fields 0
1377 #`(begin
1378 #,exp
1379 (define (#,(make-id rtd type-name '?) obj)
1380 (and (struct? obj) (eq? (struct-vtable obj) #,rtd))))))
1381
1382 (define (field-list fields)
1383 (syntax-case fields ()
1384 (() '())
1385 (((f . opts) . rest) (identifier? #'f)
1386 (cons #'f (field-list #'rest)))
1387 ((f . rest) (identifier? #'f)
1388 (cons #'f (field-list #'rest)))))
1389
1390 (define (constructor rtd type-name fields exp)
1391 (let ((ctor (make-id rtd type-name '-constructor))
1392 (args (field-list fields)))
1393 (predicate rtd type-name fields
1394 #`(begin #,exp
1395 (define #,ctor
1396 (let ((rtd #,rtd))
1397 (lambda #,args
1398 (make-struct rtd 0 #,@args))))
1399 (struct-set! #,rtd (+ vtable-offset-user 2)
1400 #,ctor)))))
1401
1402 (define (type type-name printer fields)
1403 (define (make-layout)
1404 (let lp ((fields fields) (slots '()))
1405 (syntax-case fields ()
1406 (() (datum->syntax #'here
1407 (make-struct-layout
1408 (apply string-append slots))))
1409 ((_ . rest) (lp #'rest (cons "pw" slots))))))
1410
1411 (let ((rtd (make-id type-name type-name '-type)))
1412 (constructor rtd type-name fields
1413 #`(begin
1414 (define #,rtd
1415 (make-struct record-type-vtable 0
1416 '#,(make-layout)
1417 #,printer
1418 '#,type-name
1419 '#,(field-list fields)))
1420 (set-struct-vtable-name! #,rtd '#,type-name)))))
1421
1422 (syntax-case x ()
1423 ((_ type-name printer (field ...))
1424 (type #'type-name #'printer #'(field ...)))))))
1425
1426 ;; module-type
1427 ;;
1428 ;; A module is characterized by an obarray in which local symbols
1429 ;; are interned, a list of modules, "uses", from which non-local
1430 ;; bindings can be inherited, and an optional lazy-binder which
1431 ;; is a (CLOSURE module symbol) which, as a last resort, can provide
1432 ;; bindings that would otherwise not be found locally in the module.
1433 ;;
1434 ;; NOTE: If you change the set of fields or their order, you also need to
1435 ;; change the constants in libguile/modules.h.
1436 ;;
1437 ;; NOTE: The getter `module-eval-closure' is used in libguile/modules.c.
1438 ;; NOTE: The getter `module-transfomer' is defined libguile/modules.c.
1439 ;; NOTE: The getter `module-name' is defined later, due to boot reasons.
1440 ;; NOTE: The getter `module-public-interface' is used in libguile/modules.c.
1441 ;;
1442 (define-record-type module
1443 (lambda (obj port) (%print-module obj port))
1444 (obarray
1445 uses
1446 binder
1447 eval-closure
1448 (transformer #:no-getter)
1449 (name #:no-getter)
1450 kind
1451 duplicates-handlers
1452 (import-obarray #:no-setter)
1453 observers
1454 (weak-observers #:no-setter)
1455 version
1456 submodules
1457 submodule-binder
1458 public-interface
1459 filename)))
1460
1461
1462 ;; make-module &opt size uses binder
1463 ;;
1464 ;; Create a new module, perhaps with a particular size of obarray,
1465 ;; initial uses list, or binding procedure.
1466 ;;
1467 (define* (make-module #:optional (size 31) (uses '()) (binder #f))
1468 (define %default-import-size
1469 ;; Typical number of imported bindings actually used by a module.
1470 600)
1471
1472 (if (not (integer? size))
1473 (error "Illegal size to make-module." size))
1474 (if (not (and (list? uses)
1475 (and-map module? uses)))
1476 (error "Incorrect use list." uses))
1477 (if (and binder (not (procedure? binder)))
1478 (error
1479 "Lazy-binder expected to be a procedure or #f." binder))
1480
1481 (let ((module (module-constructor (make-hash-table size)
1482 uses binder #f macroexpand
1483 #f #f #f
1484 (make-hash-table %default-import-size)
1485 '()
1486 (make-weak-key-hash-table 31) #f
1487 (make-hash-table 7) #f #f #f)))
1488
1489 ;; We can't pass this as an argument to module-constructor,
1490 ;; because we need it to close over a pointer to the module
1491 ;; itself.
1492 (set-module-eval-closure! module (standard-eval-closure module))
1493
1494 module))
1495
1496
1497 \f
1498
1499 ;;; {Observer protocol}
1500 ;;;
1501
1502 (define (module-observe module proc)
1503 (set-module-observers! module (cons proc (module-observers module)))
1504 (cons module proc))
1505
1506 (define* (module-observe-weak module observer-id #:optional (proc observer-id))
1507 ;; Register PROC as an observer of MODULE under name OBSERVER-ID (which can
1508 ;; be any Scheme object). PROC is invoked and passed MODULE any time
1509 ;; MODULE is modified. PROC gets unregistered when OBSERVER-ID gets GC'd
1510 ;; (thus, it is never unregistered if OBSERVER-ID is an immediate value,
1511 ;; for instance).
1512
1513 ;; The two-argument version is kept for backward compatibility: when called
1514 ;; with two arguments, the observer gets unregistered when closure PROC
1515 ;; gets GC'd (making it impossible to use an anonymous lambda for PROC).
1516 (hashq-set! (module-weak-observers module) observer-id proc))
1517
1518 (define (module-unobserve token)
1519 (let ((module (car token))
1520 (id (cdr token)))
1521 (if (integer? id)
1522 (hash-remove! (module-weak-observers module) id)
1523 (set-module-observers! module (delq1! id (module-observers module)))))
1524 *unspecified*)
1525
1526 (define module-defer-observers #f)
1527 (define module-defer-observers-mutex (make-mutex 'recursive))
1528 (define module-defer-observers-table (make-hash-table))
1529
1530 (define (module-modified m)
1531 (if module-defer-observers
1532 (hash-set! module-defer-observers-table m #t)
1533 (module-call-observers m)))
1534
1535 ;;; This function can be used to delay calls to observers so that they
1536 ;;; can be called once only in the face of massive updating of modules.
1537 ;;;
1538 (define (call-with-deferred-observers thunk)
1539 (dynamic-wind
1540 (lambda ()
1541 (lock-mutex module-defer-observers-mutex)
1542 (set! module-defer-observers #t))
1543 thunk
1544 (lambda ()
1545 (set! module-defer-observers #f)
1546 (hash-for-each (lambda (m dummy)
1547 (module-call-observers m))
1548 module-defer-observers-table)
1549 (hash-clear! module-defer-observers-table)
1550 (unlock-mutex module-defer-observers-mutex))))
1551
1552 (define (module-call-observers m)
1553 (for-each (lambda (proc) (proc m)) (module-observers m))
1554
1555 ;; We assume that weak observers don't (un)register themselves as they are
1556 ;; called since this would preclude proper iteration over the hash table
1557 ;; elements.
1558 (hash-for-each (lambda (id proc) (proc m)) (module-weak-observers m)))
1559
1560 \f
1561
1562 ;;; {Module Searching in General}
1563 ;;;
1564 ;;; We sometimes want to look for properties of a symbol
1565 ;;; just within the obarray of one module. If the property
1566 ;;; holds, then it is said to hold ``locally'' as in, ``The symbol
1567 ;;; DISPLAY is locally rebound in the module `safe-guile'.''
1568 ;;;
1569 ;;;
1570 ;;; Other times, we want to test for a symbol property in the obarray
1571 ;;; of M and, if it is not found there, try each of the modules in the
1572 ;;; uses list of M. This is the normal way of testing for some
1573 ;;; property, so we state these properties without qualification as
1574 ;;; in: ``The symbol 'fnord is interned in module M because it is
1575 ;;; interned locally in module M2 which is a member of the uses list
1576 ;;; of M.''
1577 ;;;
1578
1579 ;; module-search fn m
1580 ;;
1581 ;; return the first non-#f result of FN applied to M and then to
1582 ;; the modules in the uses of m, and so on recursively. If all applications
1583 ;; return #f, then so does this function.
1584 ;;
1585 (define (module-search fn m v)
1586 (define (loop pos)
1587 (and (pair? pos)
1588 (or (module-search fn (car pos) v)
1589 (loop (cdr pos)))))
1590 (or (fn m v)
1591 (loop (module-uses m))))
1592
1593
1594 ;;; {Is a symbol bound in a module?}
1595 ;;;
1596 ;;; Symbol S in Module M is bound if S is interned in M and if the binding
1597 ;;; of S in M has been set to some well-defined value.
1598 ;;;
1599
1600 ;; module-locally-bound? module symbol
1601 ;;
1602 ;; Is a symbol bound (interned and defined) locally in a given module?
1603 ;;
1604 (define (module-locally-bound? m v)
1605 (let ((var (module-local-variable m v)))
1606 (and var
1607 (variable-bound? var))))
1608
1609 ;; module-bound? module symbol
1610 ;;
1611 ;; Is a symbol bound (interned and defined) anywhere in a given module
1612 ;; or its uses?
1613 ;;
1614 (define (module-bound? m v)
1615 (let ((var (module-variable m v)))
1616 (and var
1617 (variable-bound? var))))
1618
1619 ;;; {Is a symbol interned in a module?}
1620 ;;;
1621 ;;; Symbol S in Module M is interned if S occurs in
1622 ;;; of S in M has been set to some well-defined value.
1623 ;;;
1624 ;;; It is possible to intern a symbol in a module without providing
1625 ;;; an initial binding for the corresponding variable. This is done
1626 ;;; with:
1627 ;;; (module-add! module symbol (make-undefined-variable))
1628 ;;;
1629 ;;; In that case, the symbol is interned in the module, but not
1630 ;;; bound there. The unbound symbol shadows any binding for that
1631 ;;; symbol that might otherwise be inherited from a member of the uses list.
1632 ;;;
1633
1634 (define (module-obarray-get-handle ob key)
1635 ((if (symbol? key) hashq-get-handle hash-get-handle) ob key))
1636
1637 (define (module-obarray-ref ob key)
1638 ((if (symbol? key) hashq-ref hash-ref) ob key))
1639
1640 (define (module-obarray-set! ob key val)
1641 ((if (symbol? key) hashq-set! hash-set!) ob key val))
1642
1643 (define (module-obarray-remove! ob key)
1644 ((if (symbol? key) hashq-remove! hash-remove!) ob key))
1645
1646 ;; module-symbol-locally-interned? module symbol
1647 ;;
1648 ;; is a symbol interned (not neccessarily defined) locally in a given module
1649 ;; or its uses? Interned symbols shadow inherited bindings even if
1650 ;; they are not themselves bound to a defined value.
1651 ;;
1652 (define (module-symbol-locally-interned? m v)
1653 (not (not (module-obarray-get-handle (module-obarray m) v))))
1654
1655 ;; module-symbol-interned? module symbol
1656 ;;
1657 ;; is a symbol interned (not neccessarily defined) anywhere in a given module
1658 ;; or its uses? Interned symbols shadow inherited bindings even if
1659 ;; they are not themselves bound to a defined value.
1660 ;;
1661 (define (module-symbol-interned? m v)
1662 (module-search module-symbol-locally-interned? m v))
1663
1664
1665 ;;; {Mapping modules x symbols --> variables}
1666 ;;;
1667
1668 ;; module-local-variable module symbol
1669 ;; return the local variable associated with a MODULE and SYMBOL.
1670 ;;
1671 ;;; This function is very important. It is the only function that can
1672 ;;; return a variable from a module other than the mutators that store
1673 ;;; new variables in modules. Therefore, this function is the location
1674 ;;; of the "lazy binder" hack.
1675 ;;;
1676 ;;; If symbol is defined in MODULE, and if the definition binds symbol
1677 ;;; to a variable, return that variable object.
1678 ;;;
1679 ;;; If the symbols is not found at first, but the module has a lazy binder,
1680 ;;; then try the binder.
1681 ;;;
1682 ;;; If the symbol is not found at all, return #f.
1683 ;;;
1684 ;;; (This is now written in C, see `modules.c'.)
1685 ;;;
1686
1687 ;;; {Mapping modules x symbols --> bindings}
1688 ;;;
1689 ;;; These are similar to the mapping to variables, except that the
1690 ;;; variable is dereferenced.
1691 ;;;
1692
1693 ;; module-symbol-binding module symbol opt-value
1694 ;;
1695 ;; return the binding of a variable specified by name within
1696 ;; a given module, signalling an error if the variable is unbound.
1697 ;; If the OPT-VALUE is passed, then instead of signalling an error,
1698 ;; return OPT-VALUE.
1699 ;;
1700 (define (module-symbol-local-binding m v . opt-val)
1701 (let ((var (module-local-variable m v)))
1702 (if (and var (variable-bound? var))
1703 (variable-ref var)
1704 (if (not (null? opt-val))
1705 (car opt-val)
1706 (error "Locally unbound variable." v)))))
1707
1708 ;; module-symbol-binding module symbol opt-value
1709 ;;
1710 ;; return the binding of a variable specified by name within
1711 ;; a given module, signalling an error if the variable is unbound.
1712 ;; If the OPT-VALUE is passed, then instead of signalling an error,
1713 ;; return OPT-VALUE.
1714 ;;
1715 (define (module-symbol-binding m v . opt-val)
1716 (let ((var (module-variable m v)))
1717 (if (and var (variable-bound? var))
1718 (variable-ref var)
1719 (if (not (null? opt-val))
1720 (car opt-val)
1721 (error "Unbound variable." v)))))
1722
1723
1724 \f
1725
1726 ;;; {Adding Variables to Modules}
1727 ;;;
1728
1729 ;; module-make-local-var! module symbol
1730 ;;
1731 ;; ensure a variable for V in the local namespace of M.
1732 ;; If no variable was already there, then create a new and uninitialzied
1733 ;; variable.
1734 ;;
1735 ;; This function is used in modules.c.
1736 ;;
1737 (define (module-make-local-var! m v)
1738 (or (let ((b (module-obarray-ref (module-obarray m) v)))
1739 (and (variable? b)
1740 (begin
1741 ;; Mark as modified since this function is called when
1742 ;; the standard eval closure defines a binding
1743 (module-modified m)
1744 b)))
1745
1746 ;; Create a new local variable.
1747 (let ((local-var (make-undefined-variable)))
1748 (module-add! m v local-var)
1749 local-var)))
1750
1751 ;; module-ensure-local-variable! module symbol
1752 ;;
1753 ;; Ensure that there is a local variable in MODULE for SYMBOL. If
1754 ;; there is no binding for SYMBOL, create a new uninitialized
1755 ;; variable. Return the local variable.
1756 ;;
1757 (define (module-ensure-local-variable! module symbol)
1758 (or (module-local-variable module symbol)
1759 (let ((var (make-undefined-variable)))
1760 (module-add! module symbol var)
1761 var)))
1762
1763 ;; module-add! module symbol var
1764 ;;
1765 ;; ensure a particular variable for V in the local namespace of M.
1766 ;;
1767 (define (module-add! m v var)
1768 (if (not (variable? var))
1769 (error "Bad variable to module-add!" var))
1770 (module-obarray-set! (module-obarray m) v var)
1771 (module-modified m))
1772
1773 ;; module-remove!
1774 ;;
1775 ;; make sure that a symbol is undefined in the local namespace of M.
1776 ;;
1777 (define (module-remove! m v)
1778 (module-obarray-remove! (module-obarray m) v)
1779 (module-modified m))
1780
1781 (define (module-clear! m)
1782 (hash-clear! (module-obarray m))
1783 (module-modified m))
1784
1785 ;; MODULE-FOR-EACH -- exported
1786 ;;
1787 ;; Call PROC on each symbol in MODULE, with arguments of (SYMBOL VARIABLE).
1788 ;;
1789 (define (module-for-each proc module)
1790 (hash-for-each proc (module-obarray module)))
1791
1792 (define (module-map proc module)
1793 (hash-map->list proc (module-obarray module)))
1794
1795 ;; Submodules
1796 ;;
1797 ;; Modules exist in a separate namespace from values, because you generally do
1798 ;; not want the name of a submodule, which you might not even use, to collide
1799 ;; with local variables that happen to be named the same as the submodule.
1800 ;;
1801 (define (module-ref-submodule module name)
1802 (or (hashq-ref (module-submodules module) name)
1803 (and (module-submodule-binder module)
1804 ((module-submodule-binder module) module name))))
1805
1806 (define (module-define-submodule! module name submodule)
1807 (hashq-set! (module-submodules module) name submodule))
1808
1809 ;; It used to be, however, that module names were also present in the
1810 ;; value namespace. When we enable deprecated code, we preserve this
1811 ;; legacy behavior.
1812 ;;
1813 ;; These shims are defined here instead of in deprecated.scm because we
1814 ;; need their definitions before loading other modules.
1815 ;;
1816 (begin-deprecated
1817 (define (module-ref-submodule module name)
1818 (or (hashq-ref (module-submodules module) name)
1819 (and (module-submodule-binder module)
1820 ((module-submodule-binder module) module name))
1821 (let ((var (module-local-variable module name)))
1822 (and var (variable-bound? var) (module? (variable-ref var))
1823 (begin
1824 (warn "module" module "not in submodules table")
1825 (variable-ref var))))))
1826
1827 (define (module-define-submodule! module name submodule)
1828 (let ((var (module-local-variable module name)))
1829 (if (and var
1830 (or (not (variable-bound? var))
1831 (not (module? (variable-ref var)))))
1832 (warn "defining module" module ": not overriding local definition" var)
1833 (module-define! module name submodule)))
1834 (hashq-set! (module-submodules module) name submodule)))
1835
1836 \f
1837
1838 ;;; {Module-based Loading}
1839 ;;;
1840
1841 (define (save-module-excursion thunk)
1842 (let ((inner-module (current-module))
1843 (outer-module #f))
1844 (dynamic-wind (lambda ()
1845 (set! outer-module (current-module))
1846 (set-current-module inner-module)
1847 (set! inner-module #f))
1848 thunk
1849 (lambda ()
1850 (set! inner-module (current-module))
1851 (set-current-module outer-module)
1852 (set! outer-module #f)))))
1853
1854 (define basic-load load)
1855
1856 (define* (load-module filename #:optional reader)
1857 (save-module-excursion
1858 (lambda ()
1859 (let ((oldname (and (current-load-port)
1860 (port-filename (current-load-port)))))
1861 (basic-load (if (and oldname
1862 (> (string-length filename) 0)
1863 (not (char=? (string-ref filename 0) #\/))
1864 (not (string=? (dirname oldname) ".")))
1865 (string-append (dirname oldname) "/" filename)
1866 filename)
1867 reader)))))
1868
1869
1870 \f
1871
1872 ;;; {MODULE-REF -- exported}
1873 ;;;
1874
1875 ;; Returns the value of a variable called NAME in MODULE or any of its
1876 ;; used modules. If there is no such variable, then if the optional third
1877 ;; argument DEFAULT is present, it is returned; otherwise an error is signaled.
1878 ;;
1879 (define (module-ref module name . rest)
1880 (let ((variable (module-variable module name)))
1881 (if (and variable (variable-bound? variable))
1882 (variable-ref variable)
1883 (if (null? rest)
1884 (error "No variable named" name 'in module)
1885 (car rest) ; default value
1886 ))))
1887
1888 ;; MODULE-SET! -- exported
1889 ;;
1890 ;; Sets the variable called NAME in MODULE (or in a module that MODULE uses)
1891 ;; to VALUE; if there is no such variable, an error is signaled.
1892 ;;
1893 (define (module-set! module name value)
1894 (let ((variable (module-variable module name)))
1895 (if variable
1896 (variable-set! variable value)
1897 (error "No variable named" name 'in module))))
1898
1899 ;; MODULE-DEFINE! -- exported
1900 ;;
1901 ;; Sets the variable called NAME in MODULE to VALUE; if there is no such
1902 ;; variable, it is added first.
1903 ;;
1904 (define (module-define! module name value)
1905 (let ((variable (module-local-variable module name)))
1906 (if variable
1907 (begin
1908 (variable-set! variable value)
1909 (module-modified module))
1910 (let ((variable (make-variable value)))
1911 (module-add! module name variable)))))
1912
1913 ;; MODULE-DEFINED? -- exported
1914 ;;
1915 ;; Return #t iff NAME is defined in MODULE (or in a module that MODULE
1916 ;; uses)
1917 ;;
1918 (define (module-defined? module name)
1919 (let ((variable (module-variable module name)))
1920 (and variable (variable-bound? variable))))
1921
1922 ;; MODULE-USE! module interface
1923 ;;
1924 ;; Add INTERFACE to the list of interfaces used by MODULE.
1925 ;;
1926 (define (module-use! module interface)
1927 (if (not (or (eq? module interface)
1928 (memq interface (module-uses module))))
1929 (begin
1930 ;; Newly used modules must be appended rather than consed, so that
1931 ;; `module-variable' traverses the use list starting from the first
1932 ;; used module.
1933 (set-module-uses! module
1934 (append (filter (lambda (m)
1935 (not
1936 (equal? (module-name m)
1937 (module-name interface))))
1938 (module-uses module))
1939 (list interface)))
1940 (hash-clear! (module-import-obarray module))
1941 (module-modified module))))
1942
1943 ;; MODULE-USE-INTERFACES! module interfaces
1944 ;;
1945 ;; Same as MODULE-USE! but add multiple interfaces and check for duplicates
1946 ;;
1947 (define (module-use-interfaces! module interfaces)
1948 (set-module-uses! module
1949 (append (module-uses module) interfaces))
1950 (hash-clear! (module-import-obarray module))
1951 (module-modified module))
1952
1953 \f
1954
1955 ;;; {Recursive Namespaces}
1956 ;;;
1957 ;;; A hierarchical namespace emerges if we consider some module to be
1958 ;;; root, and submodules of that module to be nested namespaces.
1959 ;;;
1960 ;;; The routines here manage variable names in hierarchical namespace.
1961 ;;; Each variable name is a list of elements, looked up in successively nested
1962 ;;; modules.
1963 ;;;
1964 ;;; (nested-ref some-root-module '(foo bar baz))
1965 ;;; => <value of a variable named baz in the submodule bar of
1966 ;;; the submodule foo of some-root-module>
1967 ;;;
1968 ;;;
1969 ;;; There are:
1970 ;;;
1971 ;;; ;; a-root is a module
1972 ;;; ;; name is a list of symbols
1973 ;;;
1974 ;;; nested-ref a-root name
1975 ;;; nested-set! a-root name val
1976 ;;; nested-define! a-root name val
1977 ;;; nested-remove! a-root name
1978 ;;;
1979 ;;; These functions manipulate values in namespaces. For referencing the
1980 ;;; namespaces themselves, use the following:
1981 ;;;
1982 ;;; nested-ref-module a-root name
1983 ;;; nested-define-module! a-root name mod
1984 ;;;
1985 ;;; (current-module) is a natural choice for a root so for convenience there are
1986 ;;; also:
1987 ;;;
1988 ;;; local-ref name == nested-ref (current-module) name
1989 ;;; local-set! name val == nested-set! (current-module) name val
1990 ;;; local-define name val == nested-define! (current-module) name val
1991 ;;; local-remove name == nested-remove! (current-module) name
1992 ;;; local-ref-module name == nested-ref-module (current-module) name
1993 ;;; local-define-module! name m == nested-define-module! (current-module) name m
1994 ;;;
1995
1996
1997 (define (nested-ref root names)
1998 (if (null? names)
1999 root
2000 (let loop ((cur root)
2001 (head (car names))
2002 (tail (cdr names)))
2003 (if (null? tail)
2004 (module-ref cur head #f)
2005 (let ((cur (module-ref-submodule cur head)))
2006 (and cur
2007 (loop cur (car tail) (cdr tail))))))))
2008
2009 (define (nested-set! root names val)
2010 (let loop ((cur root)
2011 (head (car names))
2012 (tail (cdr names)))
2013 (if (null? tail)
2014 (module-set! cur head val)
2015 (let ((cur (module-ref-submodule cur head)))
2016 (if (not cur)
2017 (error "failed to resolve module" names)
2018 (loop cur (car tail) (cdr tail)))))))
2019
2020 (define (nested-define! root names val)
2021 (let loop ((cur root)
2022 (head (car names))
2023 (tail (cdr names)))
2024 (if (null? tail)
2025 (module-define! cur head val)
2026 (let ((cur (module-ref-submodule cur head)))
2027 (if (not cur)
2028 (error "failed to resolve module" names)
2029 (loop cur (car tail) (cdr tail)))))))
2030
2031 (define (nested-remove! root names)
2032 (let loop ((cur root)
2033 (head (car names))
2034 (tail (cdr names)))
2035 (if (null? tail)
2036 (module-remove! cur head)
2037 (let ((cur (module-ref-submodule cur head)))
2038 (if (not cur)
2039 (error "failed to resolve module" names)
2040 (loop cur (car tail) (cdr tail)))))))
2041
2042
2043 (define (nested-ref-module root names)
2044 (let loop ((cur root)
2045 (names names))
2046 (if (null? names)
2047 cur
2048 (let ((cur (module-ref-submodule cur (car names))))
2049 (and cur
2050 (loop cur (cdr names)))))))
2051
2052 (define (nested-define-module! root names module)
2053 (if (null? names)
2054 (error "can't redefine root module" root module)
2055 (let loop ((cur root)
2056 (head (car names))
2057 (tail (cdr names)))
2058 (if (null? tail)
2059 (module-define-submodule! cur head module)
2060 (let ((cur (or (module-ref-submodule cur head)
2061 (let ((m (make-module 31)))
2062 (set-module-kind! m 'directory)
2063 (set-module-name! m (append (module-name cur)
2064 (list head)))
2065 (module-define-submodule! cur head m)
2066 m))))
2067 (loop cur (car tail) (cdr tail)))))))
2068
2069
2070 (define (local-ref names)
2071 (nested-ref (current-module) names))
2072
2073 (define (local-set! names val)
2074 (nested-set! (current-module) names val))
2075
2076 (define (local-define names val)
2077 (nested-define! (current-module) names val))
2078
2079 (define (local-remove names)
2080 (nested-remove! (current-module) names))
2081
2082 (define (local-ref-module names)
2083 (nested-ref-module (current-module) names))
2084
2085 (define (local-define-module names mod)
2086 (nested-define-module! (current-module) names mod))
2087
2088
2089
2090 \f
2091
2092 ;;; {The (guile) module}
2093 ;;;
2094 ;;; The standard module, which has the core Guile bindings. Also called the
2095 ;;; "root module", as it is imported by many other modules, but it is not
2096 ;;; necessarily the root of anything; and indeed, the module named '() might be
2097 ;;; better thought of as a root.
2098 ;;;
2099
2100 (define (set-system-module! m s)
2101 (set-procedure-property! (module-eval-closure m) 'system-module s))
2102
2103 ;; The root module uses the pre-modules-obarray as its obarray. This
2104 ;; special obarray accumulates all bindings that have been established
2105 ;; before the module system is fully booted.
2106 ;;
2107 ;; (The obarray continues to be used by code that has been closed over
2108 ;; before the module system has been booted.)
2109 ;;
2110 (define the-root-module
2111 (let ((m (make-module 0)))
2112 (set-module-obarray! m (%get-pre-modules-obarray))
2113 (set-module-name! m '(guile))
2114 (set-system-module! m #t)
2115 m))
2116
2117 ;; The root interface is a module that uses the same obarray as the
2118 ;; root module. It does not allow new definitions, tho.
2119 ;;
2120 (define the-scm-module
2121 (let ((m (make-module 0)))
2122 (set-module-obarray! m (%get-pre-modules-obarray))
2123 (set-module-eval-closure! m (standard-interface-eval-closure m))
2124 (set-module-name! m '(guile))
2125 (set-module-kind! m 'interface)
2126 (set-system-module! m #t)
2127 m))
2128
2129 (set-module-public-interface! the-root-module the-scm-module)
2130
2131 \f
2132
2133 ;; Now that we have a root module, even though modules aren't fully booted,
2134 ;; expand the definition of resolve-module.
2135 ;;
2136 (define (resolve-module name . args)
2137 (if (equal? name '(guile))
2138 the-root-module
2139 (error "unexpected module to resolve during module boot" name)))
2140
2141 ;; Cheat. These bindings are needed by modules.c, but we don't want
2142 ;; to move their real definition here because that would be unnatural.
2143 ;;
2144 (define process-define-module #f)
2145 (define process-use-modules #f)
2146 (define module-export! #f)
2147 (define default-duplicate-binding-procedures #f)
2148
2149 ;; This boots the module system. All bindings needed by modules.c
2150 ;; must have been defined by now.
2151 ;;
2152 (set-current-module the-root-module)
2153
2154
2155 \f
2156
2157 ;; Now that modules are booted, give module-name its final definition.
2158 ;;
2159 (define module-name
2160 (let ((accessor (record-accessor module-type 'name)))
2161 (lambda (mod)
2162 (or (accessor mod)
2163 (let ((name (list (gensym))))
2164 ;; Name MOD and bind it in the module root so that it's visible to
2165 ;; `resolve-module'. This is important as `psyntax' stores module
2166 ;; names and relies on being able to `resolve-module' them.
2167 (set-module-name! mod name)
2168 (nested-define-module! (resolve-module '() #f) name mod)
2169 (accessor mod))))))
2170
2171 (define (make-modules-in module name)
2172 (or (nested-ref-module module name)
2173 (let ((m (make-module 31)))
2174 (set-module-kind! m 'directory)
2175 (set-module-name! m (append (module-name module) name))
2176 (nested-define-module! module name m)
2177 m)))
2178
2179 (define (beautify-user-module! module)
2180 (let ((interface (module-public-interface module)))
2181 (if (or (not interface)
2182 (eq? interface module))
2183 (let ((interface (make-module 31)))
2184 (set-module-name! interface (module-name module))
2185 (set-module-version! interface (module-version module))
2186 (set-module-kind! interface 'interface)
2187 (set-module-public-interface! module interface))))
2188 (if (and (not (memq the-scm-module (module-uses module)))
2189 (not (eq? module the-root-module)))
2190 ;; Import the default set of bindings (from the SCM module) in MODULE.
2191 (module-use! module the-scm-module)))
2192
2193 (define (version-matches? version-ref target)
2194 (define (sub-versions-match? v-refs t)
2195 (define (sub-version-matches? v-ref t)
2196 (let ((matches? (lambda (v) (sub-version-matches? v t))))
2197 (cond
2198 ((number? v-ref) (eqv? v-ref t))
2199 ((list? v-ref)
2200 (case (car v-ref)
2201 ((>=) (>= t (cadr v-ref)))
2202 ((<=) (<= t (cadr v-ref)))
2203 ((and) (and-map matches? (cdr v-ref)))
2204 ((or) (or-map matches? (cdr v-ref)))
2205 ((not) (not (matches? (cadr v-ref))))
2206 (else (error "Invalid sub-version reference" v-ref))))
2207 (else (error "Invalid sub-version reference" v-ref)))))
2208 (or (null? v-refs)
2209 (and (not (null? t))
2210 (sub-version-matches? (car v-refs) (car t))
2211 (sub-versions-match? (cdr v-refs) (cdr t)))))
2212
2213 (let ((matches? (lambda (v) (version-matches? v target))))
2214 (or (null? version-ref)
2215 (case (car version-ref)
2216 ((and) (and-map matches? (cdr version-ref)))
2217 ((or) (or-map matches? (cdr version-ref)))
2218 ((not) (not (matches? (cadr version-ref))))
2219 (else (sub-versions-match? version-ref target))))))
2220
2221 (define (make-fresh-user-module)
2222 (let ((m (make-module)))
2223 (beautify-user-module! m)
2224 m))
2225
2226 ;; NOTE: This binding is used in libguile/modules.c.
2227 ;;
2228 (define resolve-module
2229 (let ((root (make-module)))
2230 (set-module-name! root '())
2231 ;; Define the-root-module as '(guile).
2232 (module-define-submodule! root 'guile the-root-module)
2233
2234 (lambda* (name #:optional (autoload #t) (version #f) #:key (ensure #t))
2235 (let ((already (nested-ref-module root name)))
2236 (cond
2237 ((and already
2238 (or (not autoload) (module-public-interface already)))
2239 ;; A hit, a palpable hit.
2240 (if (and version
2241 (not (version-matches? version (module-version already))))
2242 (error "incompatible module version already loaded" name))
2243 already)
2244 (autoload
2245 ;; Try to autoload the module, and recurse.
2246 (try-load-module name version)
2247 (resolve-module name #f #:ensure ensure))
2248 (else
2249 ;; No module found (or if one was, it had no public interface), and
2250 ;; we're not autoloading. Make an empty module if #:ensure is true.
2251 (or already
2252 (and ensure
2253 (make-modules-in root name)))))))))
2254
2255
2256 (define (try-load-module name version)
2257 (try-module-autoload name version))
2258
2259 (define (purify-module! module)
2260 "Removes bindings in MODULE which are inherited from the (guile) module."
2261 (let ((use-list (module-uses module)))
2262 (if (and (pair? use-list)
2263 (eq? (car (last-pair use-list)) the-scm-module))
2264 (set-module-uses! module (reverse (cdr (reverse use-list)))))))
2265
2266 ;; Return a module that is an interface to the module designated by
2267 ;; NAME.
2268 ;;
2269 ;; `resolve-interface' takes four keyword arguments:
2270 ;;
2271 ;; #:select SELECTION
2272 ;;
2273 ;; SELECTION is a list of binding-specs to be imported; A binding-spec
2274 ;; is either a symbol or a pair of symbols (ORIG . SEEN), where ORIG
2275 ;; is the name in the used module and SEEN is the name in the using
2276 ;; module. Note that SEEN is also passed through RENAMER, below. The
2277 ;; default is to select all bindings. If you specify no selection but
2278 ;; a renamer, only the bindings that already exist in the used module
2279 ;; are made available in the interface. Bindings that are added later
2280 ;; are not picked up.
2281 ;;
2282 ;; #:hide BINDINGS
2283 ;;
2284 ;; BINDINGS is a list of bindings which should not be imported.
2285 ;;
2286 ;; #:prefix PREFIX
2287 ;;
2288 ;; PREFIX is a symbol that will be appended to each exported name.
2289 ;; The default is to not perform any renaming.
2290 ;;
2291 ;; #:renamer RENAMER
2292 ;;
2293 ;; RENAMER is a procedure that takes a symbol and returns its new
2294 ;; name. The default is not perform any renaming.
2295 ;;
2296 ;; Signal "no code for module" error if module name is not resolvable
2297 ;; or its public interface is not available. Signal "no binding"
2298 ;; error if selected binding does not exist in the used module.
2299 ;;
2300 (define* (resolve-interface name #:key
2301 (select #f)
2302 (hide '())
2303 (prefix #f)
2304 (renamer (if prefix
2305 (symbol-prefix-proc prefix)
2306 identity))
2307 version)
2308 (let* ((module (resolve-module name #t version #:ensure #f))
2309 (public-i (and module (module-public-interface module))))
2310 (and (or (not module) (not public-i))
2311 (error "no code for module" name))
2312 (if (and (not select) (null? hide) (eq? renamer identity))
2313 public-i
2314 (let ((selection (or select (module-map (lambda (sym var) sym)
2315 public-i)))
2316 (custom-i (make-module 31)))
2317 (set-module-kind! custom-i 'custom-interface)
2318 (set-module-name! custom-i name)
2319 ;; XXX - should use a lazy binder so that changes to the
2320 ;; used module are picked up automatically.
2321 (for-each (lambda (bspec)
2322 (let* ((direct? (symbol? bspec))
2323 (orig (if direct? bspec (car bspec)))
2324 (seen (if direct? bspec (cdr bspec)))
2325 (var (or (module-local-variable public-i orig)
2326 (module-local-variable module orig)
2327 (error
2328 ;; fixme: format manually for now
2329 (simple-format
2330 #f "no binding `~A' in module ~A"
2331 orig name)))))
2332 (if (memq orig hide)
2333 (set! hide (delq! orig hide))
2334 (module-add! custom-i
2335 (renamer seen)
2336 var))))
2337 selection)
2338 ;; Check that we are not hiding bindings which don't exist
2339 (for-each (lambda (binding)
2340 (if (not (module-local-variable public-i binding))
2341 (error
2342 (simple-format
2343 #f "no binding `~A' to hide in module ~A"
2344 binding name))))
2345 hide)
2346 custom-i))))
2347
2348 (define (symbol-prefix-proc prefix)
2349 (lambda (symbol)
2350 (symbol-append prefix symbol)))
2351
2352 ;; This function is called from "modules.c". If you change it, be
2353 ;; sure to update "modules.c" as well.
2354
2355 (define (process-define-module args)
2356 (let* ((module-id (car args))
2357 (module (resolve-module module-id #f))
2358 (kws (cdr args))
2359 (unrecognized (lambda (arg)
2360 (error "unrecognized define-module argument" arg))))
2361 (beautify-user-module! module)
2362 (let loop ((kws kws)
2363 (reversed-interfaces '())
2364 (exports '())
2365 (re-exports '())
2366 (replacements '())
2367 (autoloads '()))
2368
2369 (if (null? kws)
2370 (call-with-deferred-observers
2371 (lambda ()
2372 (module-use-interfaces! module (reverse reversed-interfaces))
2373 (module-export! module exports)
2374 (module-replace! module replacements)
2375 (module-re-export! module re-exports)
2376 (if (not (null? autoloads))
2377 (apply module-autoload! module autoloads))))
2378 (case (car kws)
2379 ((#:use-module #:use-syntax)
2380 (or (pair? (cdr kws))
2381 (unrecognized kws))
2382 (cond
2383 ((equal? (caadr kws) '(ice-9 syncase))
2384 (issue-deprecation-warning
2385 "(ice-9 syncase) is deprecated. Support for syntax-case is now in Guile core.")
2386 (loop (cddr kws)
2387 reversed-interfaces
2388 exports
2389 re-exports
2390 replacements
2391 autoloads))
2392 (else
2393 (let* ((interface-args (cadr kws))
2394 (interface (apply resolve-interface interface-args)))
2395 (and (eq? (car kws) #:use-syntax)
2396 (or (symbol? (caar interface-args))
2397 (error "invalid module name for use-syntax"
2398 (car interface-args)))
2399 (set-module-transformer!
2400 module
2401 (module-ref interface
2402 (car (last-pair (car interface-args)))
2403 #f)))
2404 (loop (cddr kws)
2405 (cons interface reversed-interfaces)
2406 exports
2407 re-exports
2408 replacements
2409 autoloads)))))
2410 ((#:autoload)
2411 (or (and (pair? (cdr kws)) (pair? (cddr kws)))
2412 (unrecognized kws))
2413 (loop (cdddr kws)
2414 reversed-interfaces
2415 exports
2416 re-exports
2417 replacements
2418 (let ((name (cadr kws))
2419 (bindings (caddr kws)))
2420 (cons* name bindings autoloads))))
2421 ((#:no-backtrace)
2422 (set-system-module! module #t)
2423 (loop (cdr kws) reversed-interfaces exports re-exports
2424 replacements autoloads))
2425 ((#:pure)
2426 (purify-module! module)
2427 (loop (cdr kws) reversed-interfaces exports re-exports
2428 replacements autoloads))
2429 ((#:version)
2430 (or (pair? (cdr kws))
2431 (unrecognized kws))
2432 (let ((version (cadr kws)))
2433 (set-module-version! module version)
2434 (set-module-version! (module-public-interface module) version))
2435 (loop (cddr kws) reversed-interfaces exports re-exports
2436 replacements autoloads))
2437 ((#:duplicates)
2438 (if (not (pair? (cdr kws)))
2439 (unrecognized kws))
2440 (set-module-duplicates-handlers!
2441 module
2442 (lookup-duplicates-handlers (cadr kws)))
2443 (loop (cddr kws) reversed-interfaces exports re-exports
2444 replacements autoloads))
2445 ((#:export #:export-syntax)
2446 (or (pair? (cdr kws))
2447 (unrecognized kws))
2448 (loop (cddr kws)
2449 reversed-interfaces
2450 (append (cadr kws) exports)
2451 re-exports
2452 replacements
2453 autoloads))
2454 ((#:re-export #:re-export-syntax)
2455 (or (pair? (cdr kws))
2456 (unrecognized kws))
2457 (loop (cddr kws)
2458 reversed-interfaces
2459 exports
2460 (append (cadr kws) re-exports)
2461 replacements
2462 autoloads))
2463 ((#:replace #:replace-syntax)
2464 (or (pair? (cdr kws))
2465 (unrecognized kws))
2466 (loop (cddr kws)
2467 reversed-interfaces
2468 exports
2469 re-exports
2470 (append (cadr kws) replacements)
2471 autoloads))
2472 ((#:filename)
2473 (or (pair? (cdr kws))
2474 (unrecognized kws))
2475 (set-module-filename! module (cadr kws))
2476 (loop (cddr kws)
2477 reversed-interfaces
2478 exports
2479 re-exports
2480 replacements
2481 autoloads))
2482 (else
2483 (unrecognized kws)))))
2484 (run-hook module-defined-hook module)
2485 module))
2486
2487 ;; `module-defined-hook' is a hook that is run whenever a new module
2488 ;; is defined. Its members are called with one argument, the new
2489 ;; module.
2490 (define module-defined-hook (make-hook 1))
2491
2492 \f
2493
2494 ;;; {Autoload}
2495 ;;;
2496
2497 (define (make-autoload-interface module name bindings)
2498 (let ((b (lambda (a sym definep)
2499 (and (memq sym bindings)
2500 (let ((i (module-public-interface (resolve-module name))))
2501 (if (not i)
2502 (error "missing interface for module" name))
2503 (let ((autoload (memq a (module-uses module))))
2504 ;; Replace autoload-interface with actual interface if
2505 ;; that has not happened yet.
2506 (if (pair? autoload)
2507 (set-car! autoload i)))
2508 (module-local-variable i sym))))))
2509 (module-constructor (make-hash-table 0) '() b #f #f name 'autoload #f
2510 (make-hash-table 0) '() (make-weak-value-hash-table 31) #f
2511 (make-hash-table 0) #f #f #f)))
2512
2513 (define (module-autoload! module . args)
2514 "Have @var{module} automatically load the module named @var{name} when one
2515 of the symbols listed in @var{bindings} is looked up. @var{args} should be a
2516 list of module-name/binding-list pairs, e.g., as in @code{(module-autoload!
2517 module '(ice-9 q) '(make-q q-length))}."
2518 (let loop ((args args))
2519 (cond ((null? args)
2520 #t)
2521 ((null? (cdr args))
2522 (error "invalid name+binding autoload list" args))
2523 (else
2524 (let ((name (car args))
2525 (bindings (cadr args)))
2526 (module-use! module (make-autoload-interface module
2527 name bindings))
2528 (loop (cddr args)))))))
2529
2530
2531 \f
2532
2533 ;;; {Autoloading modules}
2534 ;;;
2535
2536 (define autoloads-in-progress '())
2537
2538 ;; This function is called from "modules.c". If you change it, be
2539 ;; sure to update "modules.c" as well.
2540
2541 (define* (try-module-autoload module-name #:optional version)
2542 (let* ((reverse-name (reverse module-name))
2543 (name (symbol->string (car reverse-name)))
2544 (dir-hint-module-name (reverse (cdr reverse-name)))
2545 (dir-hint (apply string-append
2546 (map (lambda (elt)
2547 (string-append (symbol->string elt) "/"))
2548 dir-hint-module-name))))
2549 (resolve-module dir-hint-module-name #f)
2550 (and (not (autoload-done-or-in-progress? dir-hint name))
2551 (let ((didit #f))
2552 (dynamic-wind
2553 (lambda () (autoload-in-progress! dir-hint name))
2554 (lambda ()
2555 (with-fluids ((current-reader #f))
2556 (save-module-excursion
2557 (lambda ()
2558 ;; The initial environment when loading a module is a fresh
2559 ;; user module.
2560 (set-current-module (make-fresh-user-module))
2561 ;; Here we could allow some other search strategy (other than
2562 ;; primitive-load-path), for example using versions encoded
2563 ;; into the file system -- but then we would have to figure
2564 ;; out how to locate the compiled file, do autocompilation,
2565 ;; etc. Punt for now, and don't use versions when locating
2566 ;; the file.
2567 (primitive-load-path (in-vicinity dir-hint name) #f)
2568 (set! didit #t)))))
2569 (lambda () (set-autoloaded! dir-hint name didit)))
2570 didit))))
2571
2572 \f
2573
2574 ;;; {Dynamic linking of modules}
2575 ;;;
2576
2577 (define autoloads-done '((guile . guile)))
2578
2579 (define (autoload-done-or-in-progress? p m)
2580 (let ((n (cons p m)))
2581 (->bool (or (member n autoloads-done)
2582 (member n autoloads-in-progress)))))
2583
2584 (define (autoload-done! p m)
2585 (let ((n (cons p m)))
2586 (set! autoloads-in-progress
2587 (delete! n autoloads-in-progress))
2588 (or (member n autoloads-done)
2589 (set! autoloads-done (cons n autoloads-done)))))
2590
2591 (define (autoload-in-progress! p m)
2592 (let ((n (cons p m)))
2593 (set! autoloads-done
2594 (delete! n autoloads-done))
2595 (set! autoloads-in-progress (cons n autoloads-in-progress))))
2596
2597 (define (set-autoloaded! p m done?)
2598 (if done?
2599 (autoload-done! p m)
2600 (let ((n (cons p m)))
2601 (set! autoloads-done (delete! n autoloads-done))
2602 (set! autoloads-in-progress (delete! n autoloads-in-progress)))))
2603
2604 \f
2605
2606 ;;; {Run-time options}
2607 ;;;
2608
2609 (define-syntax define-option-interface
2610 (syntax-rules ()
2611 ((_ (interface (options enable disable) (option-set!)))
2612 (begin
2613 (define options
2614 (case-lambda
2615 (() (interface))
2616 ((arg)
2617 (if (list? arg)
2618 (begin (interface arg) (interface))
2619 (for-each
2620 (lambda (option)
2621 (apply (lambda (name value documentation)
2622 (display name)
2623 (if (< (string-length (symbol->string name)) 8)
2624 (display #\tab))
2625 (display #\tab)
2626 (display value)
2627 (display #\tab)
2628 (display documentation)
2629 (newline))
2630 option))
2631 (interface #t))))))
2632 (define (enable . flags)
2633 (interface (append flags (interface)))
2634 (interface))
2635 (define (disable . flags)
2636 (let ((options (interface)))
2637 (for-each (lambda (flag) (set! options (delq! flag options)))
2638 flags)
2639 (interface options)
2640 (interface)))
2641 (define-syntax option-set!
2642 (syntax-rules ()
2643 ((_ opt val)
2644 (options (append (options) (list 'opt val))))))))))
2645
2646 (define-option-interface
2647 (debug-options-interface
2648 (debug-options debug-enable debug-disable)
2649 (debug-set!)))
2650
2651 (define-option-interface
2652 (read-options-interface
2653 (read-options read-enable read-disable)
2654 (read-set!)))
2655
2656 (define-option-interface
2657 (print-options-interface
2658 (print-options print-enable print-disable)
2659 (print-set!)))
2660
2661 \f
2662
2663 ;;; {The Unspecified Value}
2664 ;;;
2665 ;;; Currently Guile represents unspecified values via one particular value,
2666 ;;; which may be obtained by evaluating (if #f #f). It would be nice in the
2667 ;;; future if we could replace this with a return of 0 values, though.
2668 ;;;
2669
2670 (define-syntax *unspecified*
2671 (identifier-syntax (if #f #f)))
2672
2673 (define (unspecified? v) (eq? v *unspecified*))
2674
2675
2676 \f
2677
2678 ;;; {Running Repls}
2679 ;;;
2680
2681 (define *repl-stack* (make-fluid))
2682
2683 ;; Programs can call `batch-mode?' to see if they are running as part of a
2684 ;; script or if they are running interactively. REPL implementations ensure that
2685 ;; `batch-mode?' returns #f during their extent.
2686 ;;
2687 (define (batch-mode?)
2688 (null? (or (fluid-ref *repl-stack*) '())))
2689
2690 ;; Programs can re-enter batch mode, for example after a fork, by calling
2691 ;; `ensure-batch-mode!'. It's not a great interface, though; it would be better
2692 ;; to abort to the outermost prompt, and call a thunk there.
2693 ;;
2694 (define (ensure-batch-mode!)
2695 (set! batch-mode? (lambda () #t)))
2696
2697 (define (quit . args)
2698 (apply throw 'quit args))
2699
2700 (define exit quit)
2701
2702 (define (gc-run-time)
2703 (cdr (assq 'gc-time-taken (gc-stats))))
2704
2705 (define abort-hook (make-hook))
2706 (define before-error-hook (make-hook))
2707 (define after-error-hook (make-hook))
2708 (define before-backtrace-hook (make-hook))
2709 (define after-backtrace-hook (make-hook))
2710
2711 (define before-read-hook (make-hook))
2712 (define after-read-hook (make-hook))
2713 (define before-eval-hook (make-hook 1))
2714 (define after-eval-hook (make-hook 1))
2715 (define before-print-hook (make-hook 1))
2716 (define after-print-hook (make-hook 1))
2717
2718 ;;; This hook is run at the very end of an interactive session.
2719 ;;;
2720 (define exit-hook (make-hook))
2721
2722 ;;; The default repl-reader function. We may override this if we've
2723 ;;; the readline library.
2724 (define repl-reader
2725 (lambda* (prompt #:optional (reader (fluid-ref current-reader)))
2726 (if (not (char-ready?))
2727 (display (if (string? prompt) prompt (prompt))))
2728 (force-output)
2729 (run-hook before-read-hook)
2730 ((or reader read) (current-input-port))))
2731
2732
2733 \f
2734
2735 ;;; {IOTA functions: generating lists of numbers}
2736 ;;;
2737
2738 (define (iota n)
2739 (let loop ((count (1- n)) (result '()))
2740 (if (< count 0) result
2741 (loop (1- count) (cons count result)))))
2742
2743 \f
2744
2745 ;;; {While}
2746 ;;;
2747 ;;; with `continue' and `break'.
2748 ;;;
2749
2750 ;; The inliner will remove the prompts at compile-time if it finds that
2751 ;; `continue' or `break' are not used.
2752 ;;
2753 (define-syntax while
2754 (lambda (x)
2755 (syntax-case x ()
2756 ((while cond body ...)
2757 #`(let ((break-tag (make-prompt-tag "break"))
2758 (continue-tag (make-prompt-tag "continue")))
2759 (call-with-prompt
2760 break-tag
2761 (lambda ()
2762 (define-syntax #,(datum->syntax #'while 'break)
2763 (lambda (x)
2764 (syntax-case x ()
2765 ((_)
2766 #'(abort-to-prompt break-tag))
2767 ((_ . args)
2768 (syntax-violation 'break "too many arguments" x))
2769 (_
2770 #'(lambda ()
2771 (abort-to-prompt break-tag))))))
2772 (let lp ()
2773 (call-with-prompt
2774 continue-tag
2775 (lambda ()
2776 (define-syntax #,(datum->syntax #'while 'continue)
2777 (lambda (x)
2778 (syntax-case x ()
2779 ((_)
2780 #'(abort-to-prompt continue-tag))
2781 ((_ . args)
2782 (syntax-violation 'continue "too many arguments" x))
2783 (_
2784 #'(lambda args
2785 (apply abort-to-prompt continue-tag args))))))
2786 (do () ((not cond)) body ...))
2787 (lambda (k) (lp)))))
2788 (lambda (k)
2789 #t)))))))
2790
2791
2792 \f
2793
2794 ;;; {Module System Macros}
2795 ;;;
2796
2797 ;; Return a list of expressions that evaluate to the appropriate
2798 ;; arguments for resolve-interface according to SPEC.
2799
2800 (eval-when (compile)
2801 (if (memq 'prefix (read-options))
2802 (error "boot-9 must be compiled with #:kw, not :kw")))
2803
2804 (define (keyword-like-symbol->keyword sym)
2805 (symbol->keyword (string->symbol (substring (symbol->string sym) 1))))
2806
2807 ;; FIXME: we really need to clean up the guts of the module system.
2808 ;; We can compile to something better than process-define-module.
2809 ;;
2810 (define-syntax define-module
2811 (lambda (x)
2812 (define (keyword-like? stx)
2813 (let ((dat (syntax->datum stx)))
2814 (and (symbol? dat)
2815 (eqv? (string-ref (symbol->string dat) 0) #\:))))
2816 (define (->keyword sym)
2817 (symbol->keyword (string->symbol (substring (symbol->string sym) 1))))
2818
2819 (define (quotify-iface args)
2820 (let loop ((in args) (out '()))
2821 (syntax-case in ()
2822 (() (reverse! out))
2823 ;; The user wanted #:foo, but wrote :foo. Fix it.
2824 ((sym . in) (keyword-like? #'sym)
2825 (loop #`(#,(->keyword (syntax->datum #'sym)) . in) out))
2826 ((kw . in) (not (keyword? (syntax->datum #'kw)))
2827 (syntax-violation 'define-module "expected keyword arg" x #'kw))
2828 ((#:renamer renamer . in)
2829 (loop #'in (cons* #'renamer #:renamer out)))
2830 ((kw val . in)
2831 (loop #'in (cons* #''val #'kw out))))))
2832
2833 (define (quotify args)
2834 ;; Just quote everything except #:use-module and #:use-syntax. We
2835 ;; need to know about all arguments regardless since we want to turn
2836 ;; symbols that look like keywords into real keywords, and the
2837 ;; keyword args in a define-module form are not regular
2838 ;; (i.e. no-backtrace doesn't take a value).
2839 (let loop ((in args) (out '()))
2840 (syntax-case in ()
2841 (() (reverse! out))
2842 ;; The user wanted #:foo, but wrote :foo. Fix it.
2843 ((sym . in) (keyword-like? #'sym)
2844 (loop #`(#,(->keyword (syntax->datum #'sym)) . in) out))
2845 ((kw . in) (not (keyword? (syntax->datum #'kw)))
2846 (syntax-violation 'define-module "expected keyword arg" x #'kw))
2847 ((#:no-backtrace . in)
2848 (loop #'in (cons #:no-backtrace out)))
2849 ((#:pure . in)
2850 (loop #'in (cons #:pure out)))
2851 ((kw)
2852 (syntax-violation 'define-module "keyword arg without value" x #'kw))
2853 ((use-module (name name* ...) . in)
2854 (and (memq (syntax->datum #'use-module) '(#:use-module #:use-syntax))
2855 (and-map symbol? (syntax->datum #'(name name* ...))))
2856 (loop #'in
2857 (cons* #''((name name* ...))
2858 #'use-module
2859 out)))
2860 ((use-module ((name name* ...) arg ...) . in)
2861 (and (memq (syntax->datum #'use-module) '(#:use-module #:use-syntax))
2862 (and-map symbol? (syntax->datum #'(name name* ...))))
2863 (loop #'in
2864 (cons* #`(list '(name name* ...) #,@(quotify-iface #'(arg ...)))
2865 #'use-module
2866 out)))
2867 ((#:autoload name bindings . in)
2868 (loop #'in (cons* #''bindings #''name #:autoload out)))
2869 ((kw val . in)
2870 (loop #'in (cons* #''val #'kw out))))))
2871
2872 (syntax-case x ()
2873 ((_ (name name* ...) arg ...)
2874 (with-syntax (((quoted-arg ...) (quotify #'(arg ...))))
2875 #'(eval-when (eval load compile expand)
2876 (let ((m (process-define-module
2877 (list '(name name* ...)
2878 #:filename (assq-ref
2879 (or (current-source-location) '())
2880 'filename)
2881 quoted-arg ...))))
2882 (set-current-module m)
2883 m)))))))
2884
2885 ;; The guts of the use-modules macro. Add the interfaces of the named
2886 ;; modules to the use-list of the current module, in order.
2887
2888 ;; This function is called by "modules.c". If you change it, be sure
2889 ;; to change scm_c_use_module as well.
2890
2891 (define (process-use-modules module-interface-args)
2892 (let ((interfaces (map (lambda (mif-args)
2893 (or (apply resolve-interface mif-args)
2894 (error "no such module" mif-args)))
2895 module-interface-args)))
2896 (call-with-deferred-observers
2897 (lambda ()
2898 (module-use-interfaces! (current-module) interfaces)))))
2899
2900 (define-syntax use-modules
2901 (lambda (x)
2902 (define (keyword-like? stx)
2903 (let ((dat (syntax->datum stx)))
2904 (and (symbol? dat)
2905 (eqv? (string-ref (symbol->string dat) 0) #\:))))
2906 (define (->keyword sym)
2907 (symbol->keyword (string->symbol (substring (symbol->string sym) 1))))
2908
2909 (define (quotify-iface args)
2910 (let loop ((in args) (out '()))
2911 (syntax-case in ()
2912 (() (reverse! out))
2913 ;; The user wanted #:foo, but wrote :foo. Fix it.
2914 ((sym . in) (keyword-like? #'sym)
2915 (loop #`(#,(->keyword (syntax->datum #'sym)) . in) out))
2916 ((kw . in) (not (keyword? (syntax->datum #'kw)))
2917 (syntax-violation 'define-module "expected keyword arg" x #'kw))
2918 ((#:renamer renamer . in)
2919 (loop #'in (cons* #'renamer #:renamer out)))
2920 ((kw val . in)
2921 (loop #'in (cons* #''val #'kw out))))))
2922
2923 (define (quotify specs)
2924 (let lp ((in specs) (out '()))
2925 (syntax-case in ()
2926 (() (reverse out))
2927 (((name name* ...) . in)
2928 (and-map symbol? (syntax->datum #'(name name* ...)))
2929 (lp #'in (cons #''((name name* ...)) out)))
2930 ((((name name* ...) arg ...) . in)
2931 (and-map symbol? (syntax->datum #'(name name* ...)))
2932 (with-syntax (((quoted-arg ...) (quotify-iface #'(arg ...))))
2933 (lp #'in (cons #`(list '(name name* ...) quoted-arg ...)
2934 out)))))))
2935
2936 (syntax-case x ()
2937 ((_ spec ...)
2938 (with-syntax (((quoted-args ...) (quotify #'(spec ...))))
2939 #'(eval-when (eval load compile expand)
2940 (process-use-modules (list quoted-args ...))
2941 *unspecified*))))))
2942
2943 (define-syntax use-syntax
2944 (syntax-rules ()
2945 ((_ spec ...)
2946 (begin
2947 (eval-when (eval load compile expand)
2948 (issue-deprecation-warning
2949 "`use-syntax' is deprecated. Please contact guile-devel for more info."))
2950 (use-modules spec ...)))))
2951
2952 (include-from-path "ice-9/r6rs-libraries")
2953
2954 (define-syntax define-private
2955 (syntax-rules ()
2956 ((_ foo bar)
2957 (define foo bar))))
2958
2959 (define-syntax define-public
2960 (syntax-rules ()
2961 ((_ (name . args) . body)
2962 (define-public name (lambda args . body)))
2963 ((_ name val)
2964 (begin
2965 (define name val)
2966 (export name)))))
2967
2968 (define-syntax defmacro-public
2969 (syntax-rules ()
2970 ((_ name args . body)
2971 (begin
2972 (defmacro name args . body)
2973 (export-syntax name)))))
2974
2975 ;; And now for the most important macro.
2976 (define-syntax λ
2977 (syntax-rules ()
2978 ((_ formals body ...)
2979 (lambda formals body ...))))
2980
2981 \f
2982 ;; Export a local variable
2983
2984 ;; This function is called from "modules.c". If you change it, be
2985 ;; sure to update "modules.c" as well.
2986
2987 (define (module-export! m names)
2988 (let ((public-i (module-public-interface m)))
2989 (for-each (lambda (name)
2990 (let* ((internal-name (if (pair? name) (car name) name))
2991 (external-name (if (pair? name) (cdr name) name))
2992 (var (module-ensure-local-variable! m internal-name)))
2993 (module-add! public-i external-name var)))
2994 names)))
2995
2996 (define (module-replace! m names)
2997 (let ((public-i (module-public-interface m)))
2998 (for-each (lambda (name)
2999 (let* ((internal-name (if (pair? name) (car name) name))
3000 (external-name (if (pair? name) (cdr name) name))
3001 (var (module-ensure-local-variable! m internal-name)))
3002 (set-object-property! var 'replace #t)
3003 (module-add! public-i external-name var)))
3004 names)))
3005
3006 ;; Export all local variables from a module
3007 ;;
3008 (define (module-export-all! mod)
3009 (define (fresh-interface!)
3010 (let ((iface (make-module)))
3011 (set-module-name! iface (module-name mod))
3012 (set-module-version! iface (module-version mod))
3013 (set-module-kind! iface 'interface)
3014 (set-module-public-interface! mod iface)
3015 iface))
3016 (let ((iface (or (module-public-interface mod)
3017 (fresh-interface!))))
3018 (set-module-obarray! iface (module-obarray mod))))
3019
3020 ;; Re-export a imported variable
3021 ;;
3022 (define (module-re-export! m names)
3023 (let ((public-i (module-public-interface m)))
3024 (for-each (lambda (name)
3025 (let* ((internal-name (if (pair? name) (car name) name))
3026 (external-name (if (pair? name) (cdr name) name))
3027 (var (module-variable m internal-name)))
3028 (cond ((not var)
3029 (error "Undefined variable:" internal-name))
3030 ((eq? var (module-local-variable m internal-name))
3031 (error "re-exporting local variable:" internal-name))
3032 (else
3033 (module-add! public-i external-name var)))))
3034 names)))
3035
3036 (define-syntax export
3037 (syntax-rules ()
3038 ((_ name ...)
3039 (eval-when (eval load compile expand)
3040 (call-with-deferred-observers
3041 (lambda ()
3042 (module-export! (current-module) '(name ...))))))))
3043
3044 (define-syntax re-export
3045 (syntax-rules ()
3046 ((_ name ...)
3047 (eval-when (eval load compile expand)
3048 (call-with-deferred-observers
3049 (lambda ()
3050 (module-re-export! (current-module) '(name ...))))))))
3051
3052 (define-syntax export!
3053 (syntax-rules ()
3054 ((_ name ...)
3055 (eval-when (eval load compile expand)
3056 (call-with-deferred-observers
3057 (lambda ()
3058 (module-replace! (current-module) '(name ...))))))))
3059
3060 (define-syntax export-syntax
3061 (syntax-rules ()
3062 ((_ name ...)
3063 (export name ...))))
3064
3065 (define-syntax re-export-syntax
3066 (syntax-rules ()
3067 ((_ name ...)
3068 (re-export name ...))))
3069
3070 (define load load-module)
3071
3072 \f
3073
3074 ;;; {Parameters}
3075 ;;;
3076
3077 (define* (make-mutable-parameter init #:optional (converter identity))
3078 (let ((fluid (make-fluid)))
3079 (fluid-set! fluid (converter init))
3080 (case-lambda
3081 (() (fluid-ref fluid))
3082 ((val) (fluid-set! fluid (converter val))))))
3083
3084
3085 \f
3086
3087 ;;; {Handling of duplicate imported bindings}
3088 ;;;
3089
3090 ;; Duplicate handlers take the following arguments:
3091 ;;
3092 ;; module importing module
3093 ;; name conflicting name
3094 ;; int1 old interface where name occurs
3095 ;; val1 value of binding in old interface
3096 ;; int2 new interface where name occurs
3097 ;; val2 value of binding in new interface
3098 ;; var previous resolution or #f
3099 ;; val value of previous resolution
3100 ;;
3101 ;; A duplicate handler can take three alternative actions:
3102 ;;
3103 ;; 1. return #f => leave responsibility to next handler
3104 ;; 2. exit with an error
3105 ;; 3. return a variable resolving the conflict
3106 ;;
3107
3108 (define duplicate-handlers
3109 (let ((m (make-module 7)))
3110
3111 (define (check module name int1 val1 int2 val2 var val)
3112 (scm-error 'misc-error
3113 #f
3114 "~A: `~A' imported from both ~A and ~A"
3115 (list (module-name module)
3116 name
3117 (module-name int1)
3118 (module-name int2))
3119 #f))
3120
3121 (define (warn module name int1 val1 int2 val2 var val)
3122 (format (current-error-port)
3123 "WARNING: ~A: `~A' imported from both ~A and ~A\n"
3124 (module-name module)
3125 name
3126 (module-name int1)
3127 (module-name int2))
3128 #f)
3129
3130 (define (replace module name int1 val1 int2 val2 var val)
3131 (let ((old (or (and var (object-property var 'replace) var)
3132 (module-variable int1 name)))
3133 (new (module-variable int2 name)))
3134 (if (object-property old 'replace)
3135 (and (or (eq? old new)
3136 (not (object-property new 'replace)))
3137 old)
3138 (and (object-property new 'replace)
3139 new))))
3140
3141 (define (warn-override-core module name int1 val1 int2 val2 var val)
3142 (and (eq? int1 the-scm-module)
3143 (begin
3144 (format (current-error-port)
3145 "WARNING: ~A: imported module ~A overrides core binding `~A'\n"
3146 (module-name module)
3147 (module-name int2)
3148 name)
3149 (module-local-variable int2 name))))
3150
3151 (define (first module name int1 val1 int2 val2 var val)
3152 (or var (module-local-variable int1 name)))
3153
3154 (define (last module name int1 val1 int2 val2 var val)
3155 (module-local-variable int2 name))
3156
3157 (define (noop module name int1 val1 int2 val2 var val)
3158 #f)
3159
3160 (set-module-name! m 'duplicate-handlers)
3161 (set-module-kind! m 'interface)
3162 (module-define! m 'check check)
3163 (module-define! m 'warn warn)
3164 (module-define! m 'replace replace)
3165 (module-define! m 'warn-override-core warn-override-core)
3166 (module-define! m 'first first)
3167 (module-define! m 'last last)
3168 (module-define! m 'merge-generics noop)
3169 (module-define! m 'merge-accessors noop)
3170 m))
3171
3172 (define (lookup-duplicates-handlers handler-names)
3173 (and handler-names
3174 (map (lambda (handler-name)
3175 (or (module-symbol-local-binding
3176 duplicate-handlers handler-name #f)
3177 (error "invalid duplicate handler name:"
3178 handler-name)))
3179 (if (list? handler-names)
3180 handler-names
3181 (list handler-names)))))
3182
3183 (define default-duplicate-binding-procedures
3184 (make-mutable-parameter #f))
3185
3186 (define default-duplicate-binding-handler
3187 (make-mutable-parameter '(replace warn-override-core warn last)
3188 (lambda (handler-names)
3189 (default-duplicate-binding-procedures
3190 (lookup-duplicates-handlers handler-names))
3191 handler-names)))
3192
3193 \f
3194
3195 ;;; {`cond-expand' for SRFI-0 support.}
3196 ;;;
3197 ;;; This syntactic form expands into different commands or
3198 ;;; definitions, depending on the features provided by the Scheme
3199 ;;; implementation.
3200 ;;;
3201 ;;; Syntax:
3202 ;;;
3203 ;;; <cond-expand>
3204 ;;; --> (cond-expand <cond-expand-clause>+)
3205 ;;; | (cond-expand <cond-expand-clause>* (else <command-or-definition>))
3206 ;;; <cond-expand-clause>
3207 ;;; --> (<feature-requirement> <command-or-definition>*)
3208 ;;; <feature-requirement>
3209 ;;; --> <feature-identifier>
3210 ;;; | (and <feature-requirement>*)
3211 ;;; | (or <feature-requirement>*)
3212 ;;; | (not <feature-requirement>)
3213 ;;; <feature-identifier>
3214 ;;; --> <a symbol which is the name or alias of a SRFI>
3215 ;;;
3216 ;;; Additionally, this implementation provides the
3217 ;;; <feature-identifier>s `guile' and `r5rs', so that programs can
3218 ;;; determine the implementation type and the supported standard.
3219 ;;;
3220 ;;; Currently, the following feature identifiers are supported:
3221 ;;;
3222 ;;; guile r5rs srfi-0 srfi-4 srfi-6 srfi-13 srfi-14 srfi-55 srfi-61
3223 ;;;
3224 ;;; Remember to update the features list when adding more SRFIs.
3225 ;;;
3226
3227 (define %cond-expand-features
3228 ;; Adjust the above comment when changing this.
3229 '(guile
3230 guile-2
3231 r5rs
3232 srfi-0 ;; cond-expand itself
3233 srfi-4 ;; homogenous numeric vectors
3234 srfi-6 ;; open-input-string etc, in the guile core
3235 srfi-13 ;; string library
3236 srfi-14 ;; character sets
3237 srfi-55 ;; require-extension
3238 srfi-61 ;; general cond clause
3239 ))
3240
3241 ;; This table maps module public interfaces to the list of features.
3242 ;;
3243 (define %cond-expand-table (make-hash-table 31))
3244
3245 ;; Add one or more features to the `cond-expand' feature list of the
3246 ;; module `module'.
3247 ;;
3248 (define (cond-expand-provide module features)
3249 (let ((mod (module-public-interface module)))
3250 (and mod
3251 (hashq-set! %cond-expand-table mod
3252 (append (hashq-ref %cond-expand-table mod '())
3253 features)))))
3254
3255 (define-syntax cond-expand
3256 (lambda (x)
3257 (define (module-has-feature? mod sym)
3258 (or-map (lambda (mod)
3259 (memq sym (hashq-ref %cond-expand-table mod '())))
3260 (module-uses mod)))
3261
3262 (define (condition-matches? condition)
3263 (syntax-case condition (and or not)
3264 ((and c ...)
3265 (and-map condition-matches? #'(c ...)))
3266 ((or c ...)
3267 (or-map condition-matches? #'(c ...)))
3268 ((not c)
3269 (if (condition-matches? #'c) #f #t))
3270 (c
3271 (identifier? #'c)
3272 (let ((sym (syntax->datum #'c)))
3273 (if (memq sym %cond-expand-features)
3274 #t
3275 (module-has-feature? (current-module) sym))))))
3276
3277 (define (match clauses alternate)
3278 (syntax-case clauses ()
3279 (((condition form ...) . rest)
3280 (if (condition-matches? #'condition)
3281 #'(begin form ...)
3282 (match #'rest alternate)))
3283 (() (alternate))))
3284
3285 (syntax-case x (else)
3286 ((_ clause ... (else form ...))
3287 (match #'(clause ...)
3288 (lambda ()
3289 #'(begin form ...))))
3290 ((_ clause ...)
3291 (match #'(clause ...)
3292 (lambda ()
3293 (syntax-violation 'cond-expand "unfulfilled cond-expand" x)))))))
3294
3295 ;; This procedure gets called from the startup code with a list of
3296 ;; numbers, which are the numbers of the SRFIs to be loaded on startup.
3297 ;;
3298 (define (use-srfis srfis)
3299 (process-use-modules
3300 (map (lambda (num)
3301 (list (list 'srfi (string->symbol
3302 (string-append "srfi-" (number->string num))))))
3303 srfis)))
3304
3305 \f
3306
3307 ;;; srfi-55: require-extension
3308 ;;;
3309
3310 (define-syntax require-extension
3311 (lambda (x)
3312 (syntax-case x (srfi)
3313 ((_ (srfi n ...))
3314 (and-map integer? (syntax->datum #'(n ...)))
3315 (with-syntax
3316 (((srfi-n ...)
3317 (map (lambda (n)
3318 (datum->syntax x (symbol-append 'srfi- n)))
3319 (map string->symbol
3320 (map number->string (syntax->datum #'(n ...)))))))
3321 #'(use-modules (srfi srfi-n) ...)))
3322 ((_ (type arg ...))
3323 (identifier? #'type)
3324 (syntax-violation 'require-extension "Not a recognized extension type"
3325 x)))))
3326
3327 \f
3328
3329 (define using-readline?
3330 (let ((using-readline? (make-fluid)))
3331 (make-procedure-with-setter
3332 (lambda () (fluid-ref using-readline?))
3333 (lambda (v) (fluid-set! using-readline? v)))))
3334
3335 \f
3336
3337 ;;; {Deprecated stuff}
3338 ;;;
3339
3340 (begin-deprecated
3341 (module-use! the-scm-module (resolve-interface '(ice-9 deprecated))))
3342
3343 \f
3344
3345 ;;; Place the user in the guile-user module.
3346 ;;;
3347
3348 ;; FIXME:
3349 (module-use! the-scm-module (resolve-interface '(srfi srfi-4)))
3350
3351 (define-module (guile-user)
3352 #:autoload (system base compile) (compile))
3353
3354 ;; Remain in the `(guile)' module at compilation-time so that the
3355 ;; `-Wunused-toplevel' warning works as expected.
3356 (eval-when (compile) (set-current-module the-root-module))
3357
3358 ;;; boot-9.scm ends here