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