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