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