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