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