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