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