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