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