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