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