module-name before syncase is booted
[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 ;;; {Features}
44 ;;;
45
46 (define (provide sym)
47 (if (not (memq sym *features*))
48 (set! *features* (cons sym *features*))))
49
50 ;; Return #t iff FEATURE is available to this Guile interpreter. In SLIB,
51 ;; provided? also checks to see if the module is available. We should do that
52 ;; too, but don't.
53
54 (define (provided? feature)
55 (and (memq feature *features*) #t))
56
57 ;; let format alias simple-format until the more complete version is loaded
58
59 (define format simple-format)
60
61 ;; this is scheme wrapping the C code so the final pred call is a tail call,
62 ;; per SRFI-13 spec
63 (define (string-any char_pred s . rest)
64 (let ((start (if (null? rest)
65 0 (car rest)))
66 (end (if (or (null? rest) (null? (cdr rest)))
67 (string-length s) (cadr rest))))
68 (if (and (procedure? char_pred)
69 (> end start)
70 (<= end (string-length s))) ;; let c-code handle range error
71 (or (string-any-c-code char_pred s start (1- end))
72 (char_pred (string-ref s (1- end))))
73 (string-any-c-code char_pred s start end))))
74
75 ;; this is scheme wrapping the C code so the final pred call is a tail call,
76 ;; per SRFI-13 spec
77 (define (string-every char_pred s . rest)
78 (let ((start (if (null? rest)
79 0 (car rest)))
80 (end (if (or (null? rest) (null? (cdr rest)))
81 (string-length s) (cadr rest))))
82 (if (and (procedure? char_pred)
83 (> end start)
84 (<= end (string-length s))) ;; let c-code handle range error
85 (and (string-every-c-code char_pred s start (1- end))
86 (char_pred (string-ref s (1- end))))
87 (string-every-c-code char_pred s start end))))
88
89 ;; A variant of string-fill! that we keep for compatability
90 ;;
91 (define (substring-fill! str start end fill)
92 (string-fill! str fill start end))
93
94 \f
95
96 ;; Before the module system boots, there are no module names. But
97 ;; psyntax does want a module-name definition, so give it one.
98 (define (module-name x)
99 #f)
100
101 ;; (eval-when (situation...) form...)
102 ;;
103 ;; Evaluate certain code based on the situation that eval-when is used
104 ;; in. There are three situations defined.
105 ;;
106 ;; `load' triggers when a file is loaded via `load', or when a compiled
107 ;; file is loaded.
108 ;;
109 ;; `compile' triggers when an expression is compiled.
110 ;;
111 ;; `eval' triggers when code is evaluated interactively, as at the REPL
112 ;; or via the `compile' or `eval' procedures.
113
114 ;; NB: this macro is only ever expanded by the interpreter. The compiler
115 ;; notices it and interprets the situations differently.
116 (define eval-when
117 (procedure->memoizing-macro
118 (lambda (exp env)
119 (let ((situations (cadr exp))
120 (body (cddr exp)))
121 (if (or (memq 'load situations)
122 (memq 'eval situations))
123 `(begin . ,body))))))
124
125 \f
126
127 ;; Before compiling, make sure any symbols are resolved in the (guile)
128 ;; module, the primary location of those symbols, rather than in
129 ;; (guile-user), the default module that we compile in.
130
131 (eval-when (compile)
132 (set-current-module (resolve-module '(guile))))
133
134 ;;; {Defmacros}
135 ;;;
136 ;;; Depends on: features, eval-case
137 ;;;
138
139 (define macro-table (make-weak-key-hash-table 61))
140 (define xformer-table (make-weak-key-hash-table 61))
141
142 (define (defmacro? m) (hashq-ref macro-table m))
143 (define (assert-defmacro?! m) (hashq-set! macro-table m #t))
144 (define (defmacro-transformer m) (hashq-ref xformer-table m))
145 (define (set-defmacro-transformer! m t) (hashq-set! xformer-table m t))
146
147 (define defmacro:transformer
148 (lambda (f)
149 (let* ((xform (lambda (exp env)
150 (copy-tree (apply f (cdr exp)))))
151 (a (procedure->memoizing-macro xform)))
152 (assert-defmacro?! a)
153 (set-defmacro-transformer! a f)
154 a)))
155
156
157 (define defmacro
158 (let ((defmacro-transformer
159 (lambda (name parms . body)
160 (let ((transformer `(lambda ,parms ,@body)))
161 `(eval-when
162 (eval load compile)
163 (define ,name (defmacro:transformer ,transformer)))))))
164 (defmacro:transformer defmacro-transformer)))
165
166
167 ;; XXX - should the definition of the car really be looked up in the
168 ;; current module?
169
170 (define (macroexpand-1 e)
171 (cond
172 ((pair? e) (let* ((a (car e))
173 (val (and (symbol? a) (local-ref (list a)))))
174 (if (defmacro? val)
175 (apply (defmacro-transformer val) (cdr e))
176 e)))
177 (#t e)))
178
179 (define (macroexpand e)
180 (cond
181 ((pair? e) (let* ((a (car e))
182 (val (and (symbol? a) (local-ref (list a)))))
183 (if (defmacro? val)
184 (macroexpand (apply (defmacro-transformer val) (cdr e)))
185 e)))
186 (#t e)))
187
188 (provide 'defmacro)
189
190 \f
191
192 ;;; {Deprecation}
193 ;;;
194 ;;; Depends on: defmacro
195 ;;;
196
197 (defmacro begin-deprecated forms
198 (if (include-deprecated-features)
199 `(begin ,@forms)
200 `(begin)))
201
202 \f
203
204 ;;; {Simple Debugging Tools}
205 ;;;
206
207 ;; peek takes any number of arguments, writes them to the
208 ;; current ouput port, and returns the last argument.
209 ;; It is handy to wrap around an expression to look at
210 ;; a value each time is evaluated, e.g.:
211 ;;
212 ;; (+ 10 (troublesome-fn))
213 ;; => (+ 10 (pk 'troublesome-fn-returned (troublesome-fn)))
214 ;;
215
216 (define (peek . stuff)
217 (newline)
218 (display ";;; ")
219 (write stuff)
220 (newline)
221 (car (last-pair stuff)))
222
223 (define pk peek)
224
225 (define (warn . stuff)
226 (with-output-to-port (current-error-port)
227 (lambda ()
228 (newline)
229 (display ";;; WARNING ")
230 (display stuff)
231 (newline)
232 (car (last-pair stuff)))))
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 ;;; {Compiled module}
2125
2126 (if (not (defined? 'load-compiled))
2127 (define load-compiled #f))
2128
2129 \f
2130
2131 ;;; {Autoloading modules}
2132 ;;;
2133
2134 (define autoloads-in-progress '())
2135
2136 ;; This function is called from "modules.c". If you change it, be
2137 ;; sure to update "modules.c" as well.
2138
2139 (define (try-module-autoload module-name)
2140 (let* ((reverse-name (reverse module-name))
2141 (name (symbol->string (car reverse-name)))
2142 (dir-hint-module-name (reverse (cdr reverse-name)))
2143 (dir-hint (apply string-append
2144 (map (lambda (elt)
2145 (string-append (symbol->string elt) "/"))
2146 dir-hint-module-name))))
2147 (resolve-module dir-hint-module-name #f)
2148 (and (not (autoload-done-or-in-progress? dir-hint name))
2149 (let ((didit #f))
2150 (define (load-file proc file)
2151 (save-module-excursion (lambda () (proc file)))
2152 (set! didit #t))
2153 (dynamic-wind
2154 (lambda () (autoload-in-progress! dir-hint name))
2155 (lambda ()
2156 (let ((file (in-vicinity dir-hint name)))
2157 (let ((compiled (and load-compiled
2158 (%search-load-path
2159 (string-append file ".go"))))
2160 (source (%search-load-path file)))
2161 (cond ((and source
2162 (or (not compiled)
2163 (< (stat:mtime (stat compiled))
2164 (stat:mtime (stat source)))))
2165 (if compiled
2166 (warn "source file" source "newer than" compiled))
2167 (with-fluid* current-reader #f
2168 (lambda () (load-file primitive-load source))))
2169 (compiled
2170 (load-file load-compiled compiled))))))
2171 (lambda () (set-autoloaded! dir-hint name didit)))
2172 didit))))
2173
2174 \f
2175
2176 ;;; {Dynamic linking of modules}
2177 ;;;
2178
2179 (define autoloads-done '((guile . guile)))
2180
2181 (define (autoload-done-or-in-progress? p m)
2182 (let ((n (cons p m)))
2183 (->bool (or (member n autoloads-done)
2184 (member n autoloads-in-progress)))))
2185
2186 (define (autoload-done! p m)
2187 (let ((n (cons p m)))
2188 (set! autoloads-in-progress
2189 (delete! n autoloads-in-progress))
2190 (or (member n autoloads-done)
2191 (set! autoloads-done (cons n autoloads-done)))))
2192
2193 (define (autoload-in-progress! p m)
2194 (let ((n (cons p m)))
2195 (set! autoloads-done
2196 (delete! n autoloads-done))
2197 (set! autoloads-in-progress (cons n autoloads-in-progress))))
2198
2199 (define (set-autoloaded! p m done?)
2200 (if done?
2201 (autoload-done! p m)
2202 (let ((n (cons p m)))
2203 (set! autoloads-done (delete! n autoloads-done))
2204 (set! autoloads-in-progress (delete! n autoloads-in-progress)))))
2205
2206 \f
2207
2208 ;;; {Run-time options}
2209 ;;;
2210
2211 (defmacro define-option-interface (option-group)
2212 (let* ((option-name car)
2213 (option-value cadr)
2214 (option-documentation caddr)
2215
2216 ;; Below follow the macros defining the run-time option interfaces.
2217
2218 (make-options (lambda (interface)
2219 `(lambda args
2220 (cond ((null? args) (,interface))
2221 ((list? (car args))
2222 (,interface (car args)) (,interface))
2223 (else (for-each
2224 (lambda (option)
2225 (display (option-name option))
2226 (if (< (string-length
2227 (symbol->string (option-name option)))
2228 8)
2229 (display #\tab))
2230 (display #\tab)
2231 (display (option-value option))
2232 (display #\tab)
2233 (display (option-documentation option))
2234 (newline))
2235 (,interface #t)))))))
2236
2237 (make-enable (lambda (interface)
2238 `(lambda flags
2239 (,interface (append flags (,interface)))
2240 (,interface))))
2241
2242 (make-disable (lambda (interface)
2243 `(lambda flags
2244 (let ((options (,interface)))
2245 (for-each (lambda (flag)
2246 (set! options (delq! flag options)))
2247 flags)
2248 (,interface options)
2249 (,interface))))))
2250 (let* ((interface (car option-group))
2251 (options/enable/disable (cadr option-group)))
2252 `(begin
2253 (define ,(car options/enable/disable)
2254 ,(make-options interface))
2255 (define ,(cadr options/enable/disable)
2256 ,(make-enable interface))
2257 (define ,(caddr options/enable/disable)
2258 ,(make-disable interface))
2259 (defmacro ,(caaddr option-group) (opt val)
2260 `(,',(car options/enable/disable)
2261 (append (,',(car options/enable/disable))
2262 (list ',opt ,val))))))))
2263
2264 (define-option-interface
2265 (eval-options-interface
2266 (eval-options eval-enable eval-disable)
2267 (eval-set!)))
2268
2269 (define-option-interface
2270 (debug-options-interface
2271 (debug-options debug-enable debug-disable)
2272 (debug-set!)))
2273
2274 (define-option-interface
2275 (evaluator-traps-interface
2276 (traps trap-enable trap-disable)
2277 (trap-set!)))
2278
2279 (define-option-interface
2280 (read-options-interface
2281 (read-options read-enable read-disable)
2282 (read-set!)))
2283
2284 (define-option-interface
2285 (print-options-interface
2286 (print-options print-enable print-disable)
2287 (print-set!)))
2288
2289 \f
2290
2291 ;;; {Running Repls}
2292 ;;;
2293
2294 (define (repl read evaler print)
2295 (let loop ((source (read (current-input-port))))
2296 (print (evaler source))
2297 (loop (read (current-input-port)))))
2298
2299 ;; A provisional repl that acts like the SCM repl:
2300 ;;
2301 (define scm-repl-silent #f)
2302 (define (assert-repl-silence v) (set! scm-repl-silent v))
2303
2304 (define *unspecified* (if #f #f))
2305 (define (unspecified? v) (eq? v *unspecified*))
2306
2307 (define scm-repl-print-unspecified #f)
2308 (define (assert-repl-print-unspecified v) (set! scm-repl-print-unspecified v))
2309
2310 (define scm-repl-verbose #f)
2311 (define (assert-repl-verbosity v) (set! scm-repl-verbose v))
2312
2313 (define scm-repl-prompt "guile> ")
2314
2315 (define (set-repl-prompt! v) (set! scm-repl-prompt v))
2316
2317 (define (default-pre-unwind-handler key . args)
2318 (save-stack pre-unwind-handler-dispatch)
2319 (apply throw key args))
2320
2321 (define (pre-unwind-handler-dispatch key . args)
2322 (apply default-pre-unwind-handler key args))
2323
2324 (define abort-hook (make-hook))
2325
2326 ;; these definitions are used if running a script.
2327 ;; otherwise redefined in error-catching-loop.
2328 (define (set-batch-mode?! arg) #t)
2329 (define (batch-mode?) #t)
2330
2331 (define (error-catching-loop thunk)
2332 (let ((status #f)
2333 (interactive #t))
2334 (define (loop first)
2335 (let ((next
2336 (catch #t
2337
2338 (lambda ()
2339 (call-with-unblocked-asyncs
2340 (lambda ()
2341 (with-traps
2342 (lambda ()
2343 (first)
2344
2345 ;; This line is needed because mark
2346 ;; doesn't do closures quite right.
2347 ;; Unreferenced locals should be
2348 ;; collected.
2349 (set! first #f)
2350 (let loop ((v (thunk)))
2351 (loop (thunk)))
2352 #f)))))
2353
2354 (lambda (key . args)
2355 (case key
2356 ((quit)
2357 (set! status args)
2358 #f)
2359
2360 ((switch-repl)
2361 (apply throw 'switch-repl args))
2362
2363 ((abort)
2364 ;; This is one of the closures that require
2365 ;; (set! first #f) above
2366 ;;
2367 (lambda ()
2368 (run-hook abort-hook)
2369 (force-output (current-output-port))
2370 (display "ABORT: " (current-error-port))
2371 (write args (current-error-port))
2372 (newline (current-error-port))
2373 (if interactive
2374 (begin
2375 (if (and
2376 (not has-shown-debugger-hint?)
2377 (not (memq 'backtrace
2378 (debug-options-interface)))
2379 (stack? (fluid-ref the-last-stack)))
2380 (begin
2381 (newline (current-error-port))
2382 (display
2383 "Type \"(backtrace)\" to get more information or \"(debug)\" to enter the debugger.\n"
2384 (current-error-port))
2385 (set! has-shown-debugger-hint? #t)))
2386 (force-output (current-error-port)))
2387 (begin
2388 (primitive-exit 1)))
2389 (set! stack-saved? #f)))
2390
2391 (else
2392 ;; This is the other cons-leak closure...
2393 (lambda ()
2394 (cond ((= (length args) 4)
2395 (apply handle-system-error key args))
2396 (else
2397 (apply bad-throw key args)))))))
2398
2399 ;; Note that having just `pre-unwind-handler-dispatch'
2400 ;; here is connected with the mechanism that
2401 ;; produces a nice backtrace upon error. If, for
2402 ;; example, this is replaced with (lambda args
2403 ;; (apply pre-unwind-handler-dispatch args)), the stack
2404 ;; cutting (in save-stack) goes wrong and ends up
2405 ;; saving no stack at all, so there is no
2406 ;; backtrace.
2407 pre-unwind-handler-dispatch)))
2408
2409 (if next (loop next) status)))
2410 (set! set-batch-mode?! (lambda (arg)
2411 (cond (arg
2412 (set! interactive #f)
2413 (restore-signals))
2414 (#t
2415 (error "sorry, not implemented")))))
2416 (set! batch-mode? (lambda () (not interactive)))
2417 (call-with-blocked-asyncs
2418 (lambda () (loop (lambda () #t))))))
2419
2420 ;;(define the-last-stack (make-fluid)) Defined by scm_init_backtrace ()
2421 (define before-signal-stack (make-fluid))
2422 (define stack-saved? #f)
2423
2424 (define (save-stack . narrowing)
2425 (or stack-saved?
2426 (cond ((not (memq 'debug (debug-options-interface)))
2427 (fluid-set! the-last-stack #f)
2428 (set! stack-saved? #t))
2429 (else
2430 (fluid-set!
2431 the-last-stack
2432 (case (stack-id #t)
2433 ((repl-stack)
2434 (apply make-stack #t save-stack primitive-eval #t 0 narrowing))
2435 ((load-stack)
2436 (apply make-stack #t save-stack 0 #t 0 narrowing))
2437 ((tk-stack)
2438 (apply make-stack #t save-stack tk-stack-mark #t 0 narrowing))
2439 ((#t)
2440 (apply make-stack #t save-stack 0 1 narrowing))
2441 (else
2442 (let ((id (stack-id #t)))
2443 (and (procedure? id)
2444 (apply make-stack #t save-stack id #t 0 narrowing))))))
2445 (set! stack-saved? #t)))))
2446
2447 (define before-error-hook (make-hook))
2448 (define after-error-hook (make-hook))
2449 (define before-backtrace-hook (make-hook))
2450 (define after-backtrace-hook (make-hook))
2451
2452 (define has-shown-debugger-hint? #f)
2453
2454 (define (handle-system-error key . args)
2455 (let ((cep (current-error-port)))
2456 (cond ((not (stack? (fluid-ref the-last-stack))))
2457 ((memq 'backtrace (debug-options-interface))
2458 (let ((highlights (if (or (eq? key 'wrong-type-arg)
2459 (eq? key 'out-of-range))
2460 (list-ref args 3)
2461 '())))
2462 (run-hook before-backtrace-hook)
2463 (newline cep)
2464 (display "Backtrace:\n")
2465 (display-backtrace (fluid-ref the-last-stack) cep
2466 #f #f highlights)
2467 (newline cep)
2468 (run-hook after-backtrace-hook))))
2469 (run-hook before-error-hook)
2470 (apply display-error (fluid-ref the-last-stack) cep args)
2471 (run-hook after-error-hook)
2472 (force-output cep)
2473 (throw 'abort key)))
2474
2475 (define (quit . args)
2476 (apply throw 'quit args))
2477
2478 (define exit quit)
2479
2480 ;;(define has-shown-backtrace-hint? #f) Defined by scm_init_backtrace ()
2481
2482 ;; Replaced by C code:
2483 ;;(define (backtrace)
2484 ;; (if (fluid-ref the-last-stack)
2485 ;; (begin
2486 ;; (newline)
2487 ;; (display-backtrace (fluid-ref the-last-stack) (current-output-port))
2488 ;; (newline)
2489 ;; (if (and (not has-shown-backtrace-hint?)
2490 ;; (not (memq 'backtrace (debug-options-interface))))
2491 ;; (begin
2492 ;; (display
2493 ;;"Type \"(debug-enable 'backtrace)\" if you would like a backtrace
2494 ;;automatically if an error occurs in the future.\n")
2495 ;; (set! has-shown-backtrace-hint? #t))))
2496 ;; (display "No backtrace available.\n")))
2497
2498 (define (error-catching-repl r e p)
2499 (error-catching-loop
2500 (lambda ()
2501 (call-with-values (lambda () (e (r)))
2502 (lambda the-values (for-each p the-values))))))
2503
2504 (define (gc-run-time)
2505 (cdr (assq 'gc-time-taken (gc-stats))))
2506
2507 (define before-read-hook (make-hook))
2508 (define after-read-hook (make-hook))
2509 (define before-eval-hook (make-hook 1))
2510 (define after-eval-hook (make-hook 1))
2511 (define before-print-hook (make-hook 1))
2512 (define after-print-hook (make-hook 1))
2513
2514 ;;; The default repl-reader function. We may override this if we've
2515 ;;; the readline library.
2516 (define repl-reader
2517 (lambda (prompt)
2518 (display (if (string? prompt) prompt (prompt)))
2519 (force-output)
2520 (run-hook before-read-hook)
2521 ((or (fluid-ref current-reader) read) (current-input-port))))
2522
2523 (define (scm-style-repl)
2524
2525 (letrec (
2526 (start-gc-rt #f)
2527 (start-rt #f)
2528 (repl-report-start-timing (lambda ()
2529 (set! start-gc-rt (gc-run-time))
2530 (set! start-rt (get-internal-run-time))))
2531 (repl-report (lambda ()
2532 (display ";;; ")
2533 (display (inexact->exact
2534 (* 1000 (/ (- (get-internal-run-time) start-rt)
2535 internal-time-units-per-second))))
2536 (display " msec (")
2537 (display (inexact->exact
2538 (* 1000 (/ (- (gc-run-time) start-gc-rt)
2539 internal-time-units-per-second))))
2540 (display " msec in gc)\n")))
2541
2542 (consume-trailing-whitespace
2543 (lambda ()
2544 (let ((ch (peek-char)))
2545 (cond
2546 ((eof-object? ch))
2547 ((or (char=? ch #\space) (char=? ch #\tab))
2548 (read-char)
2549 (consume-trailing-whitespace))
2550 ((char=? ch #\newline)
2551 (read-char))))))
2552 (-read (lambda ()
2553 (let ((val
2554 (let ((prompt (cond ((string? scm-repl-prompt)
2555 scm-repl-prompt)
2556 ((thunk? scm-repl-prompt)
2557 (scm-repl-prompt))
2558 (scm-repl-prompt "> ")
2559 (else ""))))
2560 (repl-reader prompt))))
2561
2562 ;; As described in R4RS, the READ procedure updates the
2563 ;; port to point to the first character past the end of
2564 ;; the external representation of the object. This
2565 ;; means that it doesn't consume the newline typically
2566 ;; found after an expression. This means that, when
2567 ;; debugging Guile with GDB, GDB gets the newline, which
2568 ;; it often interprets as a "continue" command, making
2569 ;; breakpoints kind of useless. So, consume any
2570 ;; trailing newline here, as well as any whitespace
2571 ;; before it.
2572 ;; But not if EOF, for control-D.
2573 (if (not (eof-object? val))
2574 (consume-trailing-whitespace))
2575 (run-hook after-read-hook)
2576 (if (eof-object? val)
2577 (begin
2578 (repl-report-start-timing)
2579 (if scm-repl-verbose
2580 (begin
2581 (newline)
2582 (display ";;; EOF -- quitting")
2583 (newline)))
2584 (quit 0)))
2585 val)))
2586
2587 (-eval (lambda (sourc)
2588 (repl-report-start-timing)
2589 (run-hook before-eval-hook sourc)
2590 (let ((val (start-stack 'repl-stack
2591 ;; If you change this procedure
2592 ;; (primitive-eval), please also
2593 ;; modify the repl-stack case in
2594 ;; save-stack so that stack cutting
2595 ;; continues to work.
2596 (primitive-eval sourc))))
2597 (run-hook after-eval-hook sourc)
2598 val)))
2599
2600
2601 (-print (let ((maybe-print (lambda (result)
2602 (if (or scm-repl-print-unspecified
2603 (not (unspecified? result)))
2604 (begin
2605 (write result)
2606 (newline))))))
2607 (lambda (result)
2608 (if (not scm-repl-silent)
2609 (begin
2610 (run-hook before-print-hook result)
2611 (maybe-print result)
2612 (run-hook after-print-hook result)
2613 (if scm-repl-verbose
2614 (repl-report))
2615 (force-output))))))
2616
2617 (-quit (lambda (args)
2618 (if scm-repl-verbose
2619 (begin
2620 (display ";;; QUIT executed, repl exitting")
2621 (newline)
2622 (repl-report)))
2623 args))
2624
2625 (-abort (lambda ()
2626 (if scm-repl-verbose
2627 (begin
2628 (display ";;; ABORT executed.")
2629 (newline)
2630 (repl-report)))
2631 (repl -read -eval -print))))
2632
2633 (let ((status (error-catching-repl -read
2634 -eval
2635 -print)))
2636 (-quit status))))
2637
2638
2639 \f
2640
2641 ;;; {IOTA functions: generating lists of numbers}
2642 ;;;
2643
2644 (define (iota n)
2645 (let loop ((count (1- n)) (result '()))
2646 (if (< count 0) result
2647 (loop (1- count) (cons count result)))))
2648
2649 \f
2650
2651 ;;; {collect}
2652 ;;;
2653 ;;; Similar to `begin' but returns a list of the results of all constituent
2654 ;;; forms instead of the result of the last form.
2655 ;;; (The definition relies on the current left-to-right
2656 ;;; order of evaluation of operands in applications.)
2657 ;;;
2658
2659 (defmacro collect forms
2660 (cons 'list forms))
2661
2662 \f
2663
2664 ;;; {with-fluids}
2665 ;;;
2666
2667 ;; with-fluids is a convenience wrapper for the builtin procedure
2668 ;; `with-fluids*'. The syntax is just like `let':
2669 ;;
2670 ;; (with-fluids ((fluid val)
2671 ;; ...)
2672 ;; body)
2673
2674 (defmacro with-fluids (bindings . body)
2675 (let ((fluids (map car bindings))
2676 (values (map cadr bindings)))
2677 (if (and (= (length fluids) 1) (= (length values) 1))
2678 `(with-fluid* ,(car fluids) ,(car values) (lambda () ,@body))
2679 `(with-fluids* (list ,@fluids) (list ,@values)
2680 (lambda () ,@body)))))
2681
2682 \f
2683
2684 ;;; {Macros}
2685 ;;;
2686
2687 ;; actually....hobbit might be able to hack these with a little
2688 ;; coaxing
2689 ;;
2690
2691 (define (primitive-macro? m)
2692 (and (macro? m)
2693 (not (macro-transformer m))))
2694
2695 (defmacro define-macro (first . rest)
2696 (let ((name (if (symbol? first) first (car first)))
2697 (transformer
2698 (if (symbol? first)
2699 (car rest)
2700 `(lambda ,(cdr first) ,@rest))))
2701 `(eval-when
2702 (eval load compile)
2703 (define ,name (defmacro:transformer ,transformer)))))
2704
2705
2706 \f
2707
2708 ;;; {While}
2709 ;;;
2710 ;;; with `continue' and `break'.
2711 ;;;
2712
2713 ;; The inner `do' loop avoids re-establishing a catch every iteration,
2714 ;; that's only necessary if continue is actually used. A new key is
2715 ;; generated every time, so break and continue apply to their originating
2716 ;; `while' even when recursing.
2717 ;;
2718 ;; FIXME: This macro is unintentionally unhygienic with respect to let,
2719 ;; make-symbol, do, throw, catch, lambda, and not.
2720 ;;
2721 (define-macro (while cond . body)
2722 (let ((keyvar (make-symbol "while-keyvar")))
2723 `(let ((,keyvar (make-symbol "while-key")))
2724 (do ()
2725 ((catch ,keyvar
2726 (lambda ()
2727 (let ((break (lambda () (throw ,keyvar #t)))
2728 (continue (lambda () (throw ,keyvar #f))))
2729 (do ()
2730 ((not ,cond))
2731 ,@body)
2732 #t))
2733 (lambda (key arg)
2734 arg)))))))
2735
2736
2737 \f
2738
2739 ;;; {Module System Macros}
2740 ;;;
2741
2742 ;; Return a list of expressions that evaluate to the appropriate
2743 ;; arguments for resolve-interface according to SPEC.
2744
2745 (eval-when
2746 (compile)
2747 (if (memq 'prefix (read-options))
2748 (error "boot-9 must be compiled with #:kw, not :kw")))
2749
2750 (define (compile-interface-spec spec)
2751 (define (make-keyarg sym key quote?)
2752 (cond ((or (memq sym spec)
2753 (memq key spec))
2754 => (lambda (rest)
2755 (if quote?
2756 (list key (list 'quote (cadr rest)))
2757 (list key (cadr rest)))))
2758 (else
2759 '())))
2760 (define (map-apply func list)
2761 (map (lambda (args) (apply func args)) list))
2762 (define keys
2763 ;; sym key quote?
2764 '((:select #:select #t)
2765 (:hide #:hide #t)
2766 (:prefix #:prefix #t)
2767 (:renamer #:renamer #f)))
2768 (if (not (pair? (car spec)))
2769 `(',spec)
2770 `(',(car spec)
2771 ,@(apply append (map-apply make-keyarg keys)))))
2772
2773 (define (keyword-like-symbol->keyword sym)
2774 (symbol->keyword (string->symbol (substring (symbol->string sym) 1))))
2775
2776 (define (compile-define-module-args args)
2777 ;; Just quote everything except #:use-module and #:use-syntax. We
2778 ;; need to know about all arguments regardless since we want to turn
2779 ;; symbols that look like keywords into real keywords, and the
2780 ;; keyword args in a define-module form are not regular
2781 ;; (i.e. no-backtrace doesn't take a value).
2782 (let loop ((compiled-args `((quote ,(car args))))
2783 (args (cdr args)))
2784 (cond ((null? args)
2785 (reverse! compiled-args))
2786 ;; symbol in keyword position
2787 ((symbol? (car args))
2788 (loop compiled-args
2789 (cons (keyword-like-symbol->keyword (car args)) (cdr args))))
2790 ((memq (car args) '(#:no-backtrace #:pure))
2791 (loop (cons (car args) compiled-args)
2792 (cdr args)))
2793 ((null? (cdr args))
2794 (error "keyword without value:" (car args)))
2795 ((memq (car args) '(#:use-module #:use-syntax))
2796 (loop (cons* `(list ,@(compile-interface-spec (cadr args)))
2797 (car args)
2798 compiled-args)
2799 (cddr args)))
2800 ((eq? (car args) #:autoload)
2801 (loop (cons* `(quote ,(caddr args))
2802 `(quote ,(cadr args))
2803 (car args)
2804 compiled-args)
2805 (cdddr args)))
2806 (else
2807 (loop (cons* `(quote ,(cadr args))
2808 (car args)
2809 compiled-args)
2810 (cddr args))))))
2811
2812 (defmacro define-module args
2813 `(eval-when
2814 (eval load compile)
2815 (let ((m (process-define-module
2816 (list ,@(compile-define-module-args args)))))
2817 (set-current-module m)
2818 m)))
2819
2820 ;; The guts of the use-modules macro. Add the interfaces of the named
2821 ;; modules to the use-list of the current module, in order.
2822
2823 ;; This function is called by "modules.c". If you change it, be sure
2824 ;; to change scm_c_use_module as well.
2825
2826 (define (process-use-modules module-interface-args)
2827 (let ((interfaces (map (lambda (mif-args)
2828 (or (apply resolve-interface mif-args)
2829 (error "no such module" mif-args)))
2830 module-interface-args)))
2831 (call-with-deferred-observers
2832 (lambda ()
2833 (module-use-interfaces! (current-module) interfaces)))))
2834
2835 (defmacro use-modules modules
2836 `(eval-when
2837 (eval load compile)
2838 (process-use-modules
2839 (list ,@(map (lambda (m)
2840 `(list ,@(compile-interface-spec m)))
2841 modules)))
2842 *unspecified*))
2843
2844 (defmacro use-syntax (spec)
2845 `(eval-when
2846 (eval load compile)
2847 ,@(if (pair? spec)
2848 `((process-use-modules (list
2849 (list ,@(compile-interface-spec spec))))
2850 (set-module-transformer! (current-module)
2851 ,(car (last-pair spec))))
2852 `((set-module-transformer! (current-module) ,spec)))
2853 *unspecified*))
2854
2855 ;; Dirk:FIXME:: This incorrect (according to R5RS) syntax needs to be changed
2856 ;; as soon as guile supports hygienic macros.
2857 (define define-private define)
2858
2859 (defmacro define-public args
2860 (define (syntax)
2861 (error "bad syntax" (list 'define-public args)))
2862 (define (defined-name n)
2863 (cond
2864 ((symbol? n) n)
2865 ((pair? n) (defined-name (car n)))
2866 (else (syntax))))
2867 (cond
2868 ((null? args)
2869 (syntax))
2870 (#t
2871 (let ((name (defined-name (car args))))
2872 `(begin
2873 (define-private ,@args)
2874 (export ,name))))))
2875
2876 (defmacro defmacro-public args
2877 (define (syntax)
2878 (error "bad syntax" (list 'defmacro-public args)))
2879 (define (defined-name n)
2880 (cond
2881 ((symbol? n) n)
2882 (else (syntax))))
2883 (cond
2884 ((null? args)
2885 (syntax))
2886 (#t
2887 (let ((name (defined-name (car args))))
2888 `(begin
2889 (export-syntax ,name)
2890 (defmacro ,@args))))))
2891
2892 ;; Export a local variable
2893
2894 ;; This function is called from "modules.c". If you change it, be
2895 ;; sure to update "modules.c" as well.
2896
2897 (define (module-export! m names)
2898 (let ((public-i (module-public-interface m)))
2899 (for-each (lambda (name)
2900 (let ((var (module-ensure-local-variable! m name)))
2901 (module-add! public-i name var)))
2902 names)))
2903
2904 (define (module-replace! m names)
2905 (let ((public-i (module-public-interface m)))
2906 (for-each (lambda (name)
2907 (let ((var (module-ensure-local-variable! m name)))
2908 (set-object-property! var 'replace #t)
2909 (module-add! public-i name var)))
2910 names)))
2911
2912 ;; Re-export a imported variable
2913 ;;
2914 (define (module-re-export! m names)
2915 (let ((public-i (module-public-interface m)))
2916 (for-each (lambda (name)
2917 (let ((var (module-variable m name)))
2918 (cond ((not var)
2919 (error "Undefined variable:" name))
2920 ((eq? var (module-local-variable m name))
2921 (error "re-exporting local variable:" name))
2922 (else
2923 (module-add! public-i name var)))))
2924 names)))
2925
2926 (defmacro export names
2927 `(call-with-deferred-observers
2928 (lambda ()
2929 (module-export! (current-module) ',names))))
2930
2931 (defmacro re-export names
2932 `(call-with-deferred-observers
2933 (lambda ()
2934 (module-re-export! (current-module) ',names))))
2935
2936 (defmacro export-syntax names
2937 `(export ,@names))
2938
2939 (defmacro re-export-syntax names
2940 `(re-export ,@names))
2941
2942 (define load load-module)
2943
2944 \f
2945
2946 ;;; {Compiler interface}
2947 ;;;
2948 ;;; The full compiler interface can be found in (system). Here we put a
2949 ;;; few useful procedures into the global namespace.
2950
2951 (module-autoload! the-scm-module
2952 '(system base compile)
2953 '(compile
2954 compile-time-environment))
2955
2956
2957 \f
2958
2959 ;;; {Parameters}
2960 ;;;
2961
2962 (define make-mutable-parameter
2963 (let ((make (lambda (fluid converter)
2964 (lambda args
2965 (if (null? args)
2966 (fluid-ref fluid)
2967 (fluid-set! fluid (converter (car args))))))))
2968 (lambda (init . converter)
2969 (let ((fluid (make-fluid))
2970 (converter (if (null? converter)
2971 identity
2972 (car converter))))
2973 (fluid-set! fluid (converter init))
2974 (make fluid converter)))))
2975
2976 \f
2977
2978 ;;; {Handling of duplicate imported bindings}
2979 ;;;
2980
2981 ;; Duplicate handlers take the following arguments:
2982 ;;
2983 ;; module importing module
2984 ;; name conflicting name
2985 ;; int1 old interface where name occurs
2986 ;; val1 value of binding in old interface
2987 ;; int2 new interface where name occurs
2988 ;; val2 value of binding in new interface
2989 ;; var previous resolution or #f
2990 ;; val value of previous resolution
2991 ;;
2992 ;; A duplicate handler can take three alternative actions:
2993 ;;
2994 ;; 1. return #f => leave responsibility to next handler
2995 ;; 2. exit with an error
2996 ;; 3. return a variable resolving the conflict
2997 ;;
2998
2999 (define duplicate-handlers
3000 (let ((m (make-module 7)))
3001
3002 (define (check module name int1 val1 int2 val2 var val)
3003 (scm-error 'misc-error
3004 #f
3005 "~A: `~A' imported from both ~A and ~A"
3006 (list (module-name module)
3007 name
3008 (module-name int1)
3009 (module-name int2))
3010 #f))
3011
3012 (define (warn module name int1 val1 int2 val2 var val)
3013 (format (current-error-port)
3014 "WARNING: ~A: `~A' imported from both ~A and ~A\n"
3015 (module-name module)
3016 name
3017 (module-name int1)
3018 (module-name int2))
3019 #f)
3020
3021 (define (replace module name int1 val1 int2 val2 var val)
3022 (let ((old (or (and var (object-property var 'replace) var)
3023 (module-variable int1 name)))
3024 (new (module-variable int2 name)))
3025 (if (object-property old 'replace)
3026 (and (or (eq? old new)
3027 (not (object-property new 'replace)))
3028 old)
3029 (and (object-property new 'replace)
3030 new))))
3031
3032 (define (warn-override-core module name int1 val1 int2 val2 var val)
3033 (and (eq? int1 the-scm-module)
3034 (begin
3035 (format (current-error-port)
3036 "WARNING: ~A: imported module ~A overrides core binding `~A'\n"
3037 (module-name module)
3038 (module-name int2)
3039 name)
3040 (module-local-variable int2 name))))
3041
3042 (define (first module name int1 val1 int2 val2 var val)
3043 (or var (module-local-variable int1 name)))
3044
3045 (define (last module name int1 val1 int2 val2 var val)
3046 (module-local-variable int2 name))
3047
3048 (define (noop module name int1 val1 int2 val2 var val)
3049 #f)
3050
3051 (set-module-name! m 'duplicate-handlers)
3052 (set-module-kind! m 'interface)
3053 (module-define! m 'check check)
3054 (module-define! m 'warn warn)
3055 (module-define! m 'replace replace)
3056 (module-define! m 'warn-override-core warn-override-core)
3057 (module-define! m 'first first)
3058 (module-define! m 'last last)
3059 (module-define! m 'merge-generics noop)
3060 (module-define! m 'merge-accessors noop)
3061 m))
3062
3063 (define (lookup-duplicates-handlers handler-names)
3064 (and handler-names
3065 (map (lambda (handler-name)
3066 (or (module-symbol-local-binding
3067 duplicate-handlers handler-name #f)
3068 (error "invalid duplicate handler name:"
3069 handler-name)))
3070 (if (list? handler-names)
3071 handler-names
3072 (list handler-names)))))
3073
3074 (define default-duplicate-binding-procedures
3075 (make-mutable-parameter #f))
3076
3077 (define default-duplicate-binding-handler
3078 (make-mutable-parameter '(replace warn-override-core warn last)
3079 (lambda (handler-names)
3080 (default-duplicate-binding-procedures
3081 (lookup-duplicates-handlers handler-names))
3082 handler-names)))
3083
3084 \f
3085
3086 ;;; {`cond-expand' for SRFI-0 support.}
3087 ;;;
3088 ;;; This syntactic form expands into different commands or
3089 ;;; definitions, depending on the features provided by the Scheme
3090 ;;; implementation.
3091 ;;;
3092 ;;; Syntax:
3093 ;;;
3094 ;;; <cond-expand>
3095 ;;; --> (cond-expand <cond-expand-clause>+)
3096 ;;; | (cond-expand <cond-expand-clause>* (else <command-or-definition>))
3097 ;;; <cond-expand-clause>
3098 ;;; --> (<feature-requirement> <command-or-definition>*)
3099 ;;; <feature-requirement>
3100 ;;; --> <feature-identifier>
3101 ;;; | (and <feature-requirement>*)
3102 ;;; | (or <feature-requirement>*)
3103 ;;; | (not <feature-requirement>)
3104 ;;; <feature-identifier>
3105 ;;; --> <a symbol which is the name or alias of a SRFI>
3106 ;;;
3107 ;;; Additionally, this implementation provides the
3108 ;;; <feature-identifier>s `guile' and `r5rs', so that programs can
3109 ;;; determine the implementation type and the supported standard.
3110 ;;;
3111 ;;; Currently, the following feature identifiers are supported:
3112 ;;;
3113 ;;; guile r5rs srfi-0 srfi-4 srfi-6 srfi-13 srfi-14 srfi-55 srfi-61
3114 ;;;
3115 ;;; Remember to update the features list when adding more SRFIs.
3116 ;;;
3117
3118 (define %cond-expand-features
3119 ;; Adjust the above comment when changing this.
3120 '(guile
3121 r5rs
3122 srfi-0 ;; cond-expand itself
3123 srfi-4 ;; homogenous numeric vectors
3124 srfi-6 ;; open-input-string etc, in the guile core
3125 srfi-13 ;; string library
3126 srfi-14 ;; character sets
3127 srfi-55 ;; require-extension
3128 srfi-61 ;; general cond clause
3129 ))
3130
3131 ;; This table maps module public interfaces to the list of features.
3132 ;;
3133 (define %cond-expand-table (make-hash-table 31))
3134
3135 ;; Add one or more features to the `cond-expand' feature list of the
3136 ;; module `module'.
3137 ;;
3138 (define (cond-expand-provide module features)
3139 (let ((mod (module-public-interface module)))
3140 (and mod
3141 (hashq-set! %cond-expand-table mod
3142 (append (hashq-ref %cond-expand-table mod '())
3143 features)))))
3144
3145 (define cond-expand
3146 (procedure->memoizing-macro
3147 (lambda (exp env)
3148 (let ((clauses (cdr exp))
3149 (syntax-error (lambda (cl)
3150 (error "invalid clause in `cond-expand'" cl))))
3151 (letrec
3152 ((test-clause
3153 (lambda (clause)
3154 (cond
3155 ((symbol? clause)
3156 (or (memq clause %cond-expand-features)
3157 (let lp ((uses (module-uses (env-module env))))
3158 (if (pair? uses)
3159 (or (memq clause
3160 (hashq-ref %cond-expand-table
3161 (car uses) '()))
3162 (lp (cdr uses)))
3163 #f))))
3164 ((pair? clause)
3165 (cond
3166 ((eq? 'and (car clause))
3167 (let lp ((l (cdr clause)))
3168 (cond ((null? l)
3169 #t)
3170 ((pair? l)
3171 (and (test-clause (car l)) (lp (cdr l))))
3172 (else
3173 (syntax-error clause)))))
3174 ((eq? 'or (car clause))
3175 (let lp ((l (cdr clause)))
3176 (cond ((null? l)
3177 #f)
3178 ((pair? l)
3179 (or (test-clause (car l)) (lp (cdr l))))
3180 (else
3181 (syntax-error clause)))))
3182 ((eq? 'not (car clause))
3183 (cond ((not (pair? (cdr clause)))
3184 (syntax-error clause))
3185 ((pair? (cddr clause))
3186 ((syntax-error clause))))
3187 (not (test-clause (cadr clause))))
3188 (else
3189 (syntax-error clause))))
3190 (else
3191 (syntax-error clause))))))
3192 (let lp ((c clauses))
3193 (cond
3194 ((null? c)
3195 (error "Unfulfilled `cond-expand'"))
3196 ((not (pair? c))
3197 (syntax-error c))
3198 ((not (pair? (car c)))
3199 (syntax-error (car c)))
3200 ((test-clause (caar c))
3201 `(begin ,@(cdar c)))
3202 ((eq? (caar c) 'else)
3203 (if (pair? (cdr c))
3204 (syntax-error c))
3205 `(begin ,@(cdar c)))
3206 (else
3207 (lp (cdr c))))))))))
3208
3209 ;; This procedure gets called from the startup code with a list of
3210 ;; numbers, which are the numbers of the SRFIs to be loaded on startup.
3211 ;;
3212 (define (use-srfis srfis)
3213 (process-use-modules
3214 (map (lambda (num)
3215 (list (list 'srfi (string->symbol
3216 (string-append "srfi-" (number->string num))))))
3217 srfis)))
3218
3219 \f
3220
3221 ;;; srfi-55: require-extension
3222 ;;;
3223
3224 (define-macro (require-extension extension-spec)
3225 ;; This macro only handles the srfi extension, which, at present, is
3226 ;; the only one defined by the standard.
3227 (if (not (pair? extension-spec))
3228 (scm-error 'wrong-type-arg "require-extension"
3229 "Not an extension: ~S" (list extension-spec) #f))
3230 (let ((extension (car extension-spec))
3231 (extension-args (cdr extension-spec)))
3232 (case extension
3233 ((srfi)
3234 (let ((use-list '()))
3235 (for-each
3236 (lambda (i)
3237 (if (not (integer? i))
3238 (scm-error 'wrong-type-arg "require-extension"
3239 "Invalid srfi name: ~S" (list i) #f))
3240 (let ((srfi-sym (string->symbol
3241 (string-append "srfi-" (number->string i)))))
3242 (if (not (memq srfi-sym %cond-expand-features))
3243 (set! use-list (cons `(use-modules (srfi ,srfi-sym))
3244 use-list)))))
3245 extension-args)
3246 (if (pair? use-list)
3247 ;; i.e. (begin (use-modules x) (use-modules y) (use-modules z))
3248 `(begin ,@(reverse! use-list)))))
3249 (else
3250 (scm-error
3251 'wrong-type-arg "require-extension"
3252 "Not a recognized extension type: ~S" (list extension) #f)))))
3253
3254 \f
3255
3256 ;;; {Load emacs interface support if emacs option is given.}
3257 ;;;
3258
3259 (define (named-module-use! user usee)
3260 (module-use! (resolve-module user) (resolve-interface usee)))
3261
3262 (define (load-emacs-interface)
3263 (and (provided? 'debug-extensions)
3264 (debug-enable 'backtrace))
3265 (named-module-use! '(guile-user) '(ice-9 emacs)))
3266
3267 \f
3268
3269 (define using-readline?
3270 (let ((using-readline? (make-fluid)))
3271 (make-procedure-with-setter
3272 (lambda () (fluid-ref using-readline?))
3273 (lambda (v) (fluid-set! using-readline? v)))))
3274
3275 (define (top-repl)
3276 (let ((guile-user-module (resolve-module '(guile-user))))
3277
3278 ;; Load emacs interface support if emacs option is given.
3279 (if (and (module-defined? guile-user-module 'use-emacs-interface)
3280 (module-ref guile-user-module 'use-emacs-interface))
3281 (load-emacs-interface))
3282
3283 ;; Use some convenient modules (in reverse order)
3284
3285 (set-current-module guile-user-module)
3286 (process-use-modules
3287 (append
3288 '(((ice-9 r5rs))
3289 ((ice-9 session))
3290 ((ice-9 debug)))
3291 (if (provided? 'regex)
3292 '(((ice-9 regex)))
3293 '())
3294 (if (provided? 'threads)
3295 '(((ice-9 threads)))
3296 '())))
3297 ;; load debugger on demand
3298 (module-autoload! guile-user-module '(ice-9 debugger) '(debug))
3299
3300 ;; Note: SIGFPE, SIGSEGV and SIGBUS are actually "query-only" (see
3301 ;; scmsigs.c scm_sigaction_for_thread), so the handlers setup here have
3302 ;; no effect.
3303 (let ((old-handlers #f)
3304 (start-repl (module-ref (resolve-interface '(system repl repl))
3305 'start-repl))
3306 (signals (if (provided? 'posix)
3307 `((,SIGINT . "User interrupt")
3308 (,SIGFPE . "Arithmetic error")
3309 (,SIGSEGV
3310 . "Bad memory access (Segmentation violation)"))
3311 '())))
3312 ;; no SIGBUS on mingw
3313 (if (defined? 'SIGBUS)
3314 (set! signals (acons SIGBUS "Bad memory access (bus error)"
3315 signals)))
3316
3317 (dynamic-wind
3318
3319 ;; call at entry
3320 (lambda ()
3321 (let ((make-handler (lambda (msg)
3322 (lambda (sig)
3323 ;; Make a backup copy of the stack
3324 (fluid-set! before-signal-stack
3325 (fluid-ref the-last-stack))
3326 (save-stack 2)
3327 (scm-error 'signal
3328 #f
3329 msg
3330 #f
3331 (list sig))))))
3332 (set! old-handlers
3333 (map (lambda (sig-msg)
3334 (sigaction (car sig-msg)
3335 (make-handler (cdr sig-msg))))
3336 signals))))
3337
3338 ;; the protected thunk.
3339 (lambda ()
3340 (let ((status (start-repl 'scheme)))
3341 (run-hook exit-hook)
3342 status))
3343
3344 ;; call at exit.
3345 (lambda ()
3346 (map (lambda (sig-msg old-handler)
3347 (if (not (car old-handler))
3348 ;; restore original C handler.
3349 (sigaction (car sig-msg) #f)
3350 ;; restore Scheme handler, SIG_IGN or SIG_DFL.
3351 (sigaction (car sig-msg)
3352 (car old-handler)
3353 (cdr old-handler))))
3354 signals old-handlers))))))
3355
3356 ;;; This hook is run at the very end of an interactive session.
3357 ;;;
3358 (define exit-hook (make-hook))
3359
3360 \f
3361
3362 ;;; {Deprecated stuff}
3363 ;;;
3364
3365 (begin-deprecated
3366 (define (feature? sym)
3367 (issue-deprecation-warning
3368 "`feature?' is deprecated. Use `provided?' instead.")
3369 (provided? sym)))
3370
3371 (begin-deprecated
3372 (primitive-load-path "ice-9/deprecated"))
3373
3374 \f
3375
3376 ;;; Place the user in the guile-user module.
3377 ;;;
3378
3379 (define-module (guile-user))
3380
3381 ;;; boot-9.scm ends here