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