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