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