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