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