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