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