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