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