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