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