Simplify boot-9 for-each with two lists
[bpt/guile.git] / module / ice-9 / boot-9.scm
CommitLineData
87e00370 1;;; -*- mode: scheme; coding: utf-8; -*-
0f2d19dd 2
b3da54d1 3;;;; Copyright (C) 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003,
61d50919 4;;;; 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014
b3da54d1 5;;;; Free Software Foundation, Inc.
20edfbbd 6;;;;
73be1d9e
MV
7;;;; This library is free software; you can redistribute it and/or
8;;;; modify it under the terms of the GNU Lesser General Public
9;;;; License as published by the Free Software Foundation; either
53befeb7 10;;;; version 3 of the License, or (at your option) any later version.
73be1d9e
MV
11;;;;
12;;;; This library is distributed in the hope that it will be useful,
0f2d19dd 13;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
73be1d9e
MV
14;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15;;;; Lesser General Public License for more details.
16;;;;
17;;;; You should have received a copy of the GNU Lesser General Public
18;;;; License along with this library; if not, write to the Free Software
92205699 19;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
a482f2cc 20;;;;
3d2ada2f 21
0f2d19dd
JB
22\f
23
20edfbbd
TTN
24;;; Commentary:
25
0f2d19dd
JB
26;;; This file is the first thing loaded into Guile. It adds many mundane
27;;; definitions and a few that are interesting.
28;;;
20edfbbd 29;;; The module system (hence the hierarchical namespace) are defined in this
0f2d19dd
JB
30;;; file.
31;;;
32
20edfbbd
TTN
33;;; Code:
34
0f2d19dd 35\f
9fb41cea 36
9c35c579
AW
37;; Before compiling, make sure any symbols are resolved in the (guile)
38;; module, the primary location of those symbols, rather than in
39;; (guile-user), the default module that we compile in.
40
41(eval-when (compile)
42 (set-current-module (resolve-module '(guile))))
43
416f26c7
AW
44\f
45
f28dc43c 46;;; {Language primitives}
928258fb
AW
47;;;
48
f28dc43c 49;; These are are the procedural wrappers around the primitives of
39caffe7 50;; Guile's language: apply, call-with-current-continuation, etc.
f28dc43c
AW
51;;
52;; Usually, a call to a primitive is compiled specially. The compiler
53;; knows about all these kinds of expressions. But the primitives may
54;; be referenced not only as operators, but as values as well. These
55;; stub procedures are the "values" of apply, dynamic-wind, and other
56;; such primitives.
57;;
39caffe7
AW
58(define apply
59 (case-lambda
60 ((fun args)
61 ((@@ primitive apply) fun args))
62 ((fun arg1 . args)
63 (letrec ((append* (lambda (tail)
64 (let ((tail (car tail))
65 (tail* (cdr tail)))
66 (if (null? tail*)
67 tail
68 (cons tail (append* tail*)))))))
69 (apply fun (cons arg1 (append* args)))))))
41832152 70(define (call-with-current-continuation proc)
bc056057 71 ((@@ primitive call-with-current-continuation) proc))
41832152 72(define (call-with-values producer consumer)
0fcc39a0 73 ((@@ primitive call-with-values) producer consumer))
41832152
AW
74(define (dynamic-wind in thunk out)
75 "All three arguments must be 0-argument procedures.
76Guard @var{in} is called, then @var{thunk}, then
77guard @var{out}.
78
79If, any time during the execution of @var{thunk}, the
80continuation of the @code{dynamic_wind} expression is escaped
81non-locally, @var{out} is called. If the continuation of
82the dynamic-wind is re-entered, @var{in} is called. Thus
83@var{in} and @var{out} may be called any number of
84times.
85@lisp
86 (define x 'normal-binding)
87@result{} x
88 (define a-cont
89 (call-with-current-continuation
90 (lambda (escape)
91 (let ((old-x x))
92 (dynamic-wind
93 ;; in-guard:
94 ;;
95 (lambda () (set! x 'special-binding))
96
97 ;; thunk
98 ;;
99 (lambda () (display x) (newline)
100 (call-with-current-continuation escape)
101 (display x) (newline)
102 x)
103
104 ;; out-guard:
105 ;;
106 (lambda () (set! x old-x)))))))
107
108;; Prints:
109special-binding
110;; Evaluates to:
111@result{} a-cont
112x
113@result{} normal-binding
114 (a-cont #f)
115;; Prints:
116special-binding
117;; Evaluates to:
118@result{} a-cont ;; the value of the (define a-cont...)
119x
120@result{} normal-binding
121a-cont
122@result{} special-binding
123@end lisp"
73ba69a6
AW
124 ;; FIXME: Here we don't check that the out procedure is a thunk before
125 ;; calling the in-guard, as dynamic-wind is called as part of loading
126 ;; modules, but thunk? requires loading (system vm debug). This is in
127 ;; contrast to the open-coded version of dynamic-wind, which does
128 ;; currently insert an eager thunk? check (but often optimizes it
129 ;; out). Not sure what the right thing to do is here -- make thunk?
130 ;; callable before modules are loaded, live with this inconsistency,
131 ;; or remove the thunk? check from the compiler? Questions,
132 ;; questions.
133 #;
134 (unless (thunk? out)
135 (scm-error 'wrong-type-arg "dynamic-wind" "Not a thunk: ~S"
136 (list out) #f))
137 (in)
bb97e4ab
AW
138 ((@@ primitive wind) in out)
139 (call-with-values thunk
140 (lambda vals
141 ((@@ primitive unwind))
142 (out)
143 (apply values vals))))
41832152 144
440392fa
AW
145(define (with-fluid* fluid val thunk)
146 "Set @var{fluid} to @var{value} temporarily, and call @var{thunk}.
147@var{thunk} must be a procedure of no arguments."
148 ((@@ primitive push-fluid) fluid val)
149 (call-with-values thunk
150 (lambda vals
151 ((@@ primitive pop-fluid))
152 (apply values vals))))
153
f6e6b518 154\f
41832152 155
f6e6b518 156;;; {Low-Level Port Code}
41832152 157;;;
41832152 158
f6e6b518
AW
159;; These are used to request the proper mode to open files in.
160;;
41832152
AW
161(define OPEN_READ "r")
162(define OPEN_WRITE "w")
163(define OPEN_BOTH "r+")
164
165(define *null-device* "/dev/null")
166
f6f4feb0 167;; NOTE: Later in this file, this is redefined to support keywords
41832152
AW
168(define (open-input-file str)
169 "Takes a string naming an existing file and returns an input port
170capable of delivering characters from the file. If the file
171cannot be opened, an error is signalled."
172 (open-file str OPEN_READ))
173
f6f4feb0 174;; NOTE: Later in this file, this is redefined to support keywords
41832152
AW
175(define (open-output-file str)
176 "Takes a string naming an output file to be created and returns an
177output port capable of writing characters to a new file by that
178name. If the file cannot be opened, an error is signalled. If a
179file with the given name already exists, the effect is unspecified."
180 (open-file str OPEN_WRITE))
181
182(define (open-io-file str)
183 "Open file with name STR for both input and output."
184 (open-file str OPEN_BOTH))
185
928258fb
AW
186\f
187
eb5d1f88
AW
188;;; {Simple Debugging Tools}
189;;;
190
191;; peek takes any number of arguments, writes them to the
192;; current ouput port, and returns the last argument.
193;; It is handy to wrap around an expression to look at
194;; a value each time is evaluated, e.g.:
195;;
9b5a0d84
AW
196;; (+ 10 (troublesome-fn))
197;; => (+ 10 (pk 'troublesome-fn-returned (troublesome-fn)))
eb5d1f88
AW
198;;
199
200(define (peek . stuff)
201 (newline)
202 (display ";;; ")
203 (write stuff)
204 (newline)
205 (car (last-pair stuff)))
206
207(define pk peek)
208
3972de76
AW
209;; Temporary definition; replaced later.
210(define current-warning-port current-error-port)
b7742c6b 211
eb5d1f88 212(define (warn . stuff)
f7955da9
AW
213 (newline (current-warning-port))
214 (display ";;; WARNING " (current-warning-port))
215 (display stuff (current-warning-port))
216 (newline (current-warning-port))
217 (car (last-pair stuff)))
eb5d1f88
AW
218
219\f
220
21ed9efe 221;;; {Features}
3d2ada2f 222;;;
21ed9efe
MD
223
224(define (provide sym)
225 (if (not (memq sym *features*))
226 (set! *features* (cons sym *features*))))
227
3d2ada2f
DH
228;; Return #t iff FEATURE is available to this Guile interpreter. In SLIB,
229;; provided? also checks to see if the module is available. We should do that
230;; too, but don't.
231
50706e94
JB
232(define (provided? feature)
233 (and (memq feature *features*) #t))
234
4d248541
AW
235\f
236
9b3cc659
AW
237;;; {Structs}
238;;;
239
240(define (make-struct/no-tail vtable . args)
241 (apply make-struct vtable 0 args))
242
243\f
244
a2230b65
AW
245;;; Boot versions of `map' and `for-each', enough to get the expander
246;;; running.
247;;;
248(define map
249 (case-lambda
250 ((f l)
251 (let map1 ((l l))
252 (if (null? l)
253 '()
254 (cons (f (car l)) (map1 (cdr l))))))
255 ((f l1 l2)
256 (let map2 ((l1 l1) (l2 l2))
257 (if (null? l1)
258 '()
259 (cons (f (car l1) (car l2))
260 (map2 (cdr l1) (cdr l2))))))
261 ((f l1 . rest)
262 (let lp ((l1 l1) (rest rest))
263 (if (null? l1)
264 '()
265 (cons (apply f (car l1) (map car rest))
266 (lp (cdr l1) (map cdr rest))))))))
267
268(define for-each
269 (case-lambda
270 ((f l)
271 (let for-each1 ((l l))
272 (if (pair? l)
273 (begin
274 (f (car l))
275 (for-each1 (cdr l))))))
276 ((f l1 l2)
277 (let for-each2 ((l1 l1) (l2 l2))
278 (if (pair? l1)
279 (begin
280 (f (car l1) (car l2))
281 (for-each2 (cdr l1) (cdr l2))))))
282 ((f l1 . rest)
283 (let lp ((l1 l1) (rest rest))
284 (if (pair? l1)
285 (begin
286 (apply f (car l1) (map car rest))
287 (lp (cdr l1) (map cdr rest))))))))
288
9b6316ea
AW
289;; Temporary definition used in the include-from-path expansion;
290;; replaced later.
291
292(define (absolute-file-name? file-name)
293 #t)
294
4d248541
AW
295;;; {and-map and or-map}
296;;;
297;;; (and-map fn lst) is like (and (fn (car lst)) (fn (cadr lst)) (fn...) ...)
298;;; (or-map fn lst) is like (or (fn (car lst)) (fn (cadr lst)) (fn...) ...)
299;;;
300
301;; and-map f l
302;;
303;; Apply f to successive elements of l until exhaustion or f returns #f.
304;; If returning early, return #f. Otherwise, return the last value returned
305;; by f. If f has never been called because l is empty, return #t.
306;;
307(define (and-map f lst)
308 (let loop ((result #t)
9b5a0d84 309 (l lst))
4d248541 310 (and result
9b5a0d84
AW
311 (or (and (null? l)
312 result)
313 (loop (f (car l)) (cdr l))))))
4d248541
AW
314
315;; or-map f l
316;;
317;; Apply f to successive elements of l until exhaustion or while f returns #f.
318;; If returning early, return the return value of f.
319;;
320(define (or-map f lst)
321 (let loop ((result #f)
9b5a0d84 322 (l lst))
4d248541 323 (or result
9b5a0d84
AW
324 (and (not (null? l))
325 (loop (f (car l)) (cdr l))))))
4d248541
AW
326
327\f
328
3d2ada2f 329;; let format alias simple-format until the more complete version is loaded
52cfc69b 330
8641dd9e
GB
331(define format simple-format)
332
fdc6aebf
KR
333;; this is scheme wrapping the C code so the final pred call is a tail call,
334;; per SRFI-13 spec
a4c8a02e
AW
335(define string-any
336 (lambda* (char_pred s #:optional (start 0) (end (string-length s)))
fdc6aebf 337 (if (and (procedure? char_pred)
9b5a0d84
AW
338 (> end start)
339 (<= end (string-length s))) ;; let c-code handle range error
340 (or (string-any-c-code char_pred s start (1- end))
341 (char_pred (string-ref s (1- end))))
342 (string-any-c-code char_pred s start end))))
fdc6aebf
KR
343
344;; this is scheme wrapping the C code so the final pred call is a tail call,
345;; per SRFI-13 spec
a4c8a02e
AW
346(define string-every
347 (lambda* (char_pred s #:optional (start 0) (end (string-length s)))
fdc6aebf 348 (if (and (procedure? char_pred)
9b5a0d84
AW
349 (> end start)
350 (<= end (string-length s))) ;; let c-code handle range error
351 (and (string-every-c-code char_pred s start (1- end))
352 (char_pred (string-ref s (1- end))))
353 (string-every-c-code char_pred s start end))))
fdc6aebf 354
1b05b324
MV
355;; A variant of string-fill! that we keep for compatability
356;;
357(define (substring-fill! str start end fill)
358 (string-fill! str fill start end))
359
21ed9efe 360\f
79451588 361
12eae603
AW
362;; Define a minimal stub of the module API for psyntax, before modules
363;; have booted.
efa6f9d9 364(define (module-name x)
a26934a8 365 '(guile))
05a5e5d6
AW
366(define (module-add! module sym var)
367 (hashq-set! (%get-pre-modules-obarray) sym var))
3d5f3091
AW
368(define (module-define! module sym val)
369 (let ((v (hashq-ref (%get-pre-modules-obarray) sym)))
370 (if v
371 (variable-set! v val)
05a5e5d6 372 (module-add! (current-module) sym (make-variable val)))))
3d5f3091
AW
373(define (module-ref module sym)
374 (let ((v (module-variable module sym)))
375 (if v (variable-ref v) (error "badness!" (pk module) (pk sym)))))
12eae603
AW
376(define (resolve-module . args)
377 #f)
3d5f3091 378
6a952e0e 379;; API provided by psyntax
e4721dde 380(define syntax-violation #f)
22225fc1
AW
381(define datum->syntax #f)
382(define syntax->datum #f)
750ae8b7 383(define syntax-source #f)
22225fc1
AW
384(define identifier? #f)
385(define generate-temporaries #f)
13182603 386(define bound-identifier=? #f)
13182603 387(define free-identifier=? #f)
5a0132b3 388
8a73a6d2 389;; $sc-dispatch is an implementation detail of psyntax. It is used by
6a952e0e 390;; expanded macros, to dispatch an input against a set of patterns.
5a0132b3
AW
391(define $sc-dispatch #f)
392
6a952e0e 393;; Load it up!
13182603 394(primitive-load-path "ice-9/psyntax-pp")
4f692ace
AW
395;; The binding for `macroexpand' has now been overridden, making psyntax the
396;; expander now.
79451588 397
a1a482e0
AW
398(define-syntax and
399 (syntax-rules ()
400 ((_) #t)
401 ((_ x) x)
402 ((_ x y ...) (if x (and y ...) #f))))
403
404(define-syntax or
405 (syntax-rules ()
406 ((_) #f)
407 ((_ x) x)
408 ((_ x y ...) (let ((t x)) (if t t (or y ...))))))
409
e7cf0457
MW
410(include-from-path "ice-9/quasisyntax")
411
9accf3d9
AW
412(define-syntax-rule (when test stmt stmt* ...)
413 (if test (begin stmt stmt* ...)))
414
415(define-syntax-rule (unless test stmt stmt* ...)
416 (if (not test) (begin stmt stmt* ...)))
417
a1a482e0 418(define-syntax cond
e7cf0457
MW
419 (lambda (whole-expr)
420 (define (fold f seed xs)
421 (let loop ((xs xs) (seed seed))
422 (if (null? xs) seed
423 (loop (cdr xs) (f (car xs) seed)))))
424 (define (reverse-map f xs)
425 (fold (lambda (x seed) (cons (f x) seed))
426 '() xs))
427 (syntax-case whole-expr ()
428 ((_ clause clauses ...)
429 #`(begin
430 #,@(fold (lambda (clause-builder tail)
431 (clause-builder tail))
432 #'()
433 (reverse-map
434 (lambda (clause)
435 (define* (bad-clause #:optional (msg "invalid clause"))
436 (syntax-violation 'cond msg whole-expr clause))
437 (syntax-case clause (=> else)
438 ((else e e* ...)
439 (lambda (tail)
440 (if (null? tail)
441 #'((begin e e* ...))
442 (bad-clause "else must be the last clause"))))
443 ((else . _) (bad-clause))
444 ((test => receiver)
445 (lambda (tail)
446 #`((let ((t test))
447 (if t
448 (receiver t)
449 #,@tail)))))
450 ((test => receiver ...)
451 (bad-clause "wrong number of receiver expressions"))
452 ((generator guard => receiver)
453 (lambda (tail)
454 #`((call-with-values (lambda () generator)
455 (lambda vals
456 (if (apply guard vals)
457 (apply receiver vals)
458 #,@tail))))))
459 ((generator guard => receiver ...)
460 (bad-clause "wrong number of receiver expressions"))
461 ((test)
462 (lambda (tail)
463 #`((let ((t test))
464 (if t t #,@tail)))))
465 ((test e e* ...)
466 (lambda (tail)
467 #`((if test
468 (begin e e* ...)
469 #,@tail))))
470 (_ (bad-clause))))
471 #'(clause clauses ...))))))))
a1a482e0
AW
472
473(define-syntax case
e7cf0457
MW
474 (lambda (whole-expr)
475 (define (fold f seed xs)
476 (let loop ((xs xs) (seed seed))
477 (if (null? xs) seed
478 (loop (cdr xs) (f (car xs) seed)))))
479 (define (fold2 f a b xs)
480 (let loop ((xs xs) (a a) (b b))
481 (if (null? xs) (values a b)
482 (call-with-values
483 (lambda () (f (car xs) a b))
484 (lambda (a b)
485 (loop (cdr xs) a b))))))
486 (define (reverse-map-with-seed f seed xs)
487 (fold2 (lambda (x ys seed)
488 (call-with-values
489 (lambda () (f x seed))
490 (lambda (y seed)
491 (values (cons y ys) seed))))
492 '() seed xs))
493 (syntax-case whole-expr ()
494 ((_ expr clause clauses ...)
495 (with-syntax ((key #'key))
496 #`(let ((key expr))
497 #,@(fold
498 (lambda (clause-builder tail)
499 (clause-builder tail))
500 #'()
501 (reverse-map-with-seed
502 (lambda (clause seen)
503 (define* (bad-clause #:optional (msg "invalid clause"))
504 (syntax-violation 'case msg whole-expr clause))
505 (syntax-case clause ()
506 ((test . rest)
507 (with-syntax
508 ((clause-expr
509 (syntax-case #'rest (=>)
510 ((=> receiver) #'(receiver key))
511 ((=> receiver ...)
512 (bad-clause
513 "wrong number of receiver expressions"))
514 ((e e* ...) #'(begin e e* ...))
515 (_ (bad-clause)))))
516 (syntax-case #'test (else)
517 ((datums ...)
518 (let ((seen
519 (fold
520 (lambda (datum seen)
521 (define (warn-datum type)
522 ((@ (system base message)
523 warning)
524 type
525 (append (source-properties datum)
526 (source-properties
527 (syntax->datum #'test)))
528 datum
529 (syntax->datum clause)
530 (syntax->datum whole-expr)))
118ff892
AW
531 (when (memv datum seen)
532 (warn-datum 'duplicate-case-datum))
533 (when (or (pair? datum) (array? datum))
534 (warn-datum 'bad-case-datum))
e7cf0457
MW
535 (cons datum seen))
536 seen
537 (map syntax->datum #'(datums ...)))))
538 (values (lambda (tail)
539 #`((if (memv key '(datums ...))
540 clause-expr
541 #,@tail)))
542 seen)))
543 (else (values (lambda (tail)
544 (if (null? tail)
545 #'(clause-expr)
546 (bad-clause
547 "else must be the last clause")))
548 seen))
549 (_ (bad-clause)))))
550 (_ (bad-clause))))
551 '() #'(clause clauses ...)))))))))
a1a482e0
AW
552
553(define-syntax do
554 (syntax-rules ()
555 ((do ((var init step ...) ...)
556 (test expr ...)
557 command ...)
558 (letrec
559 ((loop
560 (lambda (var ...)
561 (if test
562 (begin
563 (if #f #f)
564 expr ...)
565 (begin
566 command
567 ...
568 (loop (do "step" var step ...)
569 ...))))))
570 (loop init ...)))
571 ((do "step" x)
572 x)
573 ((do "step" x y)
574 y)))
575
48eb9021
MW
576(define-syntax define-values
577 (lambda (orig-form)
578 (syntax-case orig-form ()
579 ((_ () expr)
866af5da
MW
580 ;; XXX Work around the lack of hygienic top-level identifiers
581 (with-syntax (((dummy) (generate-temporaries '(dummy))))
582 #`(define dummy
583 (call-with-values (lambda () expr)
b00c9b22 584 (lambda () #f)))))
48eb9021
MW
585 ((_ (var) expr)
586 (identifier? #'var)
587 #`(define var
588 (call-with-values (lambda () expr)
b00c9b22 589 (lambda (v) v))))
48eb9021
MW
590 ((_ (var0 ... varn) expr)
591 (and-map identifier? #'(var0 ... varn))
866af5da
MW
592 ;; XXX Work around the lack of hygienic toplevel identifiers
593 (with-syntax (((dummy) (generate-temporaries '(dummy))))
594 #`(begin
595 ;; Avoid mutating the user-visible variables
596 (define dummy
597 (call-with-values (lambda () expr)
b00c9b22
AW
598 (lambda (var0 ... varn)
599 (list var0 ... varn))))
866af5da
MW
600 (define var0
601 (let ((v (car dummy)))
602 (set! dummy (cdr dummy))
603 v))
604 ...
605 (define varn
606 (let ((v (car dummy)))
607 (set! dummy #f) ; blackhole dummy
608 v)))))
48eb9021
MW
609 ((_ var expr)
610 (identifier? #'var)
611 #'(define var
612 (call-with-values (lambda () expr)
613 list)))
614 ((_ (var0 ... . varn) expr)
615 (and-map identifier? #'(var0 ... varn))
866af5da
MW
616 ;; XXX Work around the lack of hygienic toplevel identifiers
617 (with-syntax (((dummy) (generate-temporaries '(dummy))))
618 #`(begin
619 ;; Avoid mutating the user-visible variables
620 (define dummy
621 (call-with-values (lambda () expr)
b00c9b22
AW
622 (lambda (var0 ... . varn)
623 (list var0 ... varn))))
866af5da
MW
624 (define var0
625 (let ((v (car dummy)))
626 (set! dummy (cdr dummy))
627 v))
628 ...
629 (define varn
630 (let ((v (car dummy)))
631 (set! dummy #f) ; blackhole dummy
632 v))))))))
48eb9021 633
0c65f52c
AW
634(define-syntax-rule (delay exp)
635 (make-promise (lambda () exp)))
79451588 636
c32b7c4c
AW
637(define-syntax with-fluids
638 (lambda (stx)
639 (define (emit-with-fluids bindings body)
640 (syntax-case bindings ()
641 (()
642 body)
643 (((f v) . bindings)
644 #`(with-fluid* f v
645 (lambda ()
646 #,(emit-with-fluids #'bindings body))))))
647 (syntax-case stx ()
648 ((_ ((fluid val) ...) exp exp* ...)
649 (with-syntax (((fluid-tmp ...) (generate-temporaries #'(fluid ...)))
650 ((val-tmp ...) (generate-temporaries #'(val ...))))
651 #`(let ((fluid-tmp fluid) ...)
652 (let ((val-tmp val) ...)
653 #,(emit-with-fluids #'((fluid-tmp val-tmp) ...)
654 #'(begin exp exp* ...)))))))))
655
41147ee7
AW
656(define-syntax current-source-location
657 (lambda (x)
658 (syntax-case x ()
659 ((_)
660 (with-syntax ((s (datum->syntax x (syntax-source x))))
661 #''s)))))
662
925172cf
AW
663;; We provide this accessor out of convenience. current-line and
664;; current-column aren't so interesting, because they distort what they
665;; are measuring; better to use syntax-source from a macro.
666;;
667(define-syntax current-filename
668 (lambda (x)
669 "A macro that expands to the current filename: the filename that
670the (current-filename) form appears in. Expands to #f if this
671information is unavailable."
21ad60a1
AW
672 (false-if-exception
673 (canonicalize-path (assq-ref (syntax-source x) 'filename)))))
925172cf 674
0c65f52c
AW
675(define-syntax-rule (define-once sym val)
676 (define sym
677 (if (module-locally-bound? (current-module) 'sym) sym val)))
41147ee7 678
440392fa
AW
679
680\f
681
682;;; {Error handling}
683;;;
684
685;; Define delimited continuation operators, and implement catch and throw in
686;; terms of them.
687
688(define make-prompt-tag
689 (lambda* (#:optional (stem "prompt"))
690 ;; The only property that prompt tags need have is uniqueness in the
691 ;; sense of eq?. A one-element list will serve nicely.
692 (list stem)))
693
694(define default-prompt-tag
695 ;; Redefined later to be a parameter.
696 (let ((%default-prompt-tag (make-prompt-tag)))
697 (lambda ()
698 %default-prompt-tag)))
699
700(define (call-with-prompt tag thunk handler)
701 ((@@ primitive call-with-prompt) tag thunk handler))
702(define (abort-to-prompt tag . args)
703 (abort-to-prompt* tag args))
704
705;; Define catch and with-throw-handler, using some common helper routines and a
706;; shared fluid. Hide the helpers in a lexical contour.
707
708(define with-throw-handler #f)
5d20fd49 709(let ((%eh (module-ref (current-module) '%exception-handler)))
0f0b6f2d 710 (define (make-exception-handler catch-key prompt-tag pre-unwind)
5d20fd49 711 (vector (fluid-ref %eh) catch-key prompt-tag pre-unwind))
0f0b6f2d
AW
712 (define (exception-handler-prev handler) (vector-ref handler 0))
713 (define (exception-handler-catch-key handler) (vector-ref handler 1))
714 (define (exception-handler-prompt-tag handler) (vector-ref handler 2))
715 (define (exception-handler-pre-unwind handler) (vector-ref handler 3))
716
717 (define %running-pre-unwind (make-fluid '()))
718
719 (define (dispatch-exception handler key args)
720 (unless handler
721 (when (eq? key 'quit)
722 (primitive-exit (cond
723 ((not (pair? args)) 0)
724 ((integer? (car args)) (car args))
725 ((not (car args)) 1)
726 (else 0))))
727 (format (current-error-port) "guile: uncaught throw to ~a: ~a\n" key args)
728 (primitive-exit 1))
729
730 (let ((catch-key (exception-handler-catch-key handler))
731 (prev (exception-handler-prev handler)))
732 (if (or (eqv? catch-key #t) (eq? catch-key key))
733 (let ((prompt-tag (exception-handler-prompt-tag handler))
734 (pre-unwind (exception-handler-pre-unwind handler)))
735 (if pre-unwind
736 ;; Instead of using a "running" set, it would be a lot
737 ;; cleaner semantically to roll back the exception
738 ;; handler binding to the one that was in place when the
739 ;; pre-unwind handler was installed, and keep it like
740 ;; that for the rest of the dispatch. Unfortunately
741 ;; that is incompatible with existing semantics. We'll
742 ;; see if we can change that later on.
743 (let ((running (fluid-ref %running-pre-unwind)))
744 (with-fluid* %running-pre-unwind (cons handler running)
745 (lambda ()
746 (unless (memq handler running)
747 (apply pre-unwind key args))
748 (if prompt-tag
749 (apply abort-to-prompt prompt-tag key args)
750 (dispatch-exception prev key args)))))
751 (apply abort-to-prompt prompt-tag key args)))
752 (dispatch-exception prev key args))))
753
754 (define (throw key . args)
755 "Invoke the catch form matching @var{key}, passing @var{args} to the
756@var{handler}.
757
758@var{key} is a symbol. It will match catches of the same symbol or of @code{#t}.
759
760If there is no handler at all, Guile prints an error and then exits."
761 (unless (symbol? key)
762 (throw 'wrong-type-arg "throw" "Wrong type argument in position ~a: ~a"
763 (list 1 key) (list key)))
5d20fd49 764 (dispatch-exception (fluid-ref %eh) key args))
0f0b6f2d
AW
765
766 (define* (catch k thunk handler #:optional pre-unwind-handler)
767 "Invoke @var{thunk} in the dynamic context of @var{handler} for
440392fa
AW
768exceptions matching @var{key}. If thunk throws to the symbol
769@var{key}, then @var{handler} is invoked this way:
770@lisp
771 (handler key args ...)
772@end lisp
773
774@var{key} is a symbol or @code{#t}.
775
776@var{thunk} takes no arguments. If @var{thunk} returns
777normally, that is the return value of @code{catch}.
778
779Handler is invoked outside the scope of its own @code{catch}.
780If @var{handler} again throws to the same key, a new handler
781from further up the call chain is invoked.
782
783If the key is @code{#t}, then a throw to @emph{any} symbol will
784match this call to @code{catch}.
785
786If a @var{pre-unwind-handler} is given and @var{thunk} throws
787an exception that matches @var{key}, Guile calls the
788@var{pre-unwind-handler} before unwinding the dynamic state and
789invoking the main @var{handler}. @var{pre-unwind-handler} should
790be a procedure with the same signature as @var{handler}, that
791is @code{(lambda (key . args))}. It is typically used to save
792the stack at the point where the exception occurred, but can also
793query other parts of the dynamic state at that point, such as
794fluid values.
795
796A @var{pre-unwind-handler} can exit either normally or non-locally.
797If it exits normally, Guile unwinds the stack and dynamic context
798and then calls the normal (third argument) handler. If it exits
799non-locally, that exit determines the continuation."
7e2fd4e7
AW
800 (define (wrong-type-arg n val)
801 (scm-error 'wrong-type-arg "catch"
802 "Wrong type argument in position ~a: ~a"
803 (list n val) (list val)))
804 (unless (or (symbol? k) (eqv? k #t))
805 (wrong-type-arg 1 k))
806 (unless (procedure? handler)
807 (wrong-type-arg 3 handler))
808 (unless (or (not pre-unwind-handler) (procedure? pre-unwind-handler))
809 (wrong-type-arg 4 pre-unwind-handler))
0f0b6f2d
AW
810 (let ((tag (make-prompt-tag "catch")))
811 (call-with-prompt
812 tag
813 (lambda ()
5d20fd49 814 (with-fluid* %eh (make-exception-handler k tag pre-unwind-handler)
0f0b6f2d
AW
815 thunk))
816 (lambda (cont k . args)
817 (apply handler k args)))))
818
819 (define (with-throw-handler k thunk pre-unwind-handler)
820 "Add @var{handler} to the dynamic context as a throw handler
440392fa 821for key @var{k}, then invoke @var{thunk}."
0f0b6f2d
AW
822 (if (not (or (symbol? k) (eqv? k #t)))
823 (scm-error 'wrong-type-arg "with-throw-handler"
824 "Wrong type argument in position ~a: ~a"
825 (list 1 k) (list k)))
5d20fd49 826 (with-fluid* %eh (make-exception-handler k #f pre-unwind-handler)
0f0b6f2d
AW
827 thunk))
828
5d20fd49 829 (hashq-remove! (%get-pre-modules-obarray) '%exception-handler)
0f0b6f2d
AW
830 (define! 'catch catch)
831 (define! 'with-throw-handler with-throw-handler)
832 (define! 'throw throw))
440392fa
AW
833
834
835\f
836
a2230b65
AW
837;;; The real versions of `map' and `for-each', with cycle detection, and
838;;; that use reverse! instead of recursion in the case of `map'.
839;;;
840(define map
841 (case-lambda
842 ((f l)
843 (let map1 ((hare l) (tortoise l) (move? #f) (out '()))
844 (if (pair? hare)
845 (if move?
846 (if (eq? tortoise hare)
847 (scm-error 'wrong-type-arg "map" "Circular list: ~S"
848 (list l) #f)
849 (map1 (cdr hare) (cdr tortoise) #f
850 (cons (f (car hare)) out)))
851 (map1 (cdr hare) tortoise #t
852 (cons (f (car hare)) out)))
853 (if (null? hare)
854 (reverse! out)
855 (scm-error 'wrong-type-arg "map" "Not a list: ~S"
856 (list l) #f)))))
857
858 ((f l1 l2)
859 (let map2 ((h1 l1) (h2 l2) (t1 l1) (t2 l2) (move? #f) (out '()))
860 (cond
861 ((pair? h1)
862 (cond
863 ((not (pair? h2))
864 (scm-error 'wrong-type-arg "map"
865 (if (list? h2)
866 "List of wrong length: ~S"
867 "Not a list: ~S")
868 (list l2) #f))
869 ((not move?)
870 (map2 (cdr h1) (cdr h2) t1 t2 #t
871 (cons (f (car h1) (car h2)) out)))
872 ((eq? t1 h1)
873 (scm-error 'wrong-type-arg "map" "Circular list: ~S"
874 (list l1) #f))
875 ((eq? t2 h2)
876 (scm-error 'wrong-type-arg "map" "Circular list: ~S"
877 (list l2) #f))
878 (else
879 (map2 (cdr h1) (cdr h2) (cdr t1) (cdr t2) #f
880 (cons (f (car h1) (car h2)) out)))))
881
882 ((and (null? h1) (null? h2))
883 (reverse! out))
884
885 ((null? h1)
886 (scm-error 'wrong-type-arg "map"
887 (if (list? h2)
888 "List of wrong length: ~S"
889 "Not a list: ~S")
890 (list l2) #f))
891 (else
892 (scm-error 'wrong-type-arg "map"
893 "Not a list: ~S"
894 (list l1) #f)))))
895
896 ((f l1 . rest)
897 (let ((len (length l1)))
898 (let mapn ((rest rest))
899 (or (null? rest)
900 (if (= (length (car rest)) len)
901 (mapn (cdr rest))
902 (scm-error 'wrong-type-arg "map" "List of wrong length: ~S"
903 (list (car rest)) #f)))))
904 (let mapn ((l1 l1) (rest rest) (out '()))
905 (if (null? l1)
906 (reverse! out)
907 (mapn (cdr l1) (map cdr rest)
908 (cons (apply f (car l1) (map car rest)) out)))))))
909
910(define map-in-order map)
911
912(define for-each
913 (case-lambda
914 ((f l)
f87a7327
AW
915 (unless (list? l)
916 (scm-error 'wrong-type-arg "for-each" "Not a list: ~S" (list l) #f))
917 (let for-each1 ((l l))
918 (unless (null? l)
919 (f (car l))
920 (for-each1 (cdr l)))))
8dcabf60 921
a2230b65 922 ((f l1 l2)
ed59b70a
AW
923 (unless (= (length l1) (length l2))
924 (scm-error 'wrong-type-arg "for-each" "List of wrong length: ~S"
925 (list l2) #f))
926 (let for-each2 ((l1 l1) (l2 l2))
927 (unless (null? l1)
928 (f (car l1) (car l2))
929 (for-each2 (cdr l1) (cdr l2)))))
a2230b65
AW
930
931 ((f l1 . rest)
932 (let ((len (length l1)))
933 (let for-eachn ((rest rest))
934 (or (null? rest)
935 (if (= (length (car rest)) len)
936 (for-eachn (cdr rest))
937 (scm-error 'wrong-type-arg "for-each" "List of wrong length: ~S"
938 (list (car rest)) #f)))))
939
940 (let for-eachn ((l1 l1) (rest rest))
941 (if (pair? l1)
942 (begin
943 (apply f (car l1) (map car rest))
944 (for-eachn (cdr l1) (map cdr rest))))))))
945
946
79451588 947\f
48fdec21 948
40b91dc8
AW
949;;;
950;;; Extensible exception printing.
951;;;
952
953(define set-exception-printer! #f)
e8df456a
AW
954;; There is already a definition of print-exception from backtrace.c
955;; that we will override.
40b91dc8
AW
956
957(let ((exception-printers '()))
958 (define (print-location frame port)
959 (let ((source (and=> frame frame-source)))
960 ;; source := (addr . (filename . (line . column)))
961 (if source
962 (let ((filename (or (cadr source) "<unnamed port>"))
963 (line (caddr source))
964 (col (cdddr source)))
153c4a4a 965 (format port "~a:~a:~a: " filename (1+ line) col))
40b91dc8
AW
966 (format port "ERROR: "))))
967
968 (set! set-exception-printer!
969 (lambda (key proc)
970 (set! exception-printers (acons key proc exception-printers))))
971
972 (set! print-exception
973 (lambda (port frame key args)
974 (define (default-printer)
975 (format port "Throw to key `~a' with args `~s'." key args))
976
977 (if frame
978 (let ((proc (frame-procedure frame)))
979 (print-location frame port)
980 (format port "In procedure ~a:\n"
da874e54
AW
981 (or (false-if-exception (procedure-name proc))
982 proc))))
40b91dc8
AW
983
984 (print-location frame port)
985 (catch #t
986 (lambda ()
987 (let ((printer (assq-ref exception-printers key)))
988 (if printer
989 (printer port key args default-printer)
990 (default-printer))))
991 (lambda (k . args)
992 (format port "Error while printing exception.")))
993 (newline port)
994 (force-output port))))
995
996;;;
997;;; Printers for those keys thrown by Guile.
998;;;
999(let ()
1000 (define (scm-error-printer port key args default-printer)
1001 ;; Abuse case-lambda as a pattern matcher, given that we don't have
1002 ;; ice-9 match at this point.
1003 (apply (case-lambda
1004 ((subr msg args . rest)
1005 (if subr
1006 (format port "In procedure ~a: " subr))
4e33a132 1007 (apply format port msg (or args '())))
40b91dc8
AW
1008 (_ (default-printer)))
1009 args))
1010
1011 (define (syntax-error-printer port key args default-printer)
1012 (apply (case-lambda
dc20f5a8 1013 ((who what where form subform . extra)
40b91dc8
AW
1014 (format port "Syntax error:\n")
1015 (if where
1016 (let ((file (or (assq-ref where 'filename) "unknown file"))
1017 (line (and=> (assq-ref where 'line) 1+))
1018 (col (assq-ref where 'column)))
1019 (format port "~a:~a:~a: " file line col))
1020 (format port "unknown location: "))
1021 (if who
1022 (format port "~a: " who))
1023 (format port "~a" what)
1024 (if subform
1025 (format port " in subform ~s of ~s" subform form)
1026 (if form
1027 (format port " in form ~s" form))))
1028 (_ (default-printer)))
1029 args))
1030
4af0d97e
LC
1031 (define (keyword-error-printer port key args default-printer)
1032 (let ((message (cadr args))
1033 (faulty (car (cadddr args)))) ; I won't do it again, I promise.
1034 (format port "~a: ~s" message faulty)))
1035
e7b2efd5
LC
1036 (define (getaddrinfo-error-printer port key args default-printer)
1037 (format port "In procedure getaddrinfo: ~a" (gai-strerror (car args))))
1038
40b91dc8
AW
1039 (set-exception-printer! 'goops-error scm-error-printer)
1040 (set-exception-printer! 'host-not-found scm-error-printer)
4af0d97e 1041 (set-exception-printer! 'keyword-argument-error keyword-error-printer)
40b91dc8
AW
1042 (set-exception-printer! 'misc-error scm-error-printer)
1043 (set-exception-printer! 'no-data scm-error-printer)
1044 (set-exception-printer! 'no-recovery scm-error-printer)
1045 (set-exception-printer! 'null-pointer-error scm-error-printer)
1046 (set-exception-printer! 'out-of-range scm-error-printer)
1047 (set-exception-printer! 'program-error scm-error-printer)
1048 (set-exception-printer! 'read-error scm-error-printer)
1049 (set-exception-printer! 'regular-expression-syntax scm-error-printer)
1050 (set-exception-printer! 'signal scm-error-printer)
1051 (set-exception-printer! 'stack-overflow scm-error-printer)
1052 (set-exception-printer! 'system-error scm-error-printer)
1053 (set-exception-printer! 'try-again scm-error-printer)
1054 (set-exception-printer! 'unbound-variable scm-error-printer)
1055 (set-exception-printer! 'wrong-number-of-args scm-error-printer)
1056 (set-exception-printer! 'wrong-type-arg scm-error-printer)
1057
e7b2efd5
LC
1058 (set-exception-printer! 'syntax-error syntax-error-printer)
1059
1060 (set-exception-printer! 'getaddrinfo-error getaddrinfo-error-printer))
40b91dc8
AW
1061
1062
1063\f
1064
3d2ada2f
DH
1065;;; {Defmacros}
1066;;;
3d2ada2f 1067
13182603
AW
1068(define-syntax define-macro
1069 (lambda (x)
97ce9dbf 1070 "Define a defmacro."
13182603 1071 (syntax-case x ()
97ce9dbf 1072 ((_ (macro . args) doc body1 body ...)
a927454d
AW
1073 (string? (syntax->datum #'doc))
1074 #'(define-macro macro doc (lambda args body1 body ...)))
97ce9dbf 1075 ((_ (macro . args) body ...)
a927454d 1076 #'(define-macro macro #f (lambda args body ...)))
10a467f3
AW
1077 ((_ macro transformer)
1078 #'(define-macro macro #f transformer))
97ce9dbf 1079 ((_ macro doc transformer)
a927454d
AW
1080 (or (string? (syntax->datum #'doc))
1081 (not (syntax->datum #'doc)))
1082 #'(define-syntax macro
1083 (lambda (y)
1084 doc
a5e95abe
AW
1085 #((macro-type . defmacro)
1086 (defmacro-args args))
a927454d
AW
1087 (syntax-case y ()
1088 ((_ . args)
1089 (let ((v (syntax->datum #'args)))
1090 (datum->syntax y (apply transformer v)))))))))))
13182603
AW
1091
1092(define-syntax defmacro
1093 (lambda (x)
97ce9dbf 1094 "Define a defmacro, with the old lispy defun syntax."
13182603 1095 (syntax-case x ()
97ce9dbf 1096 ((_ macro args doc body1 body ...)
a927454d
AW
1097 (string? (syntax->datum #'doc))
1098 #'(define-macro macro doc (lambda args body1 body ...)))
97ce9dbf 1099 ((_ macro args body ...)
a927454d 1100 #'(define-macro macro #f (lambda args body ...))))))
3d2ada2f
DH
1101
1102(provide 'defmacro)
48fdec21
MV
1103
1104\f
1105
3d2ada2f
DH
1106;;; {Deprecation}
1107;;;
3d2ada2f 1108
ec0f307e
AW
1109(define-syntax begin-deprecated
1110 (lambda (x)
1111 (syntax-case x ()
1112 ((_ form form* ...)
1113 (if (include-deprecated-features)
1114 #'(begin form form* ...)
1115 #'(begin))))))
0f2d19dd
JB
1116
1117\f
3d2ada2f 1118
79451588 1119;;; {Trivial Functions}
0f2d19dd 1120;;;
79451588 1121
6b08d75b 1122(define (identity x) x)
18f06db9
LC
1123
1124(define (compose proc . rest)
1125 "Compose PROC with the procedures in REST, such that the last one in
1126REST is applied first and PROC last, and return the resulting procedure.
1127The given procedures must have compatible arity."
1128 (if (null? rest)
1129 proc
1130 (let ((g (apply compose rest)))
1131 (lambda args
1132 (call-with-values (lambda () (apply g args)) proc)))))
1133
1134(define (negate proc)
1135 "Return a procedure with the same arity as PROC that returns the `not'
1136of PROC's result."
1137 (lambda args
1138 (not (apply proc args))))
1139
1140(define (const value)
1141 "Return a procedure that accepts any number of arguments and returns
1142VALUE."
1143 (lambda _
1144 value))
1145
8cd109bf
LC
1146(define (and=> value procedure)
1147 "When VALUE is #f, return #f. Otherwise, return (PROC VALUE)."
1148 (and value (procedure value)))
1149
e8ed460e 1150(define call/cc call-with-current-continuation)
79451588 1151
dfd1d3b1
AW
1152(define-syntax false-if-exception
1153 (syntax-rules ()
1154 ((false-if-exception expr)
1155 (catch #t
1156 (lambda () expr)
1157 (lambda args #f)))
1158 ((false-if-exception expr #:warning template arg ...)
1159 (catch #t
1160 (lambda () expr)
1161 (lambda (key . args)
1162 (for-each (lambda (s)
1163 (if (not (string-null? s))
1164 (format (current-warning-port) ";;; ~a\n" s)))
1165 (string-split
1166 (call-with-output-string
1167 (lambda (port)
1168 (format port template arg ...)
1169 (print-exception port #f key args)))
1170 #\newline))
1171 #f)))))
3d2ada2f
DH
1172
1173\f
1174
1175;;; {General Properties}
1176;;;
1177
02b582ce
AW
1178;; Properties are a lispy way to associate random info with random objects.
1179;; Traditionally properties are implemented as an alist or a plist actually
1180;; pertaining to the object in question.
1181;;
1182;; These "object properties" have the advantage that they can be associated with
1183;; any object, even if the object has no plist. Object properties are good when
1184;; you are extending pre-existing objects in unexpected ways. They also present
1185;; a pleasing, uniform procedure-with-setter interface. But if you have a data
1186;; type that always has properties, it's often still best to store those
1187;; properties within the object itself.
3d2ada2f
DH
1188
1189(define (make-object-property)
633f3a18
AW
1190 ;; Weak tables are thread-safe.
1191 (let ((prop (make-weak-key-hash-table)))
3d2ada2f 1192 (make-procedure-with-setter
633f3a18
AW
1193 (lambda (obj) (hashq-ref prop obj))
1194 (lambda (obj val) (hashq-set! prop obj val)))))
79488112 1195
3d2ada2f 1196
0f2d19dd 1197\f
6b08d75b 1198
0f2d19dd
JB
1199;;; {Symbol Properties}
1200;;;
1201
02b582ce
AW
1202;;; Symbol properties are something you see in old Lisp code. In most current
1203;;; Guile code, symbols are not used as a data structure -- they are used as
1204;;; keys into other data structures.
1205
0f2d19dd
JB
1206(define (symbol-property sym prop)
1207 (let ((pair (assoc prop (symbol-pref sym))))
1208 (and pair (cdr pair))))
1209
1210(define (set-symbol-property! sym prop val)
1211 (let ((pair (assoc prop (symbol-pref sym))))
1212 (if pair
9b5a0d84
AW
1213 (set-cdr! pair val)
1214 (symbol-pset! sym (acons prop val (symbol-pref sym))))))
0f2d19dd
JB
1215
1216(define (symbol-property-remove! sym prop)
1217 (let ((pair (assoc prop (symbol-pref sym))))
1218 (if pair
9b5a0d84 1219 (symbol-pset! sym (delq! pair (symbol-pref sym))))))
0f2d19dd
JB
1220
1221\f
1e531c3a 1222
0f2d19dd
JB
1223;;; {Arrays}
1224;;;
1225
2042e178
MV
1226(define (array-shape a)
1227 (map (lambda (ind) (if (number? ind) (list 0 (+ -1 ind)) ind))
1228 (array-dimensions a)))
0f2d19dd
JB
1229
1230\f
3d2ada2f 1231
0f2d19dd
JB
1232;;; {Keywords}
1233;;;
1234
010b159f
AW
1235;;; It's much better if you can use lambda* / define*, of course.
1236
0f2d19dd
JB
1237(define (kw-arg-ref args kw)
1238 (let ((rem (member kw args)))
1239 (and rem (pair? (cdr rem)) (cadr rem))))
1240
1241\f
fa7e9274 1242
746065c9
AW
1243;;; {IOTA functions: generating lists of numbers}
1244;;;
1245
1246(define (iota n)
1247 (let loop ((count (1- n)) (result '()))
1248 (if (< count 0) result
1249 (loop (1- count) (cons count result)))))
1250
1251\f
1252
9f9aa47b 1253;;; {Structs}
3d2ada2f 1254;;;
fa7e9274
MV
1255
1256(define (struct-layout s)
9f9aa47b 1257 (struct-ref (struct-vtable s) vtable-index-layout))
fa7e9274
MV
1258
1259\f
d7faeb2e 1260
0f2d19dd
JB
1261;;; {Records}
1262;;;
1263
fa7e9274
MV
1264;; Printing records: by default, records are printed as
1265;;
1266;; #<type-name field1: val1 field2: val2 ...>
1267;;
1268;; You can change that by giving a custom printing function to
1269;; MAKE-RECORD-TYPE (after the list of field symbols). This function
1270;; will be called like
1271;;
1272;; (<printer> object port)
1273;;
1274;; It should print OBJECT to PORT.
1275
cf8f1a90 1276(define (inherit-print-state old-port new-port)
8a30733e
MD
1277 (if (get-print-state old-port)
1278 (port-with-print-state new-port (get-print-state old-port))
cf8f1a90
MV
1279 new-port))
1280
e31f22eb 1281;; 0: type-name, 1: fields, 2: constructor
20edfbbd 1282(define record-type-vtable
f7bbc75d
AW
1283 (let ((s (make-vtable (string-append standard-vtable-fields "prprpw")
1284 (lambda (s p)
1285 (display "#<record-type " p)
1286 (display (record-type-name s) p)
1287 (display ">" p)))))
1288 (set-struct-vtable-name! s 'record-type)
1289 s))
0f2d19dd
JB
1290
1291(define (record-type? obj)
1292 (and (struct? obj) (eq? record-type-vtable (struct-vtable obj))))
1293
b2669c41 1294(define* (make-record-type type-name fields #:optional printer)
31ac29b6 1295 ;; Pre-generate constructors for nfields < 20.
e31f22eb
AW
1296 (define-syntax make-constructor
1297 (lambda (x)
1298 (define *max-static-argument-count* 20)
1299 (define (make-formals n)
1300 (let lp ((i 0))
1301 (if (< i n)
1302 (cons (datum->syntax
1303 x
1304 (string->symbol
1305 (string (integer->char (+ (char->integer #\a) i)))))
1306 (lp (1+ i)))
1307 '())))
1308 (syntax-case x ()
1309 ((_ rtd exp) (not (identifier? #'exp))
1310 #'(let ((n exp))
1311 (make-constructor rtd n)))
1312 ((_ rtd nfields)
1313 #`(case nfields
1314 #,@(let lp ((n 0))
1315 (if (< n *max-static-argument-count*)
1316 (cons (with-syntax (((formal ...) (make-formals n))
746065c9 1317 ((idx ...) (iota n))
e31f22eb
AW
1318 (n n))
1319 #'((n)
1320 (lambda (formal ...)
746065c9
AW
1321 (let ((s (allocate-struct rtd n)))
1322 (struct-set! s idx formal)
1323 ...
1324 s))))
e31f22eb
AW
1325 (lp (1+ n)))
1326 '()))
1327 (else
1328 (lambda args
1329 (if (= (length args) nfields)
1330 (apply make-struct rtd 0 args)
1331 (scm-error 'wrong-number-of-args
1332 (format #f "make-~a" type-name)
1333 "Wrong number of arguments" '() #f)))))))))
1334
51797cec
AW
1335 (define (default-record-printer s p)
1336 (display "#<" p)
1337 (display (record-type-name (record-type-descriptor s)) p)
1338 (let loop ((fields (record-type-fields (record-type-descriptor s)))
1339 (off 0))
1340 (cond
1341 ((not (null? fields))
1342 (display " " p)
1343 (display (car fields) p)
1344 (display ": " p)
1345 (display (struct-ref s off) p)
1346 (loop (cdr fields) (+ 1 off)))))
1347 (display ">" p))
1348
e31f22eb
AW
1349 (let ((rtd (make-struct record-type-vtable 0
1350 (make-struct-layout
1351 (apply string-append
1352 (map (lambda (f) "pw") fields)))
b2669c41 1353 (or printer default-record-printer)
e31f22eb
AW
1354 type-name
1355 (copy-tree fields))))
1356 (struct-set! rtd (+ vtable-offset-user 2)
1357 (make-constructor rtd (length fields)))
51797cec
AW
1358 ;; Temporary solution: Associate a name to the record type descriptor
1359 ;; so that the object system can create a wrapper class for it.
e31f22eb
AW
1360 (set-struct-vtable-name! rtd (if (symbol? type-name)
1361 type-name
1362 (string->symbol type-name)))
1363 rtd))
0f2d19dd
JB
1364
1365(define (record-type-name obj)
1366 (if (record-type? obj)
9f9aa47b 1367 (struct-ref obj vtable-offset-user)
0f2d19dd
JB
1368 (error 'not-a-record-type obj)))
1369
1370(define (record-type-fields obj)
1371 (if (record-type? obj)
9f9aa47b 1372 (struct-ref obj (+ 1 vtable-offset-user))
0f2d19dd
JB
1373 (error 'not-a-record-type obj)))
1374
d44a0d12
AW
1375(define* (record-constructor rtd #:optional field-names)
1376 (if (not field-names)
e31f22eb 1377 (struct-ref rtd (+ 2 vtable-offset-user))
d44a0d12
AW
1378 (primitive-eval
1379 `(lambda ,field-names
1380 (make-struct ',rtd 0 ,@(map (lambda (f)
1381 (if (memq f field-names)
1382 f
1383 #f))
1384 (record-type-fields rtd)))))))
3bf27608 1385
0f2d19dd
JB
1386(define (record-predicate rtd)
1387 (lambda (obj) (and (struct? obj) (eq? rtd (struct-vtable obj)))))
1388
3ba9acb1 1389(define (%record-type-error rtd obj) ;; private helper
afc4ccd4
KR
1390 (or (eq? rtd (record-type-descriptor obj))
1391 (scm-error 'wrong-type-arg "%record-type-check"
9b5a0d84
AW
1392 "Wrong type record (want `~S'): ~S"
1393 (list (record-type-name rtd) obj)
1394 #f)))
afc4ccd4 1395
0f2d19dd 1396(define (record-accessor rtd field-name)
3bf27608 1397 (let ((pos (list-index (record-type-fields rtd) field-name)))
0f2d19dd 1398 (if (not pos)
9b5a0d84 1399 (error 'no-such-field field-name))
3bf27608
AW
1400 (lambda (obj)
1401 (if (eq? (struct-vtable obj) rtd)
1402 (struct-ref obj pos)
1403 (%record-type-error rtd obj)))))
0f2d19dd
JB
1404
1405(define (record-modifier rtd field-name)
3bf27608 1406 (let ((pos (list-index (record-type-fields rtd) field-name)))
0f2d19dd 1407 (if (not pos)
9b5a0d84 1408 (error 'no-such-field field-name))
3bf27608
AW
1409 (lambda (obj val)
1410 (if (eq? (struct-vtable obj) rtd)
1411 (struct-set! obj pos val)
1412 (%record-type-error rtd obj)))))
0f2d19dd
JB
1413
1414(define (record? obj)
1415 (and (struct? obj) (record-type? (struct-vtable obj))))
1416
1417(define (record-type-descriptor obj)
1418 (if (struct? obj)
1419 (struct-vtable obj)
1420 (error 'not-a-record obj)))
1421
21ed9efe
MD
1422(provide 'record)
1423
124bc316
AW
1424
1425\f
1426;;; {Parameters}
1427;;;
1428
1429(define <parameter>
1430 ;; Three fields: the procedure itself, the fluid, and the converter.
1431 (make-struct <applicable-struct-vtable> 0 'pwprpr))
1432(set-struct-vtable-name! <parameter> '<parameter>)
1433
1434(define* (make-parameter init #:optional (conv (lambda (x) x)))
747bd534
AW
1435 "Make a new parameter.
1436
1437A parameter is a dynamically bound value, accessed through a procedure.
1438To access the current value, apply the procedure with no arguments:
1439
1440 (define p (make-parameter 10))
1441 (p) => 10
1442
1443To provide a new value for the parameter in a dynamic extent, use
1444`parameterize':
1445
1446 (parameterize ((p 20))
1447 (p)) => 20
1448 (p) => 10
1449
1450The value outside of the dynamic extent of the body is unaffected. To
1451update the current value, apply it to one argument:
1452
1453 (p 20) => 10
1454 (p) => 20
1455
1456As you can see, the call that updates a parameter returns its previous
1457value.
1458
1459All values for the parameter are first run through the CONV procedure,
1460including INIT, the initial value. The default CONV procedure is the
1461identity procedure. CONV is commonly used to ensure some set of
1462invariants on the values that a parameter may have."
124bc316
AW
1463 (let ((fluid (make-fluid (conv init))))
1464 (make-struct <parameter> 0
1465 (case-lambda
1466 (() (fluid-ref fluid))
1467 ((x) (let ((prev (fluid-ref fluid)))
1468 (fluid-set! fluid (conv x))
1469 prev)))
1470 fluid conv)))
1471
1472(define (parameter? x)
1473 (and (struct? x) (eq? (struct-vtable x) <parameter>)))
1474
1475(define (parameter-fluid p)
1476 (if (parameter? p)
1477 (struct-ref p 1)
1478 (scm-error 'wrong-type-arg "parameter-fluid"
1479 "Not a parameter: ~S" (list p) #f)))
1480
1481(define (parameter-converter p)
1482 (if (parameter? p)
1483 (struct-ref p 2)
1484 (scm-error 'wrong-type-arg "parameter-fluid"
1485 "Not a parameter: ~S" (list p) #f)))
1486
1487(define-syntax parameterize
1488 (lambda (x)
1489 (syntax-case x ()
1490 ((_ ((param value) ...) body body* ...)
1491 (with-syntax (((p ...) (generate-temporaries #'(param ...))))
1492 #'(let ((p param) ...)
1493 (if (not (parameter? p))
1494 (scm-error 'wrong-type-arg "parameterize"
1495 "Not a parameter: ~S" (list p) #f))
1496 ...
1497 (with-fluids (((struct-ref p 1) ((struct-ref p 2) value))
1498 ...)
1499 body body* ...)))))))
1500
747bd534
AW
1501(define* (fluid->parameter fluid #:optional (conv (lambda (x) x)))
1502 "Make a parameter that wraps a fluid.
1503
1504The value of the parameter will be the same as the value of the fluid.
1505If the parameter is rebound in some dynamic extent, perhaps via
1506`parameterize', the new value will be run through the optional CONV
1507procedure, as with any parameter. Note that unlike `make-parameter',
1508CONV is not applied to the initial value."
1509 (make-struct <parameter> 0
1510 (case-lambda
1511 (() (fluid-ref fluid))
1512 ((x) (let ((prev (fluid-ref fluid)))
1513 (fluid-set! fluid (conv x))
1514 prev)))
1515 fluid conv))
1516
124bc316
AW
1517\f
1518
283ab48d
AW
1519;;; Once parameters have booted, define the default prompt tag as being
1520;;; a parameter.
1521;;;
1522
1523(set! default-prompt-tag (make-parameter (default-prompt-tag)))
1524
1525\f
1526
124bc316
AW
1527;;; Current ports as parameters.
1528;;;
1529
747bd534 1530(let ()
124bc316
AW
1531 (define-syntax-rule (port-parameterize! binding fluid predicate msg)
1532 (begin
1533 (set! binding (fluid->parameter (module-ref (current-module) 'fluid)
1534 (lambda (x)
1535 (if (predicate x) x
1536 (error msg x)))))
1537 (hashq-remove! (%get-pre-modules-obarray) 'fluid)))
1538
1539 (port-parameterize! current-input-port %current-input-port-fluid
1540 input-port? "expected an input port")
1541 (port-parameterize! current-output-port %current-output-port-fluid
1542 output-port? "expected an output port")
1543 (port-parameterize! current-error-port %current-error-port-fluid
1544 output-port? "expected an output port"))
1545
1546\f
1547
1548;;; {Warnings}
1549;;;
1550
1551(define current-warning-port
1552 (make-parameter (current-error-port)
1553 (lambda (x)
1554 (if (output-port? x)
1555 x
1556 (error "expected an output port" x)))))
1557
747bd534
AW
1558
1559\f
1560
1561;;; {Languages}
1562;;;
1563
1564;; The language can be a symbolic name or a <language> object from
1565;; (system base language).
1566;;
1567(define current-language (make-parameter 'scheme))
1568
1569
0f2d19dd 1570\f
3d2ada2f 1571
f6e6b518
AW
1572;;; {High-Level Port Routines}
1573;;;
1574
f6f4feb0
MW
1575(define* (open-input-file
1576 file #:key (binary #f) (encoding #f) (guess-encoding #f))
1577 "Takes a string naming an existing file and returns an input port
1578capable of delivering characters from the file. If the file
1579cannot be opened, an error is signalled."
1580 (open-file file (if binary "rb" "r")
1581 #:encoding encoding
1582 #:guess-encoding guess-encoding))
1583
1584(define* (open-output-file file #:key (binary #f) (encoding #f))
1585 "Takes a string naming an output file to be created and returns an
1586output port capable of writing characters to a new file by that
1587name. If the file cannot be opened, an error is signalled. If a
1588file with the given name already exists, the effect is unspecified."
1589 (open-file file (if binary "wb" "w")
1590 #:encoding encoding))
1591
1592(define* (call-with-input-file
1593 file proc #:key (binary #f) (encoding #f) (guess-encoding #f))
1594 "PROC should be a procedure of one argument, and FILE should be a
1595string naming a file. The file must
1596already exist. These procedures call PROC
1597with one argument: the port obtained by opening the named file for
1598input or output. If the file cannot be opened, an error is
f6e6b518 1599signalled. If the procedure returns, then the port is closed
f6f4feb0
MW
1600automatically and the values yielded by the procedure are returned.
1601If the procedure does not return, then the port will not be closed
1602automatically unless it is possible to prove that the port will
1603never again be used for a read or write operation."
1604 (let ((p (open-input-file file
1605 #:binary binary
1606 #:encoding encoding
1607 #:guess-encoding guess-encoding)))
f6e6b518
AW
1608 (call-with-values
1609 (lambda () (proc p))
1610 (lambda vals
1611 (close-input-port p)
1612 (apply values vals)))))
1613
f6f4feb0
MW
1614(define* (call-with-output-file file proc #:key (binary #f) (encoding #f))
1615 "PROC should be a procedure of one argument, and FILE should be a
1616string naming a file. The behaviour is unspecified if the file
f6e6b518
AW
1617already exists. These procedures call PROC
1618with one argument: the port obtained by opening the named file for
1619input or output. If the file cannot be opened, an error is
1620signalled. If the procedure returns, then the port is closed
1621automatically and the values yielded by the procedure are returned.
1622If the procedure does not return, then the port will not be closed
1623automatically unless it is possible to prove that the port will
1624never again be used for a read or write operation."
f6f4feb0 1625 (let ((p (open-output-file file #:binary binary #:encoding encoding)))
f6e6b518
AW
1626 (call-with-values
1627 (lambda () (proc p))
1628 (lambda vals
1629 (close-output-port p)
1630 (apply values vals)))))
1631
1632(define (with-input-from-port port thunk)
1633 (parameterize ((current-input-port port))
1634 (thunk)))
1635
1636(define (with-output-to-port port thunk)
1637 (parameterize ((current-output-port port))
1638 (thunk)))
1639
1640(define (with-error-to-port port thunk)
1641 (parameterize ((current-error-port port))
1642 (thunk)))
1643
f6f4feb0
MW
1644(define* (with-input-from-file
1645 file thunk #:key (binary #f) (encoding #f) (guess-encoding #f))
f6e6b518
AW
1646 "THUNK must be a procedure of no arguments, and FILE must be a
1647string naming a file. The file must already exist. The file is opened for
1648input, an input port connected to it is made
f6f4feb0 1649the default value returned by `current-input-port',
f6e6b518
AW
1650and the THUNK is called with no arguments.
1651When the THUNK returns, the port is closed and the previous
1652default is restored. Returns the values yielded by THUNK. If an
1653escape procedure is used to escape from the continuation of these
1654procedures, their behavior is implementation dependent."
1655 (call-with-input-file file
f6f4feb0
MW
1656 (lambda (p) (with-input-from-port p thunk))
1657 #:binary binary
1658 #:encoding encoding
1659 #:guess-encoding guess-encoding))
f6e6b518 1660
f6f4feb0 1661(define* (with-output-to-file file thunk #:key (binary #f) (encoding #f))
f6e6b518 1662 "THUNK must be a procedure of no arguments, and FILE must be a
f6f4feb0 1663string naming a file. The effect is unspecified if the file already exists.
f6e6b518 1664The file is opened for output, an output port connected to it is made
f6f4feb0 1665the default value returned by `current-output-port',
f6e6b518
AW
1666and the THUNK is called with no arguments.
1667When the THUNK returns, the port is closed and the previous
1668default is restored. Returns the values yielded by THUNK. If an
1669escape procedure is used to escape from the continuation of these
1670procedures, their behavior is implementation dependent."
1671 (call-with-output-file file
f6f4feb0
MW
1672 (lambda (p) (with-output-to-port p thunk))
1673 #:binary binary
1674 #:encoding encoding))
f6e6b518 1675
f6f4feb0 1676(define* (with-error-to-file file thunk #:key (binary #f) (encoding #f))
f6e6b518 1677 "THUNK must be a procedure of no arguments, and FILE must be a
f6f4feb0 1678string naming a file. The effect is unspecified if the file already exists.
f6e6b518 1679The file is opened for output, an output port connected to it is made
f6f4feb0 1680the default value returned by `current-error-port',
f6e6b518
AW
1681and the THUNK is called with no arguments.
1682When the THUNK returns, the port is closed and the previous
1683default is restored. Returns the values yielded by THUNK. If an
1684escape procedure is used to escape from the continuation of these
1685procedures, their behavior is implementation dependent."
1686 (call-with-output-file file
f6f4feb0
MW
1687 (lambda (p) (with-error-to-port p thunk))
1688 #:binary binary
1689 #:encoding encoding))
f6e6b518 1690
a62b5c3d
AW
1691(define (call-with-input-string string proc)
1692 "Calls the one-argument procedure @var{proc} with a newly created
1693input port from which @var{string}'s contents may be read. The value
1694yielded by the @var{proc} is returned."
1695 (proc (open-input-string string)))
1696
f6e6b518
AW
1697(define (with-input-from-string string thunk)
1698 "THUNK must be a procedure of no arguments.
1699The test of STRING is opened for
1700input, an input port connected to it is made,
1701and the THUNK is called with no arguments.
1702When the THUNK returns, the port is closed.
1703Returns the values yielded by THUNK. If an
1704escape procedure is used to escape from the continuation of these
1705procedures, their behavior is implementation dependent."
1706 (call-with-input-string string
1707 (lambda (p) (with-input-from-port p thunk))))
1708
a62b5c3d
AW
1709(define (call-with-output-string proc)
1710 "Calls the one-argument procedure @var{proc} with a newly created output
1711port. When the function returns, the string composed of the characters
1712written into the port is returned."
1713 (let ((port (open-output-string)))
1714 (proc port)
1715 (get-output-string port)))
1716
f6e6b518
AW
1717(define (with-output-to-string thunk)
1718 "Calls THUNK and returns its output as a string."
1719 (call-with-output-string
1720 (lambda (p) (with-output-to-port p thunk))))
1721
1722(define (with-error-to-string thunk)
1723 "Calls THUNK and returns its error output as a string."
1724 (call-with-output-string
1725 (lambda (p) (with-error-to-port p thunk))))
1726
1727(define the-eof-object (call-with-input-string "" (lambda (p) (read-char p))))
1728
1729\f
1730
0f2d19dd
JB
1731;;; {Booleans}
1732;;;
1733
1734(define (->bool x) (not (not x)))
1735
1736\f
3d2ada2f 1737
0f2d19dd
JB
1738;;; {Symbols}
1739;;;
1740
1741(define (symbol-append . args)
06f0414c 1742 (string->symbol (apply string-append (map symbol->string args))))
0f2d19dd
JB
1743
1744(define (list->symbol . args)
1745 (string->symbol (apply list->string args)))
1746
1747(define (symbol . args)
1748 (string->symbol (apply string args)))
1749
0f2d19dd 1750\f
3d2ada2f 1751
0f2d19dd
JB
1752;;; {Lists}
1753;;;
1754
1755(define (list-index l k)
1756 (let loop ((n 0)
9b5a0d84 1757 (l l))
0f2d19dd 1758 (and (not (null? l))
9b5a0d84
AW
1759 (if (eq? (car l) k)
1760 n
1761 (loop (+ n 1) (cdr l))))))
0f2d19dd 1762
1729d8ff 1763\f
3d2ada2f 1764
073167ef
LC
1765;; Load `posix.scm' even when not (provided? 'posix) so that we get the
1766;; `stat' accessors.
1767(primitive-load-path "ice-9/posix")
6fa8995c 1768
52cfc69b 1769(if (provided? 'socket)
1e6ebf54 1770 (primitive-load-path "ice-9/networking"))
3afb28ce 1771
f3197274 1772;; For reference, Emacs file-exists-p uses stat in this same way.
6fa8995c 1773(define file-exists?
52cfc69b 1774 (if (provided? 'posix)
6fa8995c 1775 (lambda (str)
9b5a0d84 1776 (->bool (stat str #f)))
6fa8995c 1777 (lambda (str)
d867c749 1778 (let ((port (catch 'system-error (lambda () (open-input-file str))
9b5a0d84
AW
1779 (lambda args #f))))
1780 (if port (begin (close-port port) #t)
1781 #f)))))
6fa8995c
GH
1782
1783(define file-is-directory?
52cfc69b 1784 (if (provided? 'posix)
6fa8995c 1785 (lambda (str)
9b5a0d84 1786 (eq? (stat:type (stat str)) 'directory))
6fa8995c 1787 (lambda (str)
9b5a0d84 1788 (let ((port (catch 'system-error
d867c749
AW
1789 (lambda ()
1790 (open-input-file (string-append str "/.")))
9b5a0d84
AW
1791 (lambda args #f))))
1792 (if port (begin (close-port port) #t)
1793 #f)))))
0f2d19dd 1794
019ac1c9
MV
1795(define (system-error-errno args)
1796 (if (eq? (car args) 'system-error)
1797 (car (list-ref args 4))
1798 #f))
1799
0f2d19dd 1800\f
3d2ada2f 1801
0f2d19dd
JB
1802;;; {Error Handling}
1803;;;
1804
4eeaf67c
AW
1805(define error
1806 (case-lambda
1807 (()
4eeaf67c
AW
1808 (scm-error 'misc-error #f "?" #f #f))
1809 ((message . args)
4eeaf67c
AW
1810 (let ((msg (string-join (cons "~A" (make-list (length args) "~S")))))
1811 (scm-error 'misc-error #f msg (cons message args) #f)))))
be2d2c70 1812
0f2d19dd 1813\f
bce074ee 1814
b38507c1
AW
1815;;; {Time Structures}
1816;;;
1817
708bf0f3
GH
1818(define (tm:sec obj) (vector-ref obj 0))
1819(define (tm:min obj) (vector-ref obj 1))
1820(define (tm:hour obj) (vector-ref obj 2))
1821(define (tm:mday obj) (vector-ref obj 3))
1822(define (tm:mon obj) (vector-ref obj 4))
1823(define (tm:year obj) (vector-ref obj 5))
1824(define (tm:wday obj) (vector-ref obj 6))
1825(define (tm:yday obj) (vector-ref obj 7))
1826(define (tm:isdst obj) (vector-ref obj 8))
1827(define (tm:gmtoff obj) (vector-ref obj 9))
1828(define (tm:zone obj) (vector-ref obj 10))
1829
1830(define (set-tm:sec obj val) (vector-set! obj 0 val))
1831(define (set-tm:min obj val) (vector-set! obj 1 val))
1832(define (set-tm:hour obj val) (vector-set! obj 2 val))
1833(define (set-tm:mday obj val) (vector-set! obj 3 val))
1834(define (set-tm:mon obj val) (vector-set! obj 4 val))
1835(define (set-tm:year obj val) (vector-set! obj 5 val))
1836(define (set-tm:wday obj val) (vector-set! obj 6 val))
1837(define (set-tm:yday obj val) (vector-set! obj 7 val))
1838(define (set-tm:isdst obj val) (vector-set! obj 8 val))
1839(define (set-tm:gmtoff obj val) (vector-set! obj 9 val))
1840(define (set-tm:zone obj val) (vector-set! obj 10 val))
1841
6afcd3b2
GH
1842(define (tms:clock obj) (vector-ref obj 0))
1843(define (tms:utime obj) (vector-ref obj 1))
1844(define (tms:stime obj) (vector-ref obj 2))
1845(define (tms:cutime obj) (vector-ref obj 3))
1846(define (tms:cstime obj) (vector-ref obj 4))
1847
b38507c1
AW
1848\f
1849
1850;;; {File Descriptors and Ports}
1851;;;
1852
1334c61a 1853(define file-position ftell)
52c9a338
AW
1854(define* (file-set-position port offset #:optional (whence SEEK_SET))
1855 (seek port offset whence))
8b13c6b3 1856
e38303a2
GH
1857(define (move->fdes fd/port fd)
1858 (cond ((integer? fd/port)
9b5a0d84
AW
1859 (dup->fdes fd/port fd)
1860 (close fd/port)
1861 fd)
1862 (else
1863 (primitive-move->fdes fd/port fd)
1864 (set-port-revealed! fd/port 1)
1865 fd/port)))
8b13c6b3
GH
1866
1867(define (release-port-handle port)
1868 (let ((revealed (port-revealed port)))
1869 (if (> revealed 0)
9b5a0d84 1870 (set-port-revealed! port (- revealed 1)))))
0f2d19dd 1871
02851b26
AW
1872(define dup->port
1873 (case-lambda
1874 ((port/fd mode)
1875 (fdopen (dup->fdes port/fd) mode))
1876 ((port/fd mode new-fd)
1877 (let ((port (fdopen (dup->fdes port/fd new-fd) mode)))
1878 (set-port-revealed! port 1)
1879 port))))
1880
1881(define dup->inport
1882 (case-lambda
1883 ((port/fd)
1884 (dup->port port/fd "r"))
1885 ((port/fd new-fd)
1886 (dup->port port/fd "r" new-fd))))
1887
1888(define dup->outport
1889 (case-lambda
1890 ((port/fd)
1891 (dup->port port/fd "w"))
1892 ((port/fd new-fd)
1893 (dup->port port/fd "w" new-fd))))
1894
1895(define dup
1896 (case-lambda
1897 ((port/fd)
1898 (if (integer? port/fd)
1899 (dup->fdes port/fd)
1900 (dup->port port/fd (port-mode port/fd))))
1901 ((port/fd new-fd)
1902 (if (integer? port/fd)
1903 (dup->fdes port/fd new-fd)
1904 (dup->port port/fd (port-mode port/fd) new-fd)))))
e38303a2
GH
1905
1906(define (duplicate-port port modes)
1907 (dup->port port modes))
1908
1909(define (fdes->inport fdes)
1910 (let loop ((rest-ports (fdes->ports fdes)))
1911 (cond ((null? rest-ports)
9b5a0d84
AW
1912 (let ((result (fdopen fdes "r")))
1913 (set-port-revealed! result 1)
1914 result))
1915 ((input-port? (car rest-ports))
1916 (set-port-revealed! (car rest-ports)
1917 (+ (port-revealed (car rest-ports)) 1))
1918 (car rest-ports))
1919 (else
1920 (loop (cdr rest-ports))))))
e38303a2
GH
1921
1922(define (fdes->outport fdes)
1923 (let loop ((rest-ports (fdes->ports fdes)))
1924 (cond ((null? rest-ports)
9b5a0d84
AW
1925 (let ((result (fdopen fdes "w")))
1926 (set-port-revealed! result 1)
1927 result))
1928 ((output-port? (car rest-ports))
1929 (set-port-revealed! (car rest-ports)
1930 (+ (port-revealed (car rest-ports)) 1))
1931 (car rest-ports))
1932 (else
1933 (loop (cdr rest-ports))))))
e38303a2
GH
1934
1935(define (port->fdes port)
1936 (set-port-revealed! port (+ (port-revealed port) 1))
1937 (fileno port))
1938
956055a9
GH
1939(define (setenv name value)
1940 (if value
1941 (putenv (string-append name "=" value))
1942 (putenv name)))
1943
5c1254da
MV
1944(define (unsetenv name)
1945 "Remove the entry for NAME from the environment."
1946 (putenv name))
1947
0f2d19dd 1948\f
3d2ada2f 1949
0f2d19dd
JB
1950;;; {Load Paths}
1951;;;
1952
9b6316ea
AW
1953(let-syntax ((compile-time-case
1954 (lambda (stx)
1955 (syntax-case stx ()
1956 ((_ exp clauses ...)
1957 (let ((val (primitive-eval (syntax->datum #'exp))))
1958 (let next-clause ((clauses #'(clauses ...)))
1959 (syntax-case clauses (else)
1960 (()
1961 (syntax-violation 'compile-time-case
1962 "all clauses failed to match" stx))
1963 (((else form ...))
1964 #'(begin form ...))
1965 ((((k ...) form ...) clauses ...)
1966 (if (memv val (syntax->datum #'(k ...)))
1967 #'(begin form ...)
1968 (next-clause #'(clauses ...))))))))))))
1969 ;; emacs: (put 'compile-time-case 'scheme-indent-function 1)
1970 (compile-time-case (system-file-name-convention)
1971 ((posix)
1972 (define (file-name-separator? c)
1973 (char=? c #\/))
1974
1975 (define file-name-separator-string "/")
1976
1977 (define (absolute-file-name? file-name)
1978 (string-prefix? "/" file-name)))
1979
1980 ((windows)
1981 (define (file-name-separator? c)
1982 (or (char=? c #\/)
1983 (char=? c #\\)))
1984
1985 (define file-name-separator-string "\\")
1986
1987 (define (absolute-file-name? file-name)
65fa3923
AW
1988 (define (file-name-separator-at-index? idx)
1989 (and (> (string-length file-name) idx)
1990 (file-name-separator? (string-ref file-name idx))))
9b6316ea
AW
1991 (define (unc-file-name?)
1992 ;; Universal Naming Convention (UNC) file-names start with \\,
0725031f
AW
1993 ;; and are always absolute. See:
1994 ;; http://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx#fully_qualified_vs._relative_paths
65fa3923
AW
1995 (and (file-name-separator-at-index? 0)
1996 (file-name-separator-at-index? 1)))
9b6316ea
AW
1997 (define (has-drive-specifier?)
1998 (and (>= (string-length file-name) 2)
1999 (let ((drive (string-ref file-name 0)))
2000 (or (char<=? #\a drive #\z)
2001 (char<=? #\A drive #\Z)))
2002 (eqv? (string-ref file-name 1) #\:)))
9b6316ea
AW
2003 (or (unc-file-name?)
2004 (if (has-drive-specifier?)
2005 (file-name-separator-at-index? 2)
2006 (file-name-separator-at-index? 0)))))))
2007
3cab8392
JB
2008(define (in-vicinity vicinity file)
2009 (let ((tail (let ((len (string-length vicinity)))
9b5a0d84
AW
2010 (if (zero? len)
2011 #f
2012 (string-ref vicinity (- len 1))))))
3cab8392 2013 (string-append vicinity
9b6316ea 2014 (if (or (not tail) (file-name-separator? tail))
9b5a0d84 2015 ""
9b6316ea 2016 file-name-separator-string)
9b5a0d84 2017 file)))
02ceadb8 2018
0f2d19dd 2019\f
3d2ada2f 2020
ef00e7f4 2021;;; {Help for scm_shell}
3d2ada2f 2022;;;
ef00e7f4
JB
2023;;; The argument-processing code used by Guile-based shells generates
2024;;; Scheme code based on the argument list. This page contains help
2025;;; functions for the code it generates.
3d2ada2f 2026;;;
ef00e7f4 2027
ef00e7f4
JB
2028(define (command-line) (program-arguments))
2029
5aa7fe69
JB
2030;; This is mostly for the internal use of the code generated by
2031;; scm_compile_shell_switches.
eef6519b 2032
ef00e7f4 2033(define (load-user-init)
1f08acd9 2034 (let* ((home (or (getenv "HOME")
9b5a0d84 2035 (false-if-exception (passwd:dir (getpwuid (getuid))))
9b6316ea 2036 file-name-separator-string)) ;; fallback for cygwin etc.
9b5a0d84 2037 (init-file (in-vicinity home ".guile")))
1f08acd9 2038 (if (file-exists? init-file)
9b5a0d84 2039 (primitive-load init-file))))
ef00e7f4
JB
2040
2041\f
3d2ada2f 2042
107139ea
AW
2043;;; {The interpreter stack}
2044;;;
2045
06dcb9df 2046;; %stacks defined in stacks.c
a6cd3555 2047(define (%start-stack tag thunk)
8fc43b12
AW
2048 (let ((prompt-tag (make-prompt-tag "start-stack")))
2049 (call-with-prompt
2050 prompt-tag
2051 (lambda ()
2052 (with-fluids ((%stacks (acons tag prompt-tag
2053 (or (fluid-ref %stacks) '()))))
2054 (thunk)))
2055 (lambda (k . args)
52738540 2056 (%start-stack tag (lambda () (apply k args)))))))
0c65f52c
AW
2057
2058(define-syntax-rule (start-stack tag exp)
2059 (%start-stack tag (lambda () exp)))
107139ea
AW
2060
2061\f
2062
a06181a2 2063;;; {Loading by paths}
3d2ada2f 2064;;;
a06181a2
JB
2065
2066;;; Load a Scheme source file named NAME, searching for it in the
2067;;; directories listed in %load-path, and applying each of the file
2068;;; name extensions listed in %load-extensions.
2069(define (load-from-path name)
2070 (start-stack 'load-stack
9b5a0d84 2071 (primitive-load-path name)))
0f2d19dd 2072
925172cf
AW
2073(define-syntax-rule (add-to-load-path elt)
2074 "Add ELT to Guile's load path, at compile-time and at run-time."
f6ddf827 2075 (eval-when (expand load eval)
21ad60a1 2076 (set! %load-path (cons elt %load-path))))
925172cf 2077
85e95b47
AW
2078(define %load-verbosely #f)
2079(define (assert-load-verbosity v) (set! %load-verbosely v))
2080
2081(define (%load-announce file)
2082 (if %load-verbosely
2c27dd57 2083 (with-output-to-port (current-warning-port)
9b5a0d84
AW
2084 (lambda ()
2085 (display ";;; ")
2086 (display "loading ")
2087 (display file)
2088 (newline)
2089 (force-output)))))
85e95b47
AW
2090
2091(set! %load-hook %load-announce)
2092
0f2d19dd 2093\f
3d2ada2f 2094
0f2d19dd
JB
2095;;; {Reader Extensions}
2096;;;
0f2d19dd
JB
2097;;; Reader code for various "#c" forms.
2098;;;
2099
9447207f 2100(define read-eval? (make-fluid #f))
600c9584
RB
2101(read-hash-extend #\.
2102 (lambda (c port)
2103 (if (fluid-ref read-eval?)
2104 (eval (read port) (interaction-environment))
2105 (error
71335c0d 2106 "#. read expansion found and read-eval? is #f."))))
75a97b92 2107
0f2d19dd 2108\f
3d2ada2f 2109
0f2d19dd
JB
2110;;; {Low Level Modules}
2111;;;
2112;;; These are the low level data structures for modules.
2113;;;
37f5dfe5
DH
2114;;; Every module object is of the type 'module-type', which is a record
2115;;; consisting of the following members:
2116;;;
2de74cb5 2117;;; - eval-closure: A deprecated field, to be removed in Guile 2.2.
37f5dfe5
DH
2118;;;
2119;;; - obarray: a hash table that maps symbols to variable objects. In this
2120;;; hash table, the definitions are found that are local to the module (that
2121;;; is, not imported from other modules). When looking up bindings in the
2122;;; module, this hash table is searched first.
2123;;;
2124;;; - binder: either #f or a function taking a module and a symbol argument.
2125;;; If it is a function it is called after the obarray has been
2126;;; unsuccessfully searched for a binding. It then can provide bindings
2127;;; that would otherwise not be found locally in the module.
2128;;;
2129;;; - uses: a list of modules from which non-local bindings can be inherited.
2130;;; These modules are the third place queried for bindings after the obarray
2131;;; has been unsuccessfully searched and the binder function did not deliver
2132;;; a result either.
2133;;;
2134;;; - transformer: either #f or a function taking a scheme expression as
2135;;; delivered by read. If it is a function, it will be called to perform
2136;;; syntax transformations (e. g. makro expansion) on the given scheme
2137;;; expression. The output of the transformer function will then be passed
2138;;; to Guile's internal memoizer. This means that the output must be valid
2139;;; scheme code. The only exception is, that the output may make use of the
2140;;; syntax extensions provided to identify the modules that a binding
2141;;; belongs to.
2142;;;
2143;;; - name: the name of the module. This is used for all kinds of printing
2144;;; outputs. In certain places the module name also serves as a way of
2145;;; identification. When adding a module to the uses list of another
2146;;; module, it is made sure that the new uses list will not contain two
2147;;; modules of the same name.
2148;;;
2149;;; - kind: classification of the kind of module. The value is (currently?)
2150;;; only used for printing. It has no influence on how a module is treated.
2151;;; Currently the following values are used when setting the module kind:
2152;;; 'module, 'directory, 'interface, 'custom-interface. If no explicit kind
2153;;; is set, it defaults to 'module.
2154;;;
608860a5
LC
2155;;; - duplicates-handlers: a list of procedures that get called to make a
2156;;; choice between two duplicate bindings when name clashes occur. See the
2157;;; `duplicate-handlers' global variable below.
37f5dfe5 2158;;;
608860a5
LC
2159;;; - observers: a list of procedures that get called when the module is
2160;;; modified.
37f5dfe5 2161;;;
608860a5
LC
2162;;; - weak-observers: a weak-key hash table of procedures that get called
2163;;; when the module is modified. See `module-observe-weak' for details.
37f5dfe5
DH
2164;;;
2165;;; In addition, the module may (must?) contain a binding for
608860a5
LC
2166;;; `%module-public-interface'. This variable should be bound to a module
2167;;; representing the exported interface of a module. See the
2168;;; `module-public-interface' and `module-export!' procedures.
37f5dfe5 2169;;;
0f2d19dd
JB
2170;;; !!! warning: The interface to lazy binder procedures is going
2171;;; to be changed in an incompatible way to permit all the basic
2172;;; module ops to be virtualized.
2173;;;
2174;;; (make-module size use-list lazy-binding-proc) => module
2175;;; module-{obarray,uses,binder}[|-set!]
2176;;; (module? obj) => [#t|#f]
2177;;; (module-locally-bound? module symbol) => [#t|#f]
2178;;; (module-bound? module symbol) => [#t|#f]
2179;;; (module-symbol-locally-interned? module symbol) => [#t|#f]
2180;;; (module-symbol-interned? module symbol) => [#t|#f]
2181;;; (module-local-variable module symbol) => [#<variable ...> | #f]
2182;;; (module-variable module symbol) => [#<variable ...> | #f]
2183;;; (module-symbol-binding module symbol opt-value)
9b5a0d84 2184;;; => [ <obj> | opt-value | an error occurs ]
0f2d19dd
JB
2185;;; (module-make-local-var! module symbol) => #<variable...>
2186;;; (module-add! module symbol var) => unspecified
2187;;; (module-remove! module symbol) => unspecified
2188;;; (module-for-each proc module) => unspecified
2189;;; (make-scm-module) => module ; a lazy copy of the symhash module
2190;;; (set-current-module module) => unspecified
2191;;; (current-module) => #<module...>
2192;;;
2193;;;
2194
2195\f
3d2ada2f 2196
44cf1f0f 2197;;; {Printing Modules}
3d2ada2f
DH
2198;;;
2199
44cf1f0f 2200;; This is how modules are printed. You can re-define it.
31ac29b6 2201(define (%print-module mod port)
0f2d19dd
JB
2202 (display "#<" port)
2203 (display (or (module-kind mod) "module") port)
dc1eed52
AW
2204 (display " " port)
2205 (display (module-name mod) port)
0f2d19dd
JB
2206 (display " " port)
2207 (display (number->string (object-address mod) 16) port)
2208 (display ">" port))
2209
31ac29b6
AW
2210(letrec-syntax
2211 ;; Locally extend the syntax to allow record accessors to be defined at
2212 ;; compile-time. Cache the rtd locally to the constructor, the getters and
2213 ;; the setters, in order to allow for redefinition of the record type; not
2214 ;; relevant in the case of modules, but perhaps if we make this public, it
2215 ;; could matter.
2216
2217 ((define-record-type
2218 (lambda (x)
2219 (define (make-id scope . fragments)
49689a3f 2220 (datum->syntax scope
31ac29b6
AW
2221 (apply symbol-append
2222 (map (lambda (x)
2223 (if (symbol? x) x (syntax->datum x)))
2224 fragments))))
2225
2226 (define (getter rtd type-name field slot)
2227 #`(define #,(make-id rtd type-name '- field)
2228 (let ((rtd #,rtd))
2229 (lambda (#,type-name)
2230 (if (eq? (struct-vtable #,type-name) rtd)
2231 (struct-ref #,type-name #,slot)
2232 (%record-type-error rtd #,type-name))))))
2233
2234 (define (setter rtd type-name field slot)
2235 #`(define #,(make-id rtd 'set- type-name '- field '!)
2236 (let ((rtd #,rtd))
2237 (lambda (#,type-name val)
2238 (if (eq? (struct-vtable #,type-name) rtd)
2239 (struct-set! #,type-name #,slot val)
2240 (%record-type-error rtd #,type-name))))))
2241
2242 (define (accessors rtd type-name fields n exp)
2243 (syntax-case fields ()
2244 (() exp)
2245 (((field #:no-accessors) field* ...) (identifier? #'field)
2246 (accessors rtd type-name #'(field* ...) (1+ n)
2247 exp))
2248 (((field #:no-setter) field* ...) (identifier? #'field)
2249 (accessors rtd type-name #'(field* ...) (1+ n)
2250 #`(begin #,exp
2251 #,(getter rtd type-name #'field n))))
2252 (((field #:no-getter) field* ...) (identifier? #'field)
2253 (accessors rtd type-name #'(field* ...) (1+ n)
2254 #`(begin #,exp
2255 #,(setter rtd type-name #'field n))))
2256 ((field field* ...) (identifier? #'field)
2257 (accessors rtd type-name #'(field* ...) (1+ n)
2258 #`(begin #,exp
2259 #,(getter rtd type-name #'field n)
2260 #,(setter rtd type-name #'field n))))))
2261
2262 (define (predicate rtd type-name fields exp)
2263 (accessors
2264 rtd type-name fields 0
2265 #`(begin
2266 #,exp
2267 (define (#,(make-id rtd type-name '?) obj)
2268 (and (struct? obj) (eq? (struct-vtable obj) #,rtd))))))
2269
2270 (define (field-list fields)
2271 (syntax-case fields ()
2272 (() '())
2273 (((f . opts) . rest) (identifier? #'f)
2274 (cons #'f (field-list #'rest)))
2275 ((f . rest) (identifier? #'f)
2276 (cons #'f (field-list #'rest)))))
2277
2278 (define (constructor rtd type-name fields exp)
746065c9
AW
2279 (let* ((ctor (make-id rtd type-name '-constructor))
2280 (args (field-list fields))
2281 (n (length fields))
2282 (slots (iota n)))
31ac29b6
AW
2283 (predicate rtd type-name fields
2284 #`(begin #,exp
2285 (define #,ctor
2286 (let ((rtd #,rtd))
2287 (lambda #,args
746065c9
AW
2288 (let ((s (allocate-struct rtd #,n)))
2289 #,@(map
2290 (lambda (arg slot)
2291 #`(struct-set! s #,slot #,arg))
2292 args slots)
2293 s))))
31ac29b6
AW
2294 (struct-set! #,rtd (+ vtable-offset-user 2)
2295 #,ctor)))))
2296
2297 (define (type type-name printer fields)
2298 (define (make-layout)
2299 (let lp ((fields fields) (slots '()))
2300 (syntax-case fields ()
2301 (() (datum->syntax #'here
2302 (make-struct-layout
2303 (apply string-append slots))))
2304 ((_ . rest) (lp #'rest (cons "pw" slots))))))
2305
2306 (let ((rtd (make-id type-name type-name '-type)))
2307 (constructor rtd type-name fields
2308 #`(begin
2309 (define #,rtd
2310 (make-struct record-type-vtable 0
2311 '#,(make-layout)
2312 #,printer
2313 '#,type-name
2314 '#,(field-list fields)))
2315 (set-struct-vtable-name! #,rtd '#,type-name)))))
2316
2317 (syntax-case x ()
2318 ((_ type-name printer (field ...))
2319 (type #'type-name #'printer #'(field ...)))))))
2320
2321 ;; module-type
2322 ;;
2323 ;; A module is characterized by an obarray in which local symbols
2324 ;; are interned, a list of modules, "uses", from which non-local
2325 ;; bindings can be inherited, and an optional lazy-binder which
2326 ;; is a (CLOSURE module symbol) which, as a last resort, can provide
2327 ;; bindings that would otherwise not be found locally in the module.
2328 ;;
2329 ;; NOTE: If you change the set of fields or their order, you also need to
2330 ;; change the constants in libguile/modules.h.
2331 ;;
31ac29b6
AW
2332 ;; NOTE: The getter `module-transfomer' is defined libguile/modules.c.
2333 ;; NOTE: The getter `module-name' is defined later, due to boot reasons.
4e48b495 2334 ;; NOTE: The getter `module-public-interface' is used in libguile/modules.c.
31ac29b6
AW
2335 ;;
2336 (define-record-type module
2337 (lambda (obj port) (%print-module obj port))
2338 (obarray
2339 uses
2340 binder
2341 eval-closure
2342 (transformer #:no-getter)
2343 (name #:no-getter)
2344 kind
2345 duplicates-handlers
2346 (import-obarray #:no-setter)
2347 observers
2348 (weak-observers #:no-setter)
f905381d 2349 version
81fc66cf 2350 submodules
4e48b495 2351 submodule-binder
78f79f18
AW
2352 public-interface
2353 filename)))
31ac29b6 2354
0f2d19dd 2355
8b718458 2356;; make-module &opt size uses binder
0f2d19dd 2357;;
8b718458
JB
2358;; Create a new module, perhaps with a particular size of obarray,
2359;; initial uses list, or binding procedure.
0f2d19dd 2360;;
e9729cbb 2361(define* (make-module #:optional (size 31) (uses '()) (binder #f))
e9729cbb
AW
2362 (if (not (integer? size))
2363 (error "Illegal size to make-module." size))
2364 (if (not (and (list? uses)
2365 (and-map module? uses)))
2366 (error "Incorrect use list." uses))
2367 (if (and binder (not (procedure? binder)))
2368 (error
2369 "Lazy-binder expected to be a procedure or #f." binder))
2370
2de74cb5
AW
2371 (module-constructor (make-hash-table size)
2372 uses binder #f macroexpand
2373 #f #f #f
747747ee 2374 (make-hash-table)
2de74cb5
AW
2375 '()
2376 (make-weak-key-hash-table 31) #f
2377 (make-hash-table 7) #f #f #f))
0f2d19dd 2378
8b718458 2379
0f2d19dd 2380\f
3d2ada2f 2381
1777c18b
MD
2382;;; {Observer protocol}
2383;;;
2384
2385(define (module-observe module proc)
2386 (set-module-observers! module (cons proc (module-observers module)))
2387 (cons module proc))
2388
723ae5b3 2389(define* (module-observe-weak module observer-id #:optional (proc observer-id))
608860a5
LC
2390 ;; Register PROC as an observer of MODULE under name OBSERVER-ID (which can
2391 ;; be any Scheme object). PROC is invoked and passed MODULE any time
2392 ;; MODULE is modified. PROC gets unregistered when OBSERVER-ID gets GC'd
2393 ;; (thus, it is never unregistered if OBSERVER-ID is an immediate value,
2394 ;; for instance).
2395
2396 ;; The two-argument version is kept for backward compatibility: when called
2397 ;; with two arguments, the observer gets unregistered when closure PROC
2398 ;; gets GC'd (making it impossible to use an anonymous lambda for PROC).
723ae5b3 2399 (hashq-set! (module-weak-observers module) observer-id proc))
1777c18b
MD
2400
2401(define (module-unobserve token)
2402 (let ((module (car token))
9b5a0d84 2403 (id (cdr token)))
1777c18b 2404 (if (integer? id)
9b5a0d84
AW
2405 (hash-remove! (module-weak-observers module) id)
2406 (set-module-observers! module (delq1! id (module-observers module)))))
1777c18b
MD
2407 *unspecified*)
2408
d57da08b 2409(define module-defer-observers #f)
03d6cddc 2410(define module-defer-observers-mutex (make-mutex 'recursive))
d57da08b
MD
2411(define module-defer-observers-table (make-hash-table))
2412
1a961d7e 2413(define (module-modified m)
d57da08b
MD
2414 (if module-defer-observers
2415 (hash-set! module-defer-observers-table m #t)
2416 (module-call-observers m)))
2417
2418;;; This function can be used to delay calls to observers so that they
2419;;; can be called once only in the face of massive updating of modules.
2420;;;
2421(define (call-with-deferred-observers thunk)
2422 (dynamic-wind
2423 (lambda ()
9b5a0d84
AW
2424 (lock-mutex module-defer-observers-mutex)
2425 (set! module-defer-observers #t))
d57da08b
MD
2426 thunk
2427 (lambda ()
9b5a0d84
AW
2428 (set! module-defer-observers #f)
2429 (hash-for-each (lambda (m dummy)
2430 (module-call-observers m))
2431 module-defer-observers-table)
2432 (hash-clear! module-defer-observers-table)
2433 (unlock-mutex module-defer-observers-mutex))))
d57da08b
MD
2434
2435(define (module-call-observers m)
1777c18b 2436 (for-each (lambda (proc) (proc m)) (module-observers m))
608860a5
LC
2437
2438 ;; We assume that weak observers don't (un)register themselves as they are
2439 ;; called since this would preclude proper iteration over the hash table
2440 ;; elements.
2441 (hash-for-each (lambda (id proc) (proc m)) (module-weak-observers m)))
1777c18b
MD
2442
2443\f
3d2ada2f 2444
0f2d19dd
JB
2445;;; {Module Searching in General}
2446;;;
2447;;; We sometimes want to look for properties of a symbol
2448;;; just within the obarray of one module. If the property
2449;;; holds, then it is said to hold ``locally'' as in, ``The symbol
2450;;; DISPLAY is locally rebound in the module `safe-guile'.''
2451;;;
2452;;;
2453;;; Other times, we want to test for a symbol property in the obarray
2454;;; of M and, if it is not found there, try each of the modules in the
2455;;; uses list of M. This is the normal way of testing for some
2456;;; property, so we state these properties without qualification as
2457;;; in: ``The symbol 'fnord is interned in module M because it is
2458;;; interned locally in module M2 which is a member of the uses list
2459;;; of M.''
2460;;;
2461
2462;; module-search fn m
20edfbbd 2463;;
0f2d19dd
JB
2464;; return the first non-#f result of FN applied to M and then to
2465;; the modules in the uses of m, and so on recursively. If all applications
2466;; return #f, then so does this function.
2467;;
2468(define (module-search fn m v)
2469 (define (loop pos)
2470 (and (pair? pos)
9b5a0d84
AW
2471 (or (module-search fn (car pos) v)
2472 (loop (cdr pos)))))
0f2d19dd
JB
2473 (or (fn m v)
2474 (loop (module-uses m))))
2475
2476
2477;;; {Is a symbol bound in a module?}
2478;;;
2479;;; Symbol S in Module M is bound if S is interned in M and if the binding
2480;;; of S in M has been set to some well-defined value.
2481;;;
2482
2483;; module-locally-bound? module symbol
2484;;
2485;; Is a symbol bound (interned and defined) locally in a given module?
2486;;
2487(define (module-locally-bound? m v)
2488 (let ((var (module-local-variable m v)))
2489 (and var
9b5a0d84 2490 (variable-bound? var))))
0f2d19dd
JB
2491
2492;; module-bound? module symbol
2493;;
2494;; Is a symbol bound (interned and defined) anywhere in a given module
2495;; or its uses?
2496;;
2497(define (module-bound? m v)
f176c584
AW
2498 (let ((var (module-variable m v)))
2499 (and var
9b5a0d84 2500 (variable-bound? var))))
0f2d19dd
JB
2501
2502;;; {Is a symbol interned in a module?}
2503;;;
20edfbbd 2504;;; Symbol S in Module M is interned if S occurs in
0f2d19dd
JB
2505;;; of S in M has been set to some well-defined value.
2506;;;
2507;;; It is possible to intern a symbol in a module without providing
2508;;; an initial binding for the corresponding variable. This is done
2509;;; with:
2510;;; (module-add! module symbol (make-undefined-variable))
2511;;;
2512;;; In that case, the symbol is interned in the module, but not
2513;;; bound there. The unbound symbol shadows any binding for that
2514;;; symbol that might otherwise be inherited from a member of the uses list.
2515;;;
2516
2517(define (module-obarray-get-handle ob key)
2518 ((if (symbol? key) hashq-get-handle hash-get-handle) ob key))
2519
2520(define (module-obarray-ref ob key)
2521 ((if (symbol? key) hashq-ref hash-ref) ob key))
2522
2523(define (module-obarray-set! ob key val)
2524 ((if (symbol? key) hashq-set! hash-set!) ob key val))
2525
2526(define (module-obarray-remove! ob key)
2527 ((if (symbol? key) hashq-remove! hash-remove!) ob key))
2528
2529;; module-symbol-locally-interned? module symbol
20edfbbd 2530;;
0f2d19dd
JB
2531;; is a symbol interned (not neccessarily defined) locally in a given module
2532;; or its uses? Interned symbols shadow inherited bindings even if
2533;; they are not themselves bound to a defined value.
2534;;
2535(define (module-symbol-locally-interned? m v)
2536 (not (not (module-obarray-get-handle (module-obarray m) v))))
2537
2538;; module-symbol-interned? module symbol
20edfbbd 2539;;
0f2d19dd
JB
2540;; is a symbol interned (not neccessarily defined) anywhere in a given module
2541;; or its uses? Interned symbols shadow inherited bindings even if
2542;; they are not themselves bound to a defined value.
2543;;
2544(define (module-symbol-interned? m v)
2545 (module-search module-symbol-locally-interned? m v))
2546
2547
2548;;; {Mapping modules x symbols --> variables}
2549;;;
2550
2551;; module-local-variable module symbol
2552;; return the local variable associated with a MODULE and SYMBOL.
2553;;
2554;;; This function is very important. It is the only function that can
2555;;; return a variable from a module other than the mutators that store
2556;;; new variables in modules. Therefore, this function is the location
2557;;; of the "lazy binder" hack.
2558;;;
2559;;; If symbol is defined in MODULE, and if the definition binds symbol
2560;;; to a variable, return that variable object.
2561;;;
2562;;; If the symbols is not found at first, but the module has a lazy binder,
2563;;; then try the binder.
2564;;;
2565;;; If the symbol is not found at all, return #f.
2566;;;
608860a5
LC
2567;;; (This is now written in C, see `modules.c'.)
2568;;;
0f2d19dd
JB
2569
2570;;; {Mapping modules x symbols --> bindings}
2571;;;
2572;;; These are similar to the mapping to variables, except that the
2573;;; variable is dereferenced.
2574;;;
2575
2576;; module-symbol-binding module symbol opt-value
20edfbbd 2577;;
0f2d19dd
JB
2578;; return the binding of a variable specified by name within
2579;; a given module, signalling an error if the variable is unbound.
2580;; If the OPT-VALUE is passed, then instead of signalling an error,
2581;; return OPT-VALUE.
2582;;
2583(define (module-symbol-local-binding m v . opt-val)
2584 (let ((var (module-local-variable m v)))
7b07e5ef 2585 (if (and var (variable-bound? var))
9b5a0d84
AW
2586 (variable-ref var)
2587 (if (not (null? opt-val))
2588 (car opt-val)
2589 (error "Locally unbound variable." v)))))
0f2d19dd
JB
2590
2591;; module-symbol-binding module symbol opt-value
20edfbbd 2592;;
0f2d19dd
JB
2593;; return the binding of a variable specified by name within
2594;; a given module, signalling an error if the variable is unbound.
2595;; If the OPT-VALUE is passed, then instead of signalling an error,
2596;; return OPT-VALUE.
2597;;
2598(define (module-symbol-binding m v . opt-val)
2599 (let ((var (module-variable m v)))
7b07e5ef 2600 (if (and var (variable-bound? var))
9b5a0d84
AW
2601 (variable-ref var)
2602 (if (not (null? opt-val))
2603 (car opt-val)
2604 (error "Unbound variable." v)))))
0f2d19dd
JB
2605
2606
2607\f
3d2ada2f 2608
0f2d19dd
JB
2609;;; {Adding Variables to Modules}
2610;;;
0f2d19dd
JB
2611
2612;; module-make-local-var! module symbol
20edfbbd 2613;;
0f2d19dd
JB
2614;; ensure a variable for V in the local namespace of M.
2615;; If no variable was already there, then create a new and uninitialzied
2616;; variable.
2617;;
d57da08b
MD
2618;; This function is used in modules.c.
2619;;
0f2d19dd
JB
2620(define (module-make-local-var! m v)
2621 (or (let ((b (module-obarray-ref (module-obarray m) v)))
9b5a0d84
AW
2622 (and (variable? b)
2623 (begin
2624 ;; Mark as modified since this function is called when
2625 ;; the standard eval closure defines a binding
2626 (module-modified m)
2627 b)))
0c5f718b 2628
608860a5
LC
2629 ;; Create a new local variable.
2630 (let ((local-var (make-undefined-variable)))
2631 (module-add! m v local-var)
2632 local-var)))
0f2d19dd 2633
89d06712 2634;; module-ensure-local-variable! module symbol
9540368e 2635;;
89d06712
MV
2636;; Ensure that there is a local variable in MODULE for SYMBOL. If
2637;; there is no binding for SYMBOL, create a new uninitialized
2638;; variable. Return the local variable.
9540368e 2639;;
89d06712
MV
2640(define (module-ensure-local-variable! module symbol)
2641 (or (module-local-variable module symbol)
9540368e 2642 (let ((var (make-undefined-variable)))
9b5a0d84
AW
2643 (module-add! module symbol var)
2644 var)))
9540368e 2645
0f2d19dd 2646;; module-add! module symbol var
20edfbbd 2647;;
0f2d19dd
JB
2648;; ensure a particular variable for V in the local namespace of M.
2649;;
2650(define (module-add! m v var)
2651 (if (not (variable? var))
2652 (error "Bad variable to module-add!" var))
df3acd29
MW
2653 (if (not (symbol? v))
2654 (error "Bad symbol to module-add!" v))
1777c18b 2655 (module-obarray-set! (module-obarray m) v var)
1a961d7e 2656 (module-modified m))
0f2d19dd 2657
20edfbbd
TTN
2658;; module-remove!
2659;;
0f2d19dd
JB
2660;; make sure that a symbol is undefined in the local namespace of M.
2661;;
2662(define (module-remove! m v)
c35738c1 2663 (module-obarray-remove! (module-obarray m) v)
1a961d7e 2664 (module-modified m))
0f2d19dd
JB
2665
2666(define (module-clear! m)
c35738c1 2667 (hash-clear! (module-obarray m))
1a961d7e 2668 (module-modified m))
0f2d19dd
JB
2669
2670;; MODULE-FOR-EACH -- exported
20edfbbd 2671;;
0f2d19dd
JB
2672;; Call PROC on each symbol in MODULE, with arguments of (SYMBOL VARIABLE).
2673;;
2674(define (module-for-each proc module)
c35738c1 2675 (hash-for-each proc (module-obarray module)))
0f2d19dd
JB
2676
2677(define (module-map proc module)
711a9fd7 2678 (hash-map->list proc (module-obarray module)))
c35738c1 2679
0f27ab8a
AW
2680;; Submodules
2681;;
2682;; Modules exist in a separate namespace from values, because you generally do
2683;; not want the name of a submodule, which you might not even use, to collide
2684;; with local variables that happen to be named the same as the submodule.
2685;;
2686(define (module-ref-submodule module name)
81fc66cf
AW
2687 (or (hashq-ref (module-submodules module) name)
2688 (and (module-submodule-binder module)
2689 ((module-submodule-binder module) module name))))
0f27ab8a
AW
2690
2691(define (module-define-submodule! module name submodule)
f6a5308b 2692 (hashq-set! (module-submodules module) name submodule))
0f27ab8a 2693
0f2d19dd
JB
2694\f
2695
0f2d19dd
JB
2696;;; {Module-based Loading}
2697;;;
2698
2699(define (save-module-excursion thunk)
2700 (let ((inner-module (current-module))
9b5a0d84 2701 (outer-module #f))
0f2d19dd 2702 (dynamic-wind (lambda ()
9b5a0d84
AW
2703 (set! outer-module (current-module))
2704 (set-current-module inner-module)
2705 (set! inner-module #f))
2706 thunk
2707 (lambda ()
2708 (set! inner-module (current-module))
2709 (set-current-module outer-module)
2710 (set! outer-module #f)))))
0f2d19dd 2711
0f2d19dd 2712\f
3d2ada2f 2713
44cf1f0f 2714;;; {MODULE-REF -- exported}
3d2ada2f
DH
2715;;;
2716
0f2d19dd
JB
2717;; Returns the value of a variable called NAME in MODULE or any of its
2718;; used modules. If there is no such variable, then if the optional third
2719;; argument DEFAULT is present, it is returned; otherwise an error is signaled.
20edfbbd 2720;;
0f2d19dd
JB
2721(define (module-ref module name . rest)
2722 (let ((variable (module-variable module name)))
2723 (if (and variable (variable-bound? variable))
9b5a0d84
AW
2724 (variable-ref variable)
2725 (if (null? rest)
2726 (error "No variable named" name 'in module)
2727 (car rest) ; default value
2728 ))))
0f2d19dd
JB
2729
2730;; MODULE-SET! -- exported
2731;;
2732;; Sets the variable called NAME in MODULE (or in a module that MODULE uses)
2733;; to VALUE; if there is no such variable, an error is signaled.
20edfbbd 2734;;
0f2d19dd
JB
2735(define (module-set! module name value)
2736 (let ((variable (module-variable module name)))
2737 (if variable
9b5a0d84
AW
2738 (variable-set! variable value)
2739 (error "No variable named" name 'in module))))
0f2d19dd
JB
2740
2741;; MODULE-DEFINE! -- exported
2742;;
2743;; Sets the variable called NAME in MODULE to VALUE; if there is no such
2744;; variable, it is added first.
20edfbbd 2745;;
0f2d19dd
JB
2746(define (module-define! module name value)
2747 (let ((variable (module-local-variable module name)))
2748 (if variable
9b5a0d84
AW
2749 (begin
2750 (variable-set! variable value)
2751 (module-modified module))
2752 (let ((variable (make-variable value)))
2753 (module-add! module name variable)))))
0f2d19dd 2754
ed218d98
MV
2755;; MODULE-DEFINED? -- exported
2756;;
2757;; Return #t iff NAME is defined in MODULE (or in a module that MODULE
2758;; uses)
2759;;
2760(define (module-defined? module name)
2761 (let ((variable (module-variable module name)))
2762 (and variable (variable-bound? variable))))
2763
0f2d19dd
JB
2764;; MODULE-USE! module interface
2765;;
2766;; Add INTERFACE to the list of interfaces used by MODULE.
20edfbbd 2767;;
0f2d19dd 2768(define (module-use! module interface)
b1907902
AW
2769 (if (not (or (eq? module interface)
2770 (memq interface (module-uses module))))
608860a5
LC
2771 (begin
2772 ;; Newly used modules must be appended rather than consed, so that
2773 ;; `module-variable' traverses the use list starting from the first
2774 ;; used module.
51c0fd80
AR
2775 (set-module-uses! module (append (module-uses module)
2776 (list interface)))
8f44138a 2777 (hash-clear! (module-import-obarray module))
608860a5 2778 (module-modified module))))
0f2d19dd 2779
7b07e5ef
MD
2780;; MODULE-USE-INTERFACES! module interfaces
2781;;
8d795c83
AW
2782;; Same as MODULE-USE!, but only notifies module observers after all
2783;; interfaces are added to the inports list.
7b07e5ef
MD
2784;;
2785(define (module-use-interfaces! module interfaces)
8d795c83
AW
2786 (let* ((cur (module-uses module))
2787 (new (let lp ((in interfaces) (out '()))
2788 (if (null? in)
2789 (reverse out)
2790 (lp (cdr in)
2791 (let ((iface (car in)))
2792 (if (or (memq iface cur) (memq iface out))
2793 out
2794 (cons iface out))))))))
2795 (set-module-uses! module (append cur new))
4181e920
AW
2796 (hash-clear! (module-import-obarray module))
2797 (module-modified module)))
7b07e5ef 2798
0f2d19dd 2799\f
3d2ada2f 2800
0f2d19dd
JB
2801;;; {Recursive Namespaces}
2802;;;
0f2d19dd 2803;;; A hierarchical namespace emerges if we consider some module to be
b910c4ac 2804;;; root, and submodules of that module to be nested namespaces.
0f2d19dd 2805;;;
b910c4ac 2806;;; The routines here manage variable names in hierarchical namespace.
0f2d19dd
JB
2807;;; Each variable name is a list of elements, looked up in successively nested
2808;;; modules.
2809;;;
9b5a0d84 2810;;; (nested-ref some-root-module '(foo bar baz))
b910c4ac
AW
2811;;; => <value of a variable named baz in the submodule bar of
2812;;; the submodule foo of some-root-module>
0f2d19dd
JB
2813;;;
2814;;;
2815;;; There are:
2816;;;
9b5a0d84
AW
2817;;; ;; a-root is a module
2818;;; ;; name is a list of symbols
0f2d19dd 2819;;;
9b5a0d84
AW
2820;;; nested-ref a-root name
2821;;; nested-set! a-root name val
2822;;; nested-define! a-root name val
2823;;; nested-remove! a-root name
0f2d19dd 2824;;;
b910c4ac
AW
2825;;; These functions manipulate values in namespaces. For referencing the
2826;;; namespaces themselves, use the following:
0f2d19dd 2827;;;
b910c4ac
AW
2828;;; nested-ref-module a-root name
2829;;; nested-define-module! a-root name mod
2830;;;
2831;;; (current-module) is a natural choice for a root so for convenience there are
0f2d19dd
JB
2832;;; also:
2833;;;
b910c4ac
AW
2834;;; local-ref name == nested-ref (current-module) name
2835;;; local-set! name val == nested-set! (current-module) name val
2836;;; local-define name val == nested-define! (current-module) name val
2837;;; local-remove name == nested-remove! (current-module) name
2838;;; local-ref-module name == nested-ref-module (current-module) name
2839;;; local-define-module! name m == nested-define-module! (current-module) name m
0f2d19dd
JB
2840;;;
2841
2842
0dd5491c 2843(define (nested-ref root names)
b910c4ac
AW
2844 (if (null? names)
2845 root
2846 (let loop ((cur root)
2847 (head (car names))
2848 (tail (cdr names)))
2849 (if (null? tail)
2850 (module-ref cur head #f)
2851 (let ((cur (module-ref-submodule cur head)))
2852 (and cur
2853 (loop cur (car tail) (cdr tail))))))))
0f2d19dd 2854
0dd5491c 2855(define (nested-set! root names val)
0f2d19dd 2856 (let loop ((cur root)
b910c4ac
AW
2857 (head (car names))
2858 (tail (cdr names)))
2859 (if (null? tail)
2860 (module-set! cur head val)
2861 (let ((cur (module-ref-submodule cur head)))
2862 (if (not cur)
2863 (error "failed to resolve module" names)
2864 (loop cur (car tail) (cdr tail)))))))
0f2d19dd 2865
0dd5491c 2866(define (nested-define! root names val)
0f2d19dd 2867 (let loop ((cur root)
b910c4ac
AW
2868 (head (car names))
2869 (tail (cdr names)))
2870 (if (null? tail)
2871 (module-define! cur head val)
2872 (let ((cur (module-ref-submodule cur head)))
2873 (if (not cur)
2874 (error "failed to resolve module" names)
2875 (loop cur (car tail) (cdr tail)))))))
0f2d19dd 2876
0dd5491c 2877(define (nested-remove! root names)
0f2d19dd 2878 (let loop ((cur root)
b910c4ac
AW
2879 (head (car names))
2880 (tail (cdr names)))
2881 (if (null? tail)
2882 (module-remove! cur head)
2883 (let ((cur (module-ref-submodule cur head)))
2884 (if (not cur)
2885 (error "failed to resolve module" names)
2886 (loop cur (car tail) (cdr tail)))))))
2887
2888
2889(define (nested-ref-module root names)
2890 (let loop ((cur root)
2891 (names names))
2892 (if (null? names)
2893 cur
2894 (let ((cur (module-ref-submodule cur (car names))))
2895 (and cur
2896 (loop cur (cdr names)))))))
2897
2898(define (nested-define-module! root names module)
2899 (if (null? names)
2900 (error "can't redefine root module" root module)
2901 (let loop ((cur root)
2902 (head (car names))
2903 (tail (cdr names)))
2904 (if (null? tail)
2905 (module-define-submodule! cur head module)
2906 (let ((cur (or (module-ref-submodule cur head)
2907 (let ((m (make-module 31)))
2908 (set-module-kind! m 'directory)
2909 (set-module-name! m (append (module-name cur)
2910 (list head)))
2911 (module-define-submodule! cur head m)
2912 m))))
2913 (loop cur (car tail) (cdr tail)))))))
2914
0f2d19dd 2915
1623ca68
AW
2916(define (local-ref names)
2917 (nested-ref (current-module) names))
2918
2919(define (local-set! names val)
2920 (nested-set! (current-module) names val))
2921
2922(define (local-define names val)
2923 (nested-define! (current-module) names val))
2924
2925(define (local-remove names)
2926 (nested-remove! (current-module) names))
2927
2928(define (local-ref-module names)
2929 (nested-ref-module (current-module) names))
2930
2931(define (local-define-module names mod)
2932 (nested-define-module! (current-module) names mod))
b910c4ac 2933
0f2d19dd
JB
2934
2935
2936\f
3d2ada2f 2937
cb67c838 2938;;; {The (guile) module}
0f2d19dd 2939;;;
cb67c838
AW
2940;;; The standard module, which has the core Guile bindings. Also called the
2941;;; "root module", as it is imported by many other modules, but it is not
2942;;; necessarily the root of anything; and indeed, the module named '() might be
2943;;; better thought of as a root.
0f2d19dd 2944;;;
bbd1d133 2945
76aea207
AW
2946;; The root module uses the pre-modules-obarray as its obarray. This
2947;; special obarray accumulates all bindings that have been established
2948;; before the module system is fully booted.
2949;;
2950;; (The obarray continues to be used by code that has been closed over
2951;; before the module system has been booted.)
2952;;
2953(define the-root-module
2954 (let ((m (make-module 0)))
2955 (set-module-obarray! m (%get-pre-modules-obarray))
2956 (set-module-name! m '(guile))
76aea207
AW
2957 m))
2958
2959;; The root interface is a module that uses the same obarray as the
2960;; root module. It does not allow new definitions, tho.
2961;;
2962(define the-scm-module
2963 (let ((m (make-module 0)))
2964 (set-module-obarray! m (%get-pre-modules-obarray))
76aea207
AW
2965 (set-module-name! m '(guile))
2966 (set-module-kind! m 'interface)
7354a105
LC
2967
2968 ;; In Guile 1.8 and earlier M was its own public interface.
2969 (set-module-public-interface! m m)
2970
76aea207
AW
2971 m))
2972
2973(set-module-public-interface! the-root-module the-scm-module)
bbd1d133
AW
2974
2975\f
2976
2977;; Now that we have a root module, even though modules aren't fully booted,
2978;; expand the definition of resolve-module.
2979;;
2980(define (resolve-module name . args)
2981 (if (equal? name '(guile))
2982 the-root-module
2983 (error "unexpected module to resolve during module boot" name)))
2984
2985;; Cheat. These bindings are needed by modules.c, but we don't want
2986;; to move their real definition here because that would be unnatural.
2987;;
57ced5b9 2988(define define-module* #f)
bbd1d133
AW
2989(define process-use-modules #f)
2990(define module-export! #f)
2991(define default-duplicate-binding-procedures #f)
2992
2993;; This boots the module system. All bindings needed by modules.c
2994;; must have been defined by now.
296ff5e7 2995;;
bbd1d133
AW
2996(set-current-module the-root-module)
2997
2998
2999\f
3000
3001;; Now that modules are booted, give module-name its final definition.
3002;;
3003(define module-name
3004 (let ((accessor (record-accessor module-type 'name)))
3005 (lambda (mod)
3006 (or (accessor mod)
3007 (let ((name (list (gensym))))
cb67c838
AW
3008 ;; Name MOD and bind it in the module root so that it's visible to
3009 ;; `resolve-module'. This is important as `psyntax' stores module
3010 ;; names and relies on being able to `resolve-module' them.
bbd1d133 3011 (set-module-name! mod name)
9e0bfdba 3012 (nested-define-module! (resolve-module '() #f) name mod)
bbd1d133
AW
3013 (accessor mod))))))
3014
296ff5e7 3015(define (make-modules-in module name)
9e0bfdba
AW
3016 (or (nested-ref-module module name)
3017 (let ((m (make-module 31)))
3018 (set-module-kind! m 'directory)
3019 (set-module-name! m (append (module-name module) name))
3020 (nested-define-module! module name m)
3021 m)))
0f2d19dd 3022
296ff5e7
MV
3023(define (beautify-user-module! module)
3024 (let ((interface (module-public-interface module)))
3025 (if (or (not interface)
9b5a0d84
AW
3026 (eq? interface module))
3027 (let ((interface (make-module 31)))
3028 (set-module-name! interface (module-name module))
dca14012 3029 (set-module-version! interface (module-version module))
9b5a0d84
AW
3030 (set-module-kind! interface 'interface)
3031 (set-module-public-interface! module interface))))
296ff5e7 3032 (if (and (not (memq the-scm-module (module-uses module)))
9b5a0d84 3033 (not (eq? module the-root-module)))
608860a5
LC
3034 ;; Import the default set of bindings (from the SCM module) in MODULE.
3035 (module-use! module the-scm-module)))
432558b9 3036
dca14012 3037(define (version-matches? version-ref target)
dca14012
JG
3038 (define (sub-versions-match? v-refs t)
3039 (define (sub-version-matches? v-ref t)
befd1df9
AW
3040 (let ((matches? (lambda (v) (sub-version-matches? v t))))
3041 (cond
3042 ((number? v-ref) (eqv? v-ref t))
3043 ((list? v-ref)
3044 (case (car v-ref)
3045 ((>=) (>= t (cadr v-ref)))
3046 ((<=) (<= t (cadr v-ref)))
3047 ((and) (and-map matches? (cdr v-ref)))
3048 ((or) (or-map matches? (cdr v-ref)))
3049 ((not) (not (matches? (cadr v-ref))))
3050 (else (error "Invalid sub-version reference" v-ref))))
3051 (else (error "Invalid sub-version reference" v-ref)))))
dca14012
JG
3052 (or (null? v-refs)
3053 (and (not (null? t))
3054 (sub-version-matches? (car v-refs) (car t))
3055 (sub-versions-match? (cdr v-refs) (cdr t)))))
befd1df9
AW
3056
3057 (let ((matches? (lambda (v) (version-matches? v target))))
3058 (or (null? version-ref)
3059 (case (car version-ref)
3060 ((and) (and-map matches? (cdr version-ref)))
3061 ((or) (or-map matches? (cdr version-ref)))
3062 ((not) (not (matches? (cadr version-ref))))
3063 (else (sub-versions-match? version-ref target))))))
dca14012 3064
f95f82f8
AW
3065(define (make-fresh-user-module)
3066 (let ((m (make-module)))
3067 (beautify-user-module! m)
3068 m))
3069
1f60d9d2
MD
3070;; NOTE: This binding is used in libguile/modules.c.
3071;;
53f84bc8 3072(define resolve-module
cb67c838
AW
3073 (let ((root (make-module)))
3074 (set-module-name! root '())
3075 ;; Define the-root-module as '(guile).
d58ccc66 3076 (module-define-submodule! root 'guile the-root-module)
cb67c838 3077
7e314766 3078 (lambda* (name #:optional (autoload #t) (version #f) #:key (ensure #t))
6b7d701e 3079 (let ((already (nested-ref-module root name)))
cb67c838 3080 (cond
d58ccc66 3081 ((and already
cb67c838
AW
3082 (or (not autoload) (module-public-interface already)))
3083 ;; A hit, a palpable hit.
e44d2e4d 3084 (if (and version
cb67c838
AW
3085 (not (version-matches? version (module-version already))))
3086 (error "incompatible module version already loaded" name))
3087 already)
3088 (autoload
3089 ;; Try to autoload the module, and recurse.
3090 (try-load-module name version)
7e314766 3091 (resolve-module name #f #:ensure ensure))
cb67c838 3092 (else
51b22dbb 3093 ;; No module found (or if one was, it had no public interface), and
7e314766
AW
3094 ;; we're not autoloading. Make an empty module if #:ensure is true.
3095 (or already
3096 (and ensure
3097 (make-modules-in root name)))))))))
cb67c838 3098
296ff5e7 3099
dca14012
JG
3100(define (try-load-module name version)
3101 (try-module-autoload name version))
0f2d19dd 3102
c9b16cee 3103(define (reload-module m)
cdab9fc6 3104 "Revisit the source file corresponding to the module @var{m}."
c9b16cee
AW
3105 (let ((f (module-filename m)))
3106 (if f
3107 (save-module-excursion
3108 (lambda ()
3109 ;; Re-set the initial environment, as in try-module-autoload.
3110 (set-current-module (make-fresh-user-module))
3111 (primitive-load-path f)
3112 m))
3113 ;; Though we could guess, we *should* know it.
3114 (error "unknown file name for module" m))))
3115
90847923
MD
3116(define (purify-module! module)
3117 "Removes bindings in MODULE which are inherited from the (guile) module."
3118 (let ((use-list (module-uses module)))
3119 (if (and (pair? use-list)
9b5a0d84
AW
3120 (eq? (car (last-pair use-list)) the-scm-module))
3121 (set-module-uses! module (reverse (cdr (reverse use-list)))))))
90847923 3122
4eecfeb7 3123;; Return a module that is an interface to the module designated by
532cf805
MV
3124;; NAME.
3125;;
c614a00b 3126;; `resolve-interface' takes four keyword arguments:
532cf805
MV
3127;;
3128;; #:select SELECTION
3129;;
3130;; SELECTION is a list of binding-specs to be imported; A binding-spec
3131;; is either a symbol or a pair of symbols (ORIG . SEEN), where ORIG
3132;; is the name in the used module and SEEN is the name in the using
3133;; module. Note that SEEN is also passed through RENAMER, below. The
3134;; default is to select all bindings. If you specify no selection but
4eecfeb7 3135;; a renamer, only the bindings that already exist in the used module
532cf805
MV
3136;; are made available in the interface. Bindings that are added later
3137;; are not picked up.
3138;;
c614a00b 3139;; #:hide BINDINGS
532cf805 3140;;
c614a00b 3141;; BINDINGS is a list of bindings which should not be imported.
f595ccfe
MD
3142;;
3143;; #:prefix PREFIX
3144;;
3145;; PREFIX is a symbol that will be appended to each exported name.
3146;; The default is to not perform any renaming.
532cf805 3147;;
c614a00b
MD
3148;; #:renamer RENAMER
3149;;
3150;; RENAMER is a procedure that takes a symbol and returns its new
3151;; name. The default is not perform any renaming.
3152;;
532cf805
MV
3153;; Signal "no code for module" error if module name is not resolvable
3154;; or its public interface is not available. Signal "no binding"
3155;; error if selected binding does not exist in the used module.
3156;;
36d58fc3
AW
3157(define* (resolve-interface name #:key
3158 (select #f)
3159 (hide '())
3160 (prefix #f)
3161 (renamer (if prefix
3162 (symbol-prefix-proc prefix)
3163 identity))
3164 version)
47aabe86 3165 (let* ((module (resolve-module name #t version #:ensure #f))
b622dec7 3166 (public-i (and module (module-public-interface module))))
f6fd2c03
AW
3167 (unless public-i
3168 (error "no code for module" name))
c614a00b 3169 (if (and (not select) (null? hide) (eq? renamer identity))
b622dec7 3170 public-i
532cf805 3171 (let ((selection (or select (module-map (lambda (sym var) sym)
9b5a0d84 3172 public-i)))
b622dec7 3173 (custom-i (make-module 31)))
c614a00b 3174 (set-module-kind! custom-i 'custom-interface)
9b5a0d84
AW
3175 (set-module-name! custom-i name)
3176 ;; XXX - should use a lazy binder so that changes to the
3177 ;; used module are picked up automatically.
3178 (for-each (lambda (bspec)
3179 (let* ((direct? (symbol? bspec))
3180 (orig (if direct? bspec (car bspec)))
3181 (seen (if direct? bspec (cdr bspec)))
3182 (var (or (module-local-variable public-i orig)
3183 (module-local-variable module orig)
3184 (error
3185 ;; fixme: format manually for now
3186 (simple-format
3187 #f "no binding `~A' in module ~A"
3188 orig name)))))
3189 (if (memq orig hide)
3190 (set! hide (delq! orig hide))
3191 (module-add! custom-i
3192 (renamer seen)
3193 var))))
3194 selection)
3195 ;; Check that we are not hiding bindings which don't exist
3196 (for-each (lambda (binding)
3197 (if (not (module-local-variable public-i binding))
3198 (error
3199 (simple-format
3200 #f "no binding `~A' to hide in module ~A"
3201 binding name))))
3202 hide)
b622dec7 3203 custom-i))))
fb1b76f4
TTN
3204
3205(define (symbol-prefix-proc prefix)
3206 (lambda (symbol)
3207 (symbol-append prefix symbol)))
0f2d19dd 3208
57ced5b9
AW
3209;; This function is called from "modules.c". If you change it, be
3210;; sure to update "modules.c" as well.
3211
f7f62d3a
AW
3212(define* (define-module* name
3213 #:key filename pure version (duplicates '())
3214 (imports '()) (exports '()) (replacements '())
3215 (re-exports '()) (autoloads '()) transformer)
3216 (define (list-of pred l)
3217 (or (null? l)
3218 (and (pair? l) (pred (car l)) (list-of pred (cdr l)))))
3219 (define (valid-export? x)
3220 (or (symbol? x) (and (pair? x) (symbol? (car x)) (symbol? (cdr x)))))
3221 (define (valid-autoload? x)
3222 (and (pair? x) (list-of symbol? (car x)) (list-of symbol? (cdr x))))
3223
3224 (define (resolve-imports imports)
3225 (define (resolve-import import-spec)
3226 (if (list? import-spec)
3227 (apply resolve-interface import-spec)
3228 (error "unexpected use-module specification" import-spec)))
3229 (let lp ((imports imports) (out '()))
3230 (cond
3231 ((null? imports) (reverse! out))
3232 ((pair? imports)
3233 (lp (cdr imports)
3234 (cons (resolve-import (car imports)) out)))
3235 (else (error "unexpected tail of imports list" imports)))))
3236
3237 ;; We could add a #:no-check arg, set by the define-module macro, if
3238 ;; these checks are taking too much time.
3239 ;;
3240 (let ((module (resolve-module name #f)))
3241 (beautify-user-module! module)
3242 (if filename
3243 (set-module-filename! module filename))
3244 (if pure
3245 (purify-module! module))
3246 (if version
3247 (begin
3248 (if (not (list-of integer? version))
3249 (error "expected list of integers for version"))
3250 (set-module-version! module version)
3251 (set-module-version! (module-public-interface module) version)))
f7f62d3a
AW
3252 (let ((imports (resolve-imports imports)))
3253 (call-with-deferred-observers
3254 (lambda ()
3255 (if (pair? imports)
3256 (module-use-interfaces! module imports))
3257 (if (list-of valid-export? exports)
3258 (if (pair? exports)
3259 (module-export! module exports))
3260 (error "expected exports to be a list of symbols or symbol pairs"))
3261 (if (list-of valid-export? replacements)
3262 (if (pair? replacements)
3263 (module-replace! module replacements))
3264 (error "expected replacements to be a list of symbols or symbol pairs"))
3265 (if (list-of valid-export? re-exports)
3266 (if (pair? re-exports)
3267 (module-re-export! module re-exports))
3268 (error "expected re-exports to be a list of symbols or symbol pairs"))
3269 ;; FIXME
3270 (if (not (null? autoloads))
6b1c5d9d
AW
3271 (apply module-autoload! module autoloads))
3272 ;; Wait until modules have been loaded to resolve duplicates
3273 ;; handlers.
3274 (if (pair? duplicates)
3275 (let ((handlers (lookup-duplicates-handlers duplicates)))
3276 (set-module-duplicates-handlers! module handlers))))))
f7f62d3a
AW
3277
3278 (if transformer
3279 (if (and (pair? transformer) (list-of symbol? transformer))
3280 (let ((iface (resolve-interface transformer))
3281 (sym (car (last-pair transformer))))
3282 (set-module-transformer! module (module-ref iface sym)))
3283 (error "expected transformer to be a module name" transformer)))
3284
3285 (run-hook module-defined-hook module)
3286 module))
3287
db853761
NJ
3288;; `module-defined-hook' is a hook that is run whenever a new module
3289;; is defined. Its members are called with one argument, the new
3290;; module.
3291(define module-defined-hook (make-hook 1))
3292
3d2ada2f
DH
3293\f
3294
71225060 3295;;; {Autoload}
3d2ada2f 3296;;;
71225060
MD
3297
3298(define (make-autoload-interface module name bindings)
3299 (let ((b (lambda (a sym definep)
dfd1d3b1
AW
3300 (false-if-exception
3301 (and (memq sym bindings)
3302 (let ((i (module-public-interface (resolve-module name))))
3303 (if (not i)
3304 (error "missing interface for module" name))
3305 (let ((autoload (memq a (module-uses module))))
3306 ;; Replace autoload-interface with actual interface if
3307 ;; that has not happened yet.
3308 (if (pair? autoload)
3309 (set-car! autoload i)))
3310 (module-local-variable i sym)))
3311 #:warning "Failed to autoload ~a in ~a:\n" sym name))))
608860a5 3312 (module-constructor (make-hash-table 0) '() b #f #f name 'autoload #f
f905381d 3313 (make-hash-table 0) '() (make-weak-value-hash-table 31) #f
78f79f18 3314 (make-hash-table 0) #f #f #f)))
608860a5
LC
3315
3316(define (module-autoload! module . args)
3317 "Have @var{module} automatically load the module named @var{name} when one
3318of the symbols listed in @var{bindings} is looked up. @var{args} should be a
3319list of module-name/binding-list pairs, e.g., as in @code{(module-autoload!
3320module '(ice-9 q) '(make-q q-length))}."
3321 (let loop ((args args))
3322 (cond ((null? args)
3323 #t)
3324 ((null? (cdr args))
3325 (error "invalid name+binding autoload list" args))
3326 (else
3327 (let ((name (car args))
3328 (bindings (cadr args)))
3329 (module-use! module (make-autoload-interface module
3330 name bindings))
3331 (loop (cddr args)))))))
3332
71225060 3333
0f2d19dd 3334\f
3d2ada2f 3335
44cf1f0f 3336;;; {Autoloading modules}
3d2ada2f 3337;;;
0f2d19dd 3338
6146984c
MW
3339;;; XXX FIXME autoloads-in-progress and autoloads-done
3340;;; are not handled in a thread-safe way.
3341
0f2d19dd
JB
3342(define autoloads-in-progress '())
3343
f6fd2c03
AW
3344;; This function is called from scm_load_scheme_module in
3345;; "deprecated.c". Please do not change its interface.
3346;;
d9113d47 3347(define* (try-module-autoload module-name #:optional version)
f6fd2c03
AW
3348 "Try to load a module of the given name. If it is not found, return
3349#f. Otherwise return #t. May raise an exception if a file is found,
3350but it fails to load."
0f2d19dd 3351 (let* ((reverse-name (reverse module-name))
9b5a0d84
AW
3352 (name (symbol->string (car reverse-name)))
3353 (dir-hint-module-name (reverse (cdr reverse-name)))
3354 (dir-hint (apply string-append
3355 (map (lambda (elt)
9b6316ea
AW
3356 (string-append (symbol->string elt)
3357 file-name-separator-string))
9b5a0d84 3358 dir-hint-module-name))))
0209ca9a 3359 (resolve-module dir-hint-module-name #f)
0f2d19dd 3360 (and (not (autoload-done-or-in-progress? dir-hint name))
9b5a0d84
AW
3361 (let ((didit #f))
3362 (dynamic-wind
3363 (lambda () (autoload-in-progress! dir-hint name))
3364 (lambda ()
eddd16d7
AW
3365 (with-fluids ((current-reader #f))
3366 (save-module-excursion
3367 (lambda ()
f6fd2c03
AW
3368 (define (call/ec proc)
3369 (let ((tag (make-prompt-tag)))
3370 (call-with-prompt
3371 tag
3372 (lambda ()
3373 (proc (lambda () (abort-to-prompt tag))))
3374 (lambda (k) (values)))))
39392995
AW
3375 ;; The initial environment when loading a module is a fresh
3376 ;; user module.
3377 (set-current-module (make-fresh-user-module))
e44d2e4d
AW
3378 ;; Here we could allow some other search strategy (other than
3379 ;; primitive-load-path), for example using versions encoded
3380 ;; into the file system -- but then we would have to figure
6f06e8d3 3381 ;; out how to locate the compiled file, do auto-compilation,
e44d2e4d
AW
3382 ;; etc. Punt for now, and don't use versions when locating
3383 ;; the file.
f6fd2c03
AW
3384 (call/ec
3385 (lambda (abort)
3386 (primitive-load-path (in-vicinity dir-hint name)
3387 abort)
3388 (set! didit #t)))))))
9b5a0d84
AW
3389 (lambda () (set-autoloaded! dir-hint name didit)))
3390 didit))))
0f2d19dd 3391
71225060 3392\f
3d2ada2f
DH
3393
3394;;; {Dynamic linking of modules}
3395;;;
d0cbd20c 3396
0f2d19dd
JB
3397(define autoloads-done '((guile . guile)))
3398
3399(define (autoload-done-or-in-progress? p m)
3400 (let ((n (cons p m)))
3401 (->bool (or (member n autoloads-done)
9b5a0d84 3402 (member n autoloads-in-progress)))))
0f2d19dd
JB
3403
3404(define (autoload-done! p m)
3405 (let ((n (cons p m)))
3406 (set! autoloads-in-progress
9b5a0d84 3407 (delete! n autoloads-in-progress))
0f2d19dd 3408 (or (member n autoloads-done)
9b5a0d84 3409 (set! autoloads-done (cons n autoloads-done)))))
0f2d19dd
JB
3410
3411(define (autoload-in-progress! p m)
3412 (let ((n (cons p m)))
3413 (set! autoloads-done
9b5a0d84 3414 (delete! n autoloads-done))
0f2d19dd
JB
3415 (set! autoloads-in-progress (cons n autoloads-in-progress))))
3416
3417(define (set-autoloaded! p m done?)
3418 (if done?
3419 (autoload-done! p m)
3420 (let ((n (cons p m)))
9b5a0d84
AW
3421 (set! autoloads-done (delete! n autoloads-done))
3422 (set! autoloads-in-progress (delete! n autoloads-in-progress)))))
0f2d19dd 3423
0f2d19dd
JB
3424\f
3425
83b38198 3426;;; {Run-time options}
3d2ada2f 3427;;;
83b38198 3428
122f296d
AW
3429(define-syntax define-option-interface
3430 (syntax-rules ()
3431 ((_ (interface (options enable disable) (option-set!)))
3432 (begin
3433 (define options
3434 (case-lambda
3435 (() (interface))
3436 ((arg)
3437 (if (list? arg)
3438 (begin (interface arg) (interface))
3439 (for-each
3440 (lambda (option)
3441 (apply (lambda (name value documentation)
3442 (display name)
495797ce
MW
3443 (let ((len (string-length (symbol->string name))))
3444 (when (< len 16)
3445 (display #\tab)
3446 (when (< len 8)
3447 (display #\tab))))
122f296d
AW
3448 (display #\tab)
3449 (display value)
3450 (display #\tab)
3451 (display documentation)
3452 (newline))
3453 option))
3454 (interface #t))))))
3455 (define (enable . flags)
3456 (interface (append flags (interface)))
3457 (interface))
3458 (define (disable . flags)
3459 (let ((options (interface)))
3460 (for-each (lambda (flag) (set! options (delq! flag options)))
3461 flags)
3462 (interface options)
3463 (interface)))
0c65f52c 3464 (define-syntax-rule (option-set! opt val)
f6ddf827 3465 (eval-when (expand load eval)
0c65f52c 3466 (options (append (options) (list 'opt val)))))))))
e9bab9df 3467
e9bab9df
DH
3468(define-option-interface
3469 (debug-options-interface
3470 (debug-options debug-enable debug-disable)
3471 (debug-set!)))
3472
e9bab9df
DH
3473(define-option-interface
3474 (read-options-interface
3475 (read-options read-enable read-disable)
3476 (read-set!)))
3477
3478(define-option-interface
3479 (print-options-interface
3480 (print-options print-enable print-disable)
3481 (print-set!)))
83b38198
MD
3482
3483\f
3484
410e83c0
AW
3485;;; {The Unspecified Value}
3486;;;
3487;;; Currently Guile represents unspecified values via one particular value,
3488;;; which may be obtained by evaluating (if #f #f). It would be nice in the
3489;;; future if we could replace this with a return of 0 values, though.
9346b857 3490;;;
410e83c0
AW
3491
3492(define-syntax *unspecified*
3493 (identifier-syntax (if #f #f)))
3494
3495(define (unspecified? v) (eq? v *unspecified*))
3496
3497
3498\f
3499
0f2d19dd
JB
3500;;; {Running Repls}
3501;;;
3502
9447207f 3503(define *repl-stack* (make-fluid '()))
1fdd5bec 3504
9346b857
AW
3505;; Programs can call `batch-mode?' to see if they are running as part of a
3506;; script or if they are running interactively. REPL implementations ensure that
3507;; `batch-mode?' returns #f during their extent.
3508;;
1fdd5bec 3509(define (batch-mode?)
9447207f 3510 (null? (fluid-ref *repl-stack*)))
1fdd5bec 3511
9346b857 3512;; Programs can re-enter batch mode, for example after a fork, by calling
0feb833d
AW
3513;; `ensure-batch-mode!'. It's not a great interface, though; it would be better
3514;; to abort to the outermost prompt, and call a thunk there.
1fdd5bec 3515;;
9346b857 3516(define (ensure-batch-mode!)
9d2136ba 3517 (set! batch-mode? (lambda () #t)))
4bbbcd5c 3518
0f2d19dd
JB
3519(define (quit . args)
3520 (apply throw 'quit args))
3521
7950df7c
GH
3522(define exit quit)
3523
0f2d19dd
JB
3524(define (gc-run-time)
3525 (cdr (assq 'gc-time-taken (gc-stats))))
3526
8942e7a1
AW
3527(define abort-hook (make-hook))
3528(define before-error-hook (make-hook))
3529(define after-error-hook (make-hook))
3530(define before-backtrace-hook (make-hook))
3531(define after-backtrace-hook (make-hook))
3532
3e3cec45
MD
3533(define before-read-hook (make-hook))
3534(define after-read-hook (make-hook))
870777d7
KN
3535(define before-eval-hook (make-hook 1))
3536(define after-eval-hook (make-hook 1))
3537(define before-print-hook (make-hook 1))
3538(define after-print-hook (make-hook 1))
1c6cd8e8 3539
c592de96
AW
3540;;; This hook is run at the very end of an interactive session.
3541;;;
3542(define exit-hook (make-hook))
3543
dc5c2038
MD
3544;;; The default repl-reader function. We may override this if we've
3545;;; the readline library.
3546(define repl-reader
17ee350c 3547 (lambda* (prompt #:optional (reader (fluid-ref current-reader)))
0becb8f3 3548 (if (not (char-ready?))
dceb7829
AW
3549 (begin
3550 (display (if (string? prompt) prompt (prompt)))
3551 ;; An interesting situation. The printer resets the column to
3552 ;; 0 by printing a newline, but we then advance it by printing
3553 ;; the prompt. However the port-column of the output port
3554 ;; does not typically correspond with the actual column on the
b3da54d1 3555 ;; screen, because the input is echoed back! Since the
dceb7829
AW
3556 ;; input is line-buffered and thus ends with a newline, the
3557 ;; output will really start on column zero. So, here we zero
3558 ;; it out. See bug 9664.
3559 ;;
3560 ;; Note that for similar reasons, the output-line will not
3561 ;; reflect the actual line on the screen. But given the
3562 ;; possibility of multiline input, the fix is not as
3563 ;; straightforward, so we don't bother.
3564 ;;
3565 ;; Also note that the readline implementation papers over
3566 ;; these concerns, because it's readline itself printing the
3567 ;; prompt, and not Guile.
3568 (set-port-column! (current-output-port) 0)))
dc5c2038 3569 (force-output)
04efd24d 3570 (run-hook before-read-hook)
17ee350c 3571 ((or reader read) (current-input-port))))
dc5c2038 3572
0f2d19dd 3573
0f2d19dd 3574\f
3d2ada2f 3575
773abfbb
KR
3576;;; {While}
3577;;;
3578;;; with `continue' and `break'.
3579;;;
3580
10e69149
AW
3581;; The inliner will remove the prompts at compile-time if it finds that
3582;; `continue' or `break' are not used.
3583;;
3584(define-syntax while
3585 (lambda (x)
3586 (syntax-case x ()
3587 ((while cond body ...)
3588 #`(let ((break-tag (make-prompt-tag "break"))
3589 (continue-tag (make-prompt-tag "continue")))
3590 (call-with-prompt
3591 break-tag
3592 (lambda ()
3593 (define-syntax #,(datum->syntax #'while 'break)
3594 (lambda (x)
3595 (syntax-case x ()
91956a94
AW
3596 ((_ arg (... ...))
3597 #'(abort-to-prompt break-tag arg (... ...)))
10e69149 3598 (_
91956a94
AW
3599 #'(lambda args
3600 (apply abort-to-prompt break-tag args))))))
10e69149
AW
3601 (let lp ()
3602 (call-with-prompt
3603 continue-tag
3604 (lambda ()
3605 (define-syntax #,(datum->syntax #'while 'continue)
3606 (lambda (x)
3607 (syntax-case x ()
3608 ((_)
3609 #'(abort-to-prompt continue-tag))
3610 ((_ . args)
3611 (syntax-violation 'continue "too many arguments" x))
3612 (_
ddf134cf
MW
3613 #'(lambda ()
3614 (abort-to-prompt continue-tag))))))
91956a94 3615 (do () ((not cond) #f) body ...))
10e69149 3616 (lambda (k) (lp)))))
91956a94
AW
3617 (lambda (k . args)
3618 (if (null? args)
3619 #t
3620 (apply values args)))))))))
5578a53f 3621
773abfbb 3622
0f2d19dd 3623\f
3d2ada2f 3624
0f2d19dd
JB
3625;;; {Module System Macros}
3626;;;
3627
532cf805
MV
3628;; Return a list of expressions that evaluate to the appropriate
3629;; arguments for resolve-interface according to SPEC.
3630
f6ddf827 3631(eval-when (expand)
1fdd5bec
AW
3632 (if (memq 'prefix (read-options))
3633 (error "boot-9 must be compiled with #:kw, not :kw")))
1a1a10d3 3634
532cf805
MV
3635(define (keyword-like-symbol->keyword sym)
3636 (symbol->keyword (string->symbol (substring (symbol->string sym) 1))))
3637
074e036e
AW
3638(define-syntax define-module
3639 (lambda (x)
3640 (define (keyword-like? stx)
3641 (let ((dat (syntax->datum stx)))
3642 (and (symbol? dat)
3643 (eqv? (string-ref (symbol->string dat) 0) #\:))))
3644 (define (->keyword sym)
3645 (symbol->keyword (string->symbol (substring (symbol->string sym) 1))))
3646
cd8c3519 3647 (define (parse-iface args)
074e036e
AW
3648 (let loop ((in args) (out '()))
3649 (syntax-case in ()
3650 (() (reverse! out))
3651 ;; The user wanted #:foo, but wrote :foo. Fix it.
3652 ((sym . in) (keyword-like? #'sym)
3653 (loop #`(#,(->keyword (syntax->datum #'sym)) . in) out))
3654 ((kw . in) (not (keyword? (syntax->datum #'kw)))
3655 (syntax-violation 'define-module "expected keyword arg" x #'kw))
3656 ((#:renamer renamer . in)
cd8c3519 3657 (loop #'in (cons* #',renamer #:renamer out)))
074e036e 3658 ((kw val . in)
cd8c3519 3659 (loop #'in (cons* #'val #'kw out))))))
074e036e 3660
cd8c3519 3661 (define (parse args imp exp rex rep aut)
074e036e
AW
3662 ;; Just quote everything except #:use-module and #:use-syntax. We
3663 ;; need to know about all arguments regardless since we want to turn
3664 ;; symbols that look like keywords into real keywords, and the
3665 ;; keyword args in a define-module form are not regular
3666 ;; (i.e. no-backtrace doesn't take a value).
cd8c3519
AW
3667 (syntax-case args ()
3668 (()
3669 (let ((imp (if (null? imp) '() #`(#:imports `#,imp)))
3670 (exp (if (null? exp) '() #`(#:exports '#,exp)))
3671 (rex (if (null? rex) '() #`(#:re-exports '#,rex)))
3672 (rep (if (null? rep) '() #`(#:replacements '#,rep)))
3673 (aut (if (null? aut) '() #`(#:autoloads '#,aut))))
3674 #`(#,@imp #,@exp #,@rex #,@rep #,@aut)))
3675 ;; The user wanted #:foo, but wrote :foo. Fix it.
3676 ((sym . args) (keyword-like? #'sym)
3677 (parse #`(#,(->keyword (syntax->datum #'sym)) . args)
3678 imp exp rex rep aut))
3679 ((kw . args) (not (keyword? (syntax->datum #'kw)))
3680 (syntax-violation 'define-module "expected keyword arg" x #'kw))
3681 ((#:no-backtrace . args)
3682 ;; Ignore this one.
3683 (parse #'args imp exp rex rep aut))
3684 ((#:pure . args)
3685 #`(#:pure #t . #,(parse #'args imp exp rex rep aut)))
3686 ((kw)
3687 (syntax-violation 'define-module "keyword arg without value" x #'kw))
3688 ((#:version (v ...) . args)
3689 #`(#:version '(v ...) . #,(parse #'args imp exp rex rep aut)))
3690 ((#:duplicates (d ...) . args)
3691 #`(#:duplicates '(d ...) . #,(parse #'args imp exp rex rep aut)))
3692 ((#:filename f . args)
3693 #`(#:filename 'f . #,(parse #'args imp exp rex rep aut)))
3694 ((#:use-module (name name* ...) . args)
3695 (and (and-map symbol? (syntax->datum #'(name name* ...))))
ad4bd7c2 3696 (parse #'args #`(#,@imp ((name name* ...))) exp rex rep aut))
cd8c3519
AW
3697 ((#:use-syntax (name name* ...) . args)
3698 (and (and-map symbol? (syntax->datum #'(name name* ...))))
3699 #`(#:transformer '(name name* ...)
ad4bd7c2 3700 . #,(parse #'args #`(#,@imp ((name name* ...))) exp rex rep aut)))
cd8c3519
AW
3701 ((#:use-module ((name name* ...) arg ...) . args)
3702 (and (and-map symbol? (syntax->datum #'(name name* ...))))
3703 (parse #'args
ad4bd7c2 3704 #`(#,@imp ((name name* ...) #,@(parse-iface #'(arg ...))))
cd8c3519
AW
3705 exp rex rep aut))
3706 ((#:export (ex ...) . args)
3707 (parse #'args imp #`(#,@exp ex ...) rex rep aut))
3708 ((#:export-syntax (ex ...) . args)
3709 (parse #'args imp #`(#,@exp ex ...) rex rep aut))
3710 ((#:re-export (re ...) . args)
3711 (parse #'args imp exp #`(#,@rex re ...) rep aut))
3712 ((#:re-export-syntax (re ...) . args)
3713 (parse #'args imp exp #`(#,@rex re ...) rep aut))
3714 ((#:replace (r ...) . args)
3715 (parse #'args imp exp rex #`(#,@rep r ...) aut))
3716 ((#:replace-syntax (r ...) . args)
3717 (parse #'args imp exp rex #`(#,@rep r ...) aut))
3718 ((#:autoload name bindings . args)
3719 (parse #'args imp exp rex rep #`(#,@aut name bindings)))
3720 ((kw val . args)
3721 (syntax-violation 'define-module "unknown keyword or bad argument"
3722 #'kw #'val))))
074e036e
AW
3723
3724 (syntax-case x ()
3725 ((_ (name name* ...) arg ...)
cd8c3519
AW
3726 (and-map symbol? (syntax->datum #'(name name* ...)))
3727 (with-syntax (((quoted-arg ...)
3728 (parse #'(arg ...) '() '() '() '() '()))
c415fe08
AW
3729 ;; Ideally the filename is either a string or #f;
3730 ;; this hack is to work around a case in which
3731 ;; port-filename returns a symbol (`socket') for
3732 ;; sockets.
3733 (filename (let ((f (assq-ref (or (syntax-source x) '())
3734 'filename)))
3735 (and (string? f) f))))
f6ddf827 3736 #'(eval-when (expand load eval)
cd8c3519
AW
3737 (let ((m (define-module* '(name name* ...)
3738 #:filename filename quoted-arg ...)))
074e036e
AW
3739 (set-current-module m)
3740 m)))))))
0f2d19dd 3741
532cf805
MV
3742;; The guts of the use-modules macro. Add the interfaces of the named
3743;; modules to the use-list of the current module, in order.
3744
482a28f9
MV
3745;; This function is called by "modules.c". If you change it, be sure
3746;; to change scm_c_use_module as well.
3747
532cf805 3748(define (process-use-modules module-interface-args)
d57da08b 3749 (let ((interfaces (map (lambda (mif-args)
9b5a0d84
AW
3750 (or (apply resolve-interface mif-args)
3751 (error "no such module" mif-args)))
3752 module-interface-args)))
d57da08b
MD
3753 (call-with-deferred-observers
3754 (lambda ()
3755 (module-use-interfaces! (current-module) interfaces)))))
89da9036 3756
4e3328ce
AW
3757(define-syntax use-modules
3758 (lambda (x)
3759 (define (keyword-like? stx)
3760 (let ((dat (syntax->datum stx)))
3761 (and (symbol? dat)
3762 (eqv? (string-ref (symbol->string dat) 0) #\:))))
3763 (define (->keyword sym)
3764 (symbol->keyword (string->symbol (substring (symbol->string sym) 1))))
3765
3766 (define (quotify-iface args)
3767 (let loop ((in args) (out '()))
3768 (syntax-case in ()
3769 (() (reverse! out))
3770 ;; The user wanted #:foo, but wrote :foo. Fix it.
3771 ((sym . in) (keyword-like? #'sym)
3772 (loop #`(#,(->keyword (syntax->datum #'sym)) . in) out))
3773 ((kw . in) (not (keyword? (syntax->datum #'kw)))
3774 (syntax-violation 'define-module "expected keyword arg" x #'kw))
3775 ((#:renamer renamer . in)
3776 (loop #'in (cons* #'renamer #:renamer out)))
3777 ((kw val . in)
3778 (loop #'in (cons* #''val #'kw out))))))
3779
3780 (define (quotify specs)
3781 (let lp ((in specs) (out '()))
3782 (syntax-case in ()
3783 (() (reverse out))
3784 (((name name* ...) . in)
3785 (and-map symbol? (syntax->datum #'(name name* ...)))
3786 (lp #'in (cons #''((name name* ...)) out)))
3787 ((((name name* ...) arg ...) . in)
3788 (and-map symbol? (syntax->datum #'(name name* ...)))
3789 (with-syntax (((quoted-arg ...) (quotify-iface #'(arg ...))))
3790 (lp #'in (cons #`(list '(name name* ...) quoted-arg ...)
3791 out)))))))
3792
3793 (syntax-case x ()
3794 ((_ spec ...)
3795 (with-syntax (((quoted-args ...) (quotify #'(spec ...))))
f6ddf827 3796 #'(eval-when (expand load eval)
4e3328ce
AW
3797 (process-use-modules (list quoted-args ...))
3798 *unspecified*))))))
3799
b1e4c7cc
JG
3800(include-from-path "ice-9/r6rs-libraries")
3801
0c65f52c
AW
3802(define-syntax-rule (define-private foo bar)
3803 (define foo bar))
13182603
AW
3804
3805(define-syntax define-public
3806 (syntax-rules ()
3807 ((_ (name . args) . body)
4aaceda2 3808 (begin
df3acd29 3809 (define (name . args) . body)
4aaceda2 3810 (export name)))
13182603
AW
3811 ((_ name val)
3812 (begin
3813 (define name val)
3814 (export name)))))
3815
0c65f52c
AW
3816(define-syntax-rule (defmacro-public name args body ...)
3817 (begin
3818 (defmacro name args body ...)
3819 (export-syntax name)))
0f2d19dd 3820
87e00370 3821;; And now for the most important macro.
0c65f52c
AW
3822(define-syntax-rule (λ formals body ...)
3823 (lambda formals body ...))
87e00370
LC
3824
3825\f
89d06712 3826;; Export a local variable
482a28f9
MV
3827
3828;; This function is called from "modules.c". If you change it, be
3829;; sure to update "modules.c" as well.
3830
90847923
MD
3831(define (module-export! m names)
3832 (let ((public-i (module-public-interface m)))
3833 (for-each (lambda (name)
78c22f5e
JG
3834 (let* ((internal-name (if (pair? name) (car name) name))
3835 (external-name (if (pair? name) (cdr name) name))
3836 (var (module-ensure-local-variable! m internal-name)))
3837 (module-add! public-i external-name var)))
9b5a0d84 3838 names)))
89d06712 3839
f595ccfe
MD
3840(define (module-replace! m names)
3841 (let ((public-i (module-public-interface m)))
3842 (for-each (lambda (name)
78c22f5e
JG
3843 (let* ((internal-name (if (pair? name) (car name) name))
3844 (external-name (if (pair? name) (cdr name) name))
3845 (var (module-ensure-local-variable! m internal-name)))
eceee4ef
AW
3846 ;; FIXME: use a bit on variables instead of object
3847 ;; properties.
9b5a0d84 3848 (set-object-property! var 'replace #t)
78c22f5e 3849 (module-add! public-i external-name var)))
9b5a0d84 3850 names)))
f595ccfe 3851
d2b7b761
AW
3852;; Export all local variables from a module
3853;;
3854(define (module-export-all! mod)
3855 (define (fresh-interface!)
3856 (let ((iface (make-module)))
3857 (set-module-name! iface (module-name mod))
e5602ce7 3858 (set-module-version! iface (module-version mod))
d2b7b761
AW
3859 (set-module-kind! iface 'interface)
3860 (set-module-public-interface! mod iface)
3861 iface))
3862 (let ((iface (or (module-public-interface mod)
3863 (fresh-interface!))))
3864 (set-module-obarray! iface (module-obarray mod))))
3865
89d06712
MV
3866;; Re-export a imported variable
3867;;
3868(define (module-re-export! m names)
3869 (let ((public-i (module-public-interface m)))
3870 (for-each (lambda (name)
78c22f5e
JG
3871 (let* ((internal-name (if (pair? name) (car name) name))
3872 (external-name (if (pair? name) (cdr name) name))
3873 (var (module-variable m internal-name)))
9b5a0d84 3874 (cond ((not var)
78c22f5e
JG
3875 (error "Undefined variable:" internal-name))
3876 ((eq? var (module-local-variable m internal-name))
3877 (error "re-exporting local variable:" internal-name))
9b5a0d84 3878 (else
78c22f5e 3879 (module-add! public-i external-name var)))))
9b5a0d84 3880 names)))
90847923 3881
0c65f52c 3882(define-syntax-rule (export name ...)
f6ddf827 3883 (eval-when (expand load eval)
0c65f52c
AW
3884 (call-with-deferred-observers
3885 (lambda ()
3886 (module-export! (current-module) '(name ...))))))
a0cc0a01 3887
0c65f52c 3888(define-syntax-rule (re-export name ...)
f6ddf827 3889 (eval-when (expand load eval)
0c65f52c
AW
3890 (call-with-deferred-observers
3891 (lambda ()
3892 (module-re-export! (current-module) '(name ...))))))
89d06712 3893
0c65f52c 3894(define-syntax-rule (export! name ...)
f6ddf827 3895 (eval-when (expand load eval)
0c65f52c
AW
3896 (call-with-deferred-observers
3897 (lambda ()
3898 (module-replace! (current-module) '(name ...))))))
1052739b 3899
0c65f52c
AW
3900(define-syntax-rule (export-syntax name ...)
3901 (export name ...))
a0cc0a01 3902
0c65f52c
AW
3903(define-syntax-rule (re-export-syntax name ...)
3904 (re-export name ...))
a0cc0a01 3905
3de80ed5
AW
3906\f
3907
f595ccfe
MD
3908;;; {Parameters}
3909;;;
3910
e9729cbb 3911(define* (make-mutable-parameter init #:optional (converter identity))
9447207f 3912 (let ((fluid (make-fluid (converter init))))
e9729cbb
AW
3913 (case-lambda
3914 (() (fluid-ref fluid))
3915 ((val) (fluid-set! fluid (converter val))))))
3916
f595ccfe
MD
3917
3918\f
3d2ada2f 3919
7b07e5ef
MD
3920;;; {Handling of duplicate imported bindings}
3921;;;
3922
3923;; Duplicate handlers take the following arguments:
3924;;
3925;; module importing module
9b5a0d84
AW
3926;; name conflicting name
3927;; int1 old interface where name occurs
3928;; val1 value of binding in old interface
3929;; int2 new interface where name occurs
3930;; val2 value of binding in new interface
3931;; var previous resolution or #f
3932;; val value of previous resolution
7b07e5ef
MD
3933;;
3934;; A duplicate handler can take three alternative actions:
3935;;
3936;; 1. return #f => leave responsibility to next handler
3937;; 2. exit with an error
3938;; 3. return a variable resolving the conflict
3939;;
3940
3941(define duplicate-handlers
3942 (let ((m (make-module 7)))
f595ccfe
MD
3943
3944 (define (check module name int1 val1 int2 val2 var val)
3945 (scm-error 'misc-error
9b5a0d84
AW
3946 #f
3947 "~A: `~A' imported from both ~A and ~A"
3948 (list (module-name module)
3949 name
3950 (module-name int1)
3951 (module-name int2))
3952 #f))
f595ccfe 3953
65bed4aa 3954 (define (warn module name int1 val1 int2 val2 var val)
2c27dd57 3955 (format (current-warning-port)
9b5a0d84
AW
3956 "WARNING: ~A: `~A' imported from both ~A and ~A\n"
3957 (module-name module)
3958 name
3959 (module-name int1)
3960 (module-name int2))
65bed4aa 3961 #f)
f595ccfe
MD
3962
3963 (define (replace module name int1 val1 int2 val2 var val)
3964 (let ((old (or (and var (object-property var 'replace) var)
9b5a0d84
AW
3965 (module-variable int1 name)))
3966 (new (module-variable int2 name)))
3967 (if (object-property old 'replace)
3968 (and (or (eq? old new)
3969 (not (object-property new 'replace)))
3970 old)
3971 (and (object-property new 'replace)
3972 new))))
f595ccfe 3973
65bed4aa
MD
3974 (define (warn-override-core module name int1 val1 int2 val2 var val)
3975 (and (eq? int1 the-scm-module)
9b5a0d84 3976 (begin
2c27dd57 3977 (format (current-warning-port)
9b5a0d84
AW
3978 "WARNING: ~A: imported module ~A overrides core binding `~A'\n"
3979 (module-name module)
3980 (module-name int2)
3981 name)
3982 (module-local-variable int2 name))))
f595ccfe 3983
65bed4aa
MD
3984 (define (first module name int1 val1 int2 val2 var val)
3985 (or var (module-local-variable int1 name)))
f595ccfe 3986
65bed4aa
MD
3987 (define (last module name int1 val1 int2 val2 var val)
3988 (module-local-variable int2 name))
f595ccfe 3989
65bed4aa
MD
3990 (define (noop module name int1 val1 int2 val2 var val)
3991 #f)
3992
7b07e5ef
MD
3993 (set-module-name! m 'duplicate-handlers)
3994 (set-module-kind! m 'interface)
f595ccfe
MD
3995 (module-define! m 'check check)
3996 (module-define! m 'warn warn)
3997 (module-define! m 'replace replace)
3998 (module-define! m 'warn-override-core warn-override-core)
3999 (module-define! m 'first first)
4000 (module-define! m 'last last)
65bed4aa
MD
4001 (module-define! m 'merge-generics noop)
4002 (module-define! m 'merge-accessors noop)
7b07e5ef
MD
4003 m))
4004
f595ccfe 4005(define (lookup-duplicates-handlers handler-names)
109c2c9f
MD
4006 (and handler-names
4007 (map (lambda (handler-name)
9b5a0d84
AW
4008 (or (module-symbol-local-binding
4009 duplicate-handlers handler-name #f)
4010 (error "invalid duplicate handler name:"
4011 handler-name)))
4012 (if (list? handler-names)
4013 handler-names
4014 (list handler-names)))))
f595ccfe 4015
70a459e3
MD
4016(define default-duplicate-binding-procedures
4017 (make-mutable-parameter #f))
4018
4019(define default-duplicate-binding-handler
6496a663 4020 (make-mutable-parameter '(replace warn-override-core warn last)
9b5a0d84
AW
4021 (lambda (handler-names)
4022 (default-duplicate-binding-procedures
4023 (lookup-duplicates-handlers handler-names))
4024 handler-names)))
f595ccfe 4025
7b07e5ef 4026\f
7f24bc58 4027
c50775e2
AW
4028;;; {`load'.}
4029;;;
9b6316ea
AW
4030;;; Load is tricky when combined with relative file names, compilation,
4031;;; and the file system. If a file name is relative, what is it
4032;;; relative to? The name of the source file at the time it was
4033;;; compiled? The name of the compiled file? What if both or either
4034;;; were installed? And how do you get that information? Tricky, I
4035;;; say.
c50775e2
AW
4036;;;
4037;;; To get around all of this, we're going to do something nasty, and
9b6316ea 4038;;; turn `load' into a macro. That way it can know the name of the
c50775e2 4039;;; source file with respect to which it was invoked, so it can resolve
9b6316ea 4040;;; relative file names with respect to the original source file.
c50775e2
AW
4041;;;
4042;;; There is an exception, and that is that if the source file was in
4043;;; the load path when it was compiled, instead of looking up against
4044;;; the absolute source location, we load-from-path against the relative
4045;;; source location.
4046;;;
4047
5a79300f
LC
4048(define %auto-compilation-options
4049 ;; Default `compile-file' option when auto-compiling.
9ee04557
LC
4050 '(#:warnings (unbound-variable arity-mismatch format
4051 duplicate-case-datum bad-case-datum)))
5a79300f 4052
9b6316ea
AW
4053(define* (load-in-vicinity dir file-name #:optional reader)
4054 "Load source file FILE-NAME in vicinity of directory DIR. Use a
4055pre-compiled version of FILE-NAME when available, and auto-compile one
4056when none is available, reading FILE-NAME with READER."
9fbca4b3 4057
65fa3923
AW
4058 ;; The auto-compilation code will residualize a .go file in the cache
4059 ;; dir: by default, $HOME/.cache/guile/2.0/ccache/PATH.go. This
4060 ;; function determines the PATH to use as a key into the compilation
4061 ;; cache.
6934d9e7
AW
4062 (define (canonical->suffix canon)
4063 (cond
9b6316ea
AW
4064 ((and (not (string-null? canon))
4065 (file-name-separator? (string-ref canon 0)))
4066 canon)
4067 ((and (eq? (system-file-name-convention) 'windows)
4068 (absolute-file-name? canon))
4069 ;; An absolute file name that doesn't start with a separator
4070 ;; starts with a drive component. Transform the drive component
4071 ;; to a file name element: c:\foo -> \c\foo.
4072 (string-append file-name-separator-string
4073 (substring canon 0 1)
4074 (substring canon 2)))
6934d9e7
AW
4075 (else canon)))
4076
9fbca4b3
LC
4077 (define compiled-extension
4078 ;; File name extension of compiled files.
4079 (cond ((or (null? %load-compiled-extensions)
4080 (string-null? (car %load-compiled-extensions)))
4081 (warn "invalid %load-compiled-extensions"
4082 %load-compiled-extensions)
4083 ".go")
4084 (else (car %load-compiled-extensions))))
4085
4086 (define (more-recent? stat1 stat2)
4087 ;; Return #t when STAT1 has an mtime greater than that of STAT2.
4088 (or (> (stat:mtime stat1) (stat:mtime stat2))
4089 (and (= (stat:mtime stat1) (stat:mtime stat2))
4090 (>= (stat:mtimensec stat1)
4091 (stat:mtimensec stat2)))))
4092
9b6316ea
AW
4093 (define (fallback-file-name canon-file-name)
4094 ;; Return the in-cache compiled file name for source file
4095 ;; CANON-FILE-NAME.
9fbca4b3 4096
9b6316ea
AW
4097 ;; FIXME: would probably be better just to append
4098 ;; SHA1(canon-file-name) to the %compile-fallback-path, to avoid
4099 ;; deep directory stats.
9fbca4b3
LC
4100 (and %compile-fallback-path
4101 (string-append %compile-fallback-path
9b6316ea 4102 (canonical->suffix canon-file-name)
9fbca4b3
LC
4103 compiled-extension)))
4104
4105 (define (compile file)
4106 ;; Compile source FILE, lazily loading the compiler.
4107 ((module-ref (resolve-interface '(system base compile))
4108 'compile-file)
4109 file
4110 #:opts %auto-compilation-options
4111 #:env (current-module)))
4112
9b6316ea
AW
4113 ;; Returns the .go file corresponding to `name'. Does not search load
4114 ;; paths, only the fallback path. If the .go file is missing or out
4115 ;; of date, and auto-compilation is enabled, will try
4116 ;; auto-compilation, just as primitive-load-path does internally.
4117 ;; primitive-load is unaffected. Returns #f if auto-compilation
4118 ;; failed or was disabled.
c50775e2 4119 ;;
9b6316ea
AW
4120 ;; NB: Unless we need to compile the file, this function should not
4121 ;; cause (system base compile) to be loaded up. For that reason
4122 ;; compiled-file-name partially duplicates functionality from (system
4123 ;; base compile).
4124
4125 (define (fresh-compiled-file-name name scmstat go-file-name)
4126 ;; Return GO-FILE-NAME after making sure that it contains a freshly
4127 ;; compiled version of source file NAME with stat SCMSTAT; return #f
4128 ;; on failure.
dfd1d3b1
AW
4129 (false-if-exception
4130 (let ((gostat (and (not %fresh-auto-compile)
4131 (stat go-file-name #f))))
4132 (if (and gostat (more-recent? gostat scmstat))
4133 go-file-name
4134 (begin
4135 (if gostat
4136 (format (current-warning-port)
4137 ";;; note: source file ~a\n;;; newer than compiled ~a\n"
4138 name go-file-name))
4139 (cond
4140 (%load-should-auto-compile
4141 (%warn-auto-compilation-enabled)
4142 (format (current-warning-port) ";;; compiling ~a\n" name)
4143 (let ((cfn (compile name)))
4144 (format (current-warning-port) ";;; compiled ~a\n" cfn)
4145 cfn))
4146 (else #f)))))
4147 #:warning "WARNING: compilation of ~a failed:\n" name))
c50775e2 4148
ca8be3f5
LC
4149 (define (sans-extension file)
4150 (let ((dot (string-rindex file #\.)))
4151 (if dot
4152 (substring file 0 dot)
4153 file)))
4154
9b6316ea
AW
4155 (define (load-absolute abs-file-name)
4156 ;; Load from ABS-FILE-NAME, using a compiled file or auto-compiling
4157 ;; if needed.
ca8be3f5 4158 (define scmstat
dfd1d3b1
AW
4159 (false-if-exception
4160 (stat abs-file-name)
4161 #:warning "Stat of ~a failed:\n" abs-file-name))
ca8be3f5
LC
4162
4163 (define (pre-compiled)
9b6316ea
AW
4164 (and=> (search-path %load-compiled-path (sans-extension file-name)
4165 %load-compiled-extensions #t)
4166 (lambda (go-file-name)
4167 (let ((gostat (stat go-file-name #f)))
4168 (and gostat (more-recent? gostat scmstat)
4169 go-file-name)))))
ca8be3f5
LC
4170
4171 (define (fallback)
9b6316ea
AW
4172 (and=> (false-if-exception (canonicalize-path abs-file-name))
4173 (lambda (canon)
4174 (and=> (fallback-file-name canon)
4175 (lambda (go-file-name)
4176 (fresh-compiled-file-name abs-file-name
4177 scmstat
4178 go-file-name))))))
4179
4180 (let ((compiled (and scmstat (or (pre-compiled) (fallback)))))
ca8be3f5 4181 (if compiled
dcada7d8
AW
4182 (begin
4183 (if %load-hook
9b6316ea 4184 (%load-hook abs-file-name))
ca8be3f5 4185 (load-compiled compiled))
c50775e2 4186 (start-stack 'load-stack
9b6316ea 4187 (primitive-load abs-file-name)))))
ca8be3f5 4188
c50775e2
AW
4189 (save-module-excursion
4190 (lambda ()
4191 (with-fluids ((current-reader reader)
4192 (%file-port-name-canonicalization 'relative))
4193 (cond
9b6316ea
AW
4194 ((absolute-file-name? file-name)
4195 (load-absolute file-name))
4196 ((absolute-file-name? dir)
4197 (load-absolute (in-vicinity dir file-name)))
c50775e2 4198 (else
9b6316ea 4199 (load-from-path (in-vicinity dir file-name))))))))
c50775e2
AW
4200
4201(define-syntax load
4202 (make-variable-transformer
4203 (lambda (x)
4204 (let* ((src (syntax-source x))
4205 (file (and src (assq-ref src 'filename)))
4206 (dir (and (string? file) (dirname file))))
4207 (syntax-case x ()
4208 ((_ arg ...)
4209 #`(load-in-vicinity #,(or dir #'(getcwd)) arg ...))
4210 (id
4211 (identifier? #'id)
4212 #`(lambda args
4213 (apply load-in-vicinity #,(or dir #'(getcwd)) args))))))))
4214
4215\f
4216
7f24bc58
MG
4217;;; {`cond-expand' for SRFI-0 support.}
4218;;;
4219;;; This syntactic form expands into different commands or
4220;;; definitions, depending on the features provided by the Scheme
4221;;; implementation.
4222;;;
4223;;; Syntax:
4224;;;
4225;;; <cond-expand>
4226;;; --> (cond-expand <cond-expand-clause>+)
4227;;; | (cond-expand <cond-expand-clause>* (else <command-or-definition>))
4228;;; <cond-expand-clause>
4229;;; --> (<feature-requirement> <command-or-definition>*)
4230;;; <feature-requirement>
4231;;; --> <feature-identifier>
4232;;; | (and <feature-requirement>*)
4233;;; | (or <feature-requirement>*)
4234;;; | (not <feature-requirement>)
4235;;; <feature-identifier>
4236;;; --> <a symbol which is the name or alias of a SRFI>
4237;;;
4238;;; Additionally, this implementation provides the
4239;;; <feature-identifier>s `guile' and `r5rs', so that programs can
4240;;; determine the implementation type and the supported standard.
4241;;;
7f24bc58 4242;;; Remember to update the features list when adding more SRFIs.
3d2ada2f 4243;;;
7f24bc58 4244
b9b8f9da 4245(define %cond-expand-features
edb6de0b
MW
4246 ;; This should contain only features that are present in core Guile,
4247 ;; before loading any modules. Modular features are handled by
4248 ;; placing 'cond-expand-provide' in the relevant module.
018733ff 4249 '(guile
60c8ad9e 4250 guile-2
688291fe 4251 guile-2.2
018733ff
KR
4252 r5rs
4253 srfi-0 ;; cond-expand itself
edb6de0b 4254 srfi-4 ;; homogeneous numeric vectors
6dce942c 4255 srfi-6 ;; string ports
4a276c08
MV
4256 srfi-13 ;; string library
4257 srfi-14 ;; character sets
61d50919 4258 srfi-16 ;; case-lambda
9670f238 4259 srfi-23 ;; `error` procedure
61d50919 4260 srfi-30 ;; nested multi-line comments
9670f238 4261 srfi-39 ;; parameterize
2d6a3144 4262 srfi-46 ;; basic syntax-rules extensions
344d68d5 4263 srfi-55 ;; require-extension
08b609aa 4264 srfi-61 ;; general cond clause
b306fae0 4265 srfi-62 ;; s-expression comments
da81e75d 4266 srfi-87 ;; => in case clauses
bf9eb54a 4267 srfi-105 ;; curly infix expressions
018733ff 4268 ))
1d00af09 4269
b9b8f9da
MG
4270;; This table maps module public interfaces to the list of features.
4271;;
4272(define %cond-expand-table (make-hash-table 31))
4273
4274;; Add one or more features to the `cond-expand' feature list of the
4275;; module `module'.
4276;;
4277(define (cond-expand-provide module features)
4278 (let ((mod (module-public-interface module)))
4279 (and mod
9b5a0d84
AW
4280 (hashq-set! %cond-expand-table mod
4281 (append (hashq-ref %cond-expand-table mod '())
4282 features)))))
b9b8f9da 4283
1fdd5bec
AW
4284(define-syntax cond-expand
4285 (lambda (x)
4286 (define (module-has-feature? mod sym)
4287 (or-map (lambda (mod)
4288 (memq sym (hashq-ref %cond-expand-table mod '())))
4289 (module-uses mod)))
4290
4291 (define (condition-matches? condition)
4292 (syntax-case condition (and or not)
4293 ((and c ...)
4294 (and-map condition-matches? #'(c ...)))
4295 ((or c ...)
4296 (or-map condition-matches? #'(c ...)))
4297 ((not c)
4298 (if (condition-matches? #'c) #f #t))
4299 (c
4300 (identifier? #'c)
4301 (let ((sym (syntax->datum #'c)))
4302 (if (memq sym %cond-expand-features)
4303 #t
4304 (module-has-feature? (current-module) sym))))))
4305
4306 (define (match clauses alternate)
4307 (syntax-case clauses ()
4308 (((condition form ...) . rest)
4309 (if (condition-matches? #'condition)
4310 #'(begin form ...)
4311 (match #'rest alternate)))
4312 (() (alternate))))
4313
4314 (syntax-case x (else)
4315 ((_ clause ... (else form ...))
4316 (match #'(clause ...)
4317 (lambda ()
4318 #'(begin form ...))))
4319 ((_ clause ...)
4320 (match #'(clause ...)
4321 (lambda ()
4322 (syntax-violation 'cond-expand "unfulfilled cond-expand" x)))))))
0f2d19dd 4323
f41be016
MG
4324;; This procedure gets called from the startup code with a list of
4325;; numbers, which are the numbers of the SRFIs to be loaded on startup.
4326;;
4327(define (use-srfis srfis)
9a18d8d4
KR
4328 (process-use-modules
4329 (map (lambda (num)
9b5a0d84
AW
4330 (list (list 'srfi (string->symbol
4331 (string-append "srfi-" (number->string num))))))
4332 srfis)))
f8a502cb 4333
0f2d19dd 4334\f
9d774814 4335
344d68d5
RB
4336;;; srfi-55: require-extension
4337;;;
4338
6669cd81
AW
4339(define-syntax require-extension
4340 (lambda (x)
4341 (syntax-case x (srfi)
4342 ((_ (srfi n ...))
4343 (and-map integer? (syntax->datum #'(n ...)))
4344 (with-syntax
4345 (((srfi-n ...)
4346 (map (lambda (n)
4347 (datum->syntax x (symbol-append 'srfi- n)))
4348 (map string->symbol
4349 (map number->string (syntax->datum #'(n ...)))))))
4350 #'(use-modules (srfi srfi-n) ...)))
4351 ((_ (type arg ...))
4352 (identifier? #'type)
4353 (syntax-violation 'require-extension "Not a recognized extension type"
4354 x)))))
344d68d5
RB
4355
4356\f
165b10dd
AR
4357;;; Defining transparently inlinable procedures
4358;;;
4359
4360(define-syntax define-inlinable
4361 ;; Define a macro and a procedure such that direct calls are inlined, via
4362 ;; the macro expansion, whereas references in non-call contexts refer to
4363 ;; the procedure. Inspired by the `define-integrable' macro by Dybvig et al.
4364 (lambda (x)
4365 ;; Use a space in the prefix to avoid potential -Wunused-toplevel
4366 ;; warning
4367 (define prefix (string->symbol "% "))
4368 (define (make-procedure-name name)
4369 (datum->syntax name
4370 (symbol-append prefix (syntax->datum name)
4371 '-procedure)))
4372
4373 (syntax-case x ()
4374 ((_ (name formals ...) body ...)
4375 (identifier? #'name)
4376 (with-syntax ((proc-name (make-procedure-name #'name))
4377 ((args ...) (generate-temporaries #'(formals ...))))
4378 #`(begin
4379 (define (proc-name formals ...)
ea3ca4e4 4380 (syntax-parameterize ((name (identifier-syntax proc-name)))
2844ab85 4381 body ...))
ea3ca4e4 4382 (define-syntax-parameter name
165b10dd
AR
4383 (lambda (x)
4384 (syntax-case x ()
4385 ((_ args ...)
ea3ca4e4 4386 #'((syntax-parameterize ((name (identifier-syntax proc-name)))
2844ab85
AW
4387 (lambda (formals ...)
4388 body ...))
165b10dd 4389 args ...))
89ffbb1c
MW
4390 ((_ a (... ...))
4391 (syntax-violation 'name "Wrong number of arguments" x))
165b10dd
AR
4392 (_
4393 (identifier? x)
4394 #'proc-name))))))))))
4395
4396\f
344d68d5 4397
755457ec
MD
4398(define using-readline?
4399 (let ((using-readline? (make-fluid)))
4400 (make-procedure-with-setter
4401 (lambda () (fluid-ref using-readline?))
4402 (lambda (v) (fluid-set! using-readline? v)))))
4403
4d31f0da 4404\f
3d2ada2f
DH
4405
4406;;; {Deprecated stuff}
4407;;;
4408
3d2ada2f 4409(begin-deprecated
0ea72faa 4410 (module-use! the-scm-module (resolve-interface '(ice-9 deprecated))))
3d2ada2f
DH
4411
4412\f
4413
68fcf711
AW
4414;;; SRFI-4 in the default environment. FIXME: we should figure out how
4415;;; to deprecate this.
3d2ada2f 4416;;;
6eb396fe 4417
a2689737
AW
4418;; FIXME:
4419(module-use! the-scm-module (resolve-interface '(srfi srfi-4)))
4420
68fcf711
AW
4421\f
4422
4423;;; A few identifiers that need to be defined in this file are really
4424;;; internal implementation details. We shove them off into internal
4425;;; modules, removing them from the (guile) module.
4426;;;
4427
4428(define-module (system syntax))
4429
4430(let ()
4431 (define (steal-bindings! from to ids)
4432 (for-each
4433 (lambda (sym)
4434 (let ((v (module-local-variable from sym)))
4435 (module-remove! from sym)
4436 (module-add! to sym v)))
4437 ids)
4438 (module-export! to ids))
4439
4440 (steal-bindings! the-root-module (resolve-module '(system syntax))
4441 '(syntax-local-binding
4442 syntax-module
f9685f43
AW
4443 syntax-locally-bound-identifiers
4444 syntax-session-id)))
68fcf711
AW
4445
4446
4447\f
4448
4449;;; Place the user in the guile-user module.
4450;;;
4451
7cf64a0a 4452;; Set filename to #f to prevent reload.
68623e8e 4453(define-module (guile-user)
7cf64a0a
AW
4454 #:autoload (system base compile) (compile compile-file)
4455 #:filename #f)
6d36532c 4456
7385dc12
LC
4457;; Remain in the `(guile)' module at compilation-time so that the
4458;; `-Wunused-toplevel' warning works as expected.
4459(eval-when (compile) (set-current-module the-root-module))
4460
20edfbbd 4461;;; boot-9.scm ends here