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