* srfi-1.scm (filter, filter!): Removed. (Now implemented in the core.)
[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
1448 (filter (lambda (m)
1449 (not (equal? (module-name m)
1450 (module-name interface))))
1451 (module-uses module))))
1452 (module-modified module))
1453
1454 ;; MODULE-USE-INTERFACES! module interfaces
1455 ;;
1456 ;; Same as MODULE-USE! but add multiple interfaces and check for duplicates
1457 ;;
1458 (define (module-use-interfaces! module interfaces)
1459 (let* ((duplicates-info (module-duplicates-info module))
1460 (duplicates-handlers? (car duplicates-info))
1461 (uses (module-uses module)))
1462 ;; remove duplicates-interface
1463 (set! uses (delq! (cdr duplicates-info) uses))
1464 ;; remove interfaces to be added
1465 (for-each (lambda (interface)
1466 (set! uses
1467 (filter (lambda (m)
1468 (not (equal? (module-name m)
1469 (module-name interface))))
1470 uses)))
1471 interfaces)
1472 ;; add interfaces to use list
1473 (set-module-uses! module uses)
1474 (for-each (lambda (interface)
1475 (and duplicates-handlers?
1476 ;; perform duplicate checking
1477 (process-duplicates module interface))
1478 (set! uses (cons interface uses))
1479 (set-module-uses! module uses))
1480 interfaces)
1481 ;; add duplicates interface
1482 (if (cdr duplicates-info)
1483 (set-module-uses! module (cons (cdr duplicates-info) uses)))
1484 (module-modified module)))
1485
1486 \f
1487 ;;; {Recursive Namespaces}
1488 ;;;
1489 ;;;
1490 ;;; A hierarchical namespace emerges if we consider some module to be
1491 ;;; root, and variables bound to modules as nested namespaces.
1492 ;;;
1493 ;;; The routines in this file manage variable names in hierarchical namespace.
1494 ;;; Each variable name is a list of elements, looked up in successively nested
1495 ;;; modules.
1496 ;;;
1497 ;;; (nested-ref some-root-module '(foo bar baz))
1498 ;;; => <value of a variable named baz in the module bound to bar in
1499 ;;; the module bound to foo in some-root-module>
1500 ;;;
1501 ;;;
1502 ;;; There are:
1503 ;;;
1504 ;;; ;; a-root is a module
1505 ;;; ;; name is a list of symbols
1506 ;;;
1507 ;;; nested-ref a-root name
1508 ;;; nested-set! a-root name val
1509 ;;; nested-define! a-root name val
1510 ;;; nested-remove! a-root name
1511 ;;;
1512 ;;;
1513 ;;; (current-module) is a natural choice for a-root so for convenience there are
1514 ;;; also:
1515 ;;;
1516 ;;; local-ref name == nested-ref (current-module) name
1517 ;;; local-set! name val == nested-set! (current-module) name val
1518 ;;; local-define! name val == nested-define! (current-module) name val
1519 ;;; local-remove! name == nested-remove! (current-module) name
1520 ;;;
1521
1522
1523 (define (nested-ref root names)
1524 (let loop ((cur root)
1525 (elts names))
1526 (cond
1527 ((null? elts) cur)
1528 ((not (module? cur)) #f)
1529 (else (loop (module-ref cur (car elts) #f) (cdr elts))))))
1530
1531 (define (nested-set! root names val)
1532 (let loop ((cur root)
1533 (elts names))
1534 (if (null? (cdr elts))
1535 (module-set! cur (car elts) val)
1536 (loop (module-ref cur (car elts)) (cdr elts)))))
1537
1538 (define (nested-define! root names val)
1539 (let loop ((cur root)
1540 (elts names))
1541 (if (null? (cdr elts))
1542 (module-define! cur (car elts) val)
1543 (loop (module-ref cur (car elts)) (cdr elts)))))
1544
1545 (define (nested-remove! root names)
1546 (let loop ((cur root)
1547 (elts names))
1548 (if (null? (cdr elts))
1549 (module-remove! cur (car elts))
1550 (loop (module-ref cur (car elts)) (cdr elts)))))
1551
1552 (define (local-ref names) (nested-ref (current-module) names))
1553 (define (local-set! names val) (nested-set! (current-module) names val))
1554 (define (local-define names val) (nested-define! (current-module) names val))
1555 (define (local-remove names) (nested-remove! (current-module) names))
1556
1557
1558 \f
1559 ;;; {The (app) module}
1560 ;;;
1561 ;;; The root of conventionally named objects not directly in the top level.
1562 ;;;
1563 ;;; (app modules)
1564 ;;; (app modules guile)
1565 ;;;
1566 ;;; The directory of all modules and the standard root module.
1567 ;;;
1568
1569 (define (module-public-interface m)
1570 (module-ref m '%module-public-interface #f))
1571 (define (set-module-public-interface! m i)
1572 (module-define! m '%module-public-interface i))
1573 (define (module-duplicates-info m)
1574 (or (module-ref m '%module-duplicates-info #f) (cons #f #f)))
1575 (define (set-module-duplicates-info! m i)
1576 (module-define! m '%module-duplicates-info i))
1577 (define (set-system-module! m s)
1578 (set-procedure-property! (module-eval-closure m) 'system-module s))
1579 (define the-root-module (make-root-module))
1580 (define the-scm-module (make-scm-module))
1581 (set-module-public-interface! the-root-module the-scm-module)
1582 (set-module-duplicates-info! the-root-module (cons #f #f))
1583 (set-module-name! the-root-module '(guile))
1584 (set-module-name! the-scm-module '(guile))
1585 (set-module-kind! the-scm-module 'interface)
1586 (for-each set-system-module! (list the-root-module the-scm-module) '(#t #t))
1587
1588 ;; NOTE: This binding is used in libguile/modules.c.
1589 ;;
1590 (define (make-modules-in module name)
1591 (if (null? name)
1592 module
1593 (cond
1594 ((module-ref module (car name) #f)
1595 => (lambda (m) (make-modules-in m (cdr name))))
1596 (else (let ((m (make-module 31)))
1597 (set-module-kind! m 'directory)
1598 (set-module-name! m (append (or (module-name module)
1599 '())
1600 (list (car name))))
1601 (module-define! module (car name) m)
1602 (make-modules-in m (cdr name)))))))
1603
1604 (define (beautify-user-module! module)
1605 (let ((interface (module-public-interface module)))
1606 (if (or (not interface)
1607 (eq? interface module))
1608 (let ((interface (make-module 31)))
1609 (set-module-name! interface (module-name module))
1610 (set-module-kind! interface 'interface)
1611 (set-module-public-interface! module interface)
1612 (set-module-duplicates-info!
1613 module
1614 (cons (default-module-duplicates-handler) #f)))))
1615 (if (and (not (memq the-scm-module (module-uses module)))
1616 (not (eq? module the-root-module)))
1617 (set-module-uses! module
1618 (append (module-uses module) (list the-scm-module)))))
1619
1620 ;; NOTE: This binding is used in libguile/modules.c.
1621 ;;
1622 (define (resolve-module name . maybe-autoload)
1623 (let ((full-name (append '(app modules) name)))
1624 (let ((already (local-ref full-name)))
1625 (if already
1626 ;; The module already exists...
1627 (if (and (or (null? maybe-autoload) (car maybe-autoload))
1628 (not (module-public-interface already)))
1629 ;; ...but we are told to load and it doesn't contain source, so
1630 (begin
1631 (try-load-module name)
1632 already)
1633 ;; simply return it.
1634 already)
1635 (begin
1636 ;; Try to autoload it if we are told so
1637 (if (or (null? maybe-autoload) (car maybe-autoload))
1638 (try-load-module name))
1639 ;; Get/create it.
1640 (make-modules-in (current-module) full-name))))))
1641
1642 ;; Cheat. These bindings are needed by modules.c, but we don't want
1643 ;; to move their real definition here because that would be unnatural.
1644 ;;
1645 (define try-module-autoload #f)
1646 (define process-define-module #f)
1647 (define process-use-modules #f)
1648 (define module-export! #f)
1649
1650 ;; This boots the module system. All bindings needed by modules.c
1651 ;; must have been defined by now.
1652 ;;
1653 (set-current-module the-root-module)
1654
1655 (define app (make-module 31))
1656 (local-define '(app modules) (make-module 31))
1657 (local-define '(app modules guile) the-root-module)
1658
1659 ;; (define-special-value '(app modules new-ws) (lambda () (make-scm-module)))
1660
1661 (define (try-load-module name)
1662 (try-module-autoload name))
1663
1664 (define (purify-module! module)
1665 "Removes bindings in MODULE which are inherited from the (guile) module."
1666 (let ((use-list (module-uses module)))
1667 (if (and (pair? use-list)
1668 (eq? (car (last-pair use-list)) the-scm-module))
1669 (set-module-uses! module (reverse (cdr (reverse use-list)))))))
1670
1671 ;; Return a module that is an interface to the module designated by
1672 ;; NAME.
1673 ;;
1674 ;; `resolve-interface' takes four keyword arguments:
1675 ;;
1676 ;; #:select SELECTION
1677 ;;
1678 ;; SELECTION is a list of binding-specs to be imported; A binding-spec
1679 ;; is either a symbol or a pair of symbols (ORIG . SEEN), where ORIG
1680 ;; is the name in the used module and SEEN is the name in the using
1681 ;; module. Note that SEEN is also passed through RENAMER, below. The
1682 ;; default is to select all bindings. If you specify no selection but
1683 ;; a renamer, only the bindings that already exist in the used module
1684 ;; are made available in the interface. Bindings that are added later
1685 ;; are not picked up.
1686 ;;
1687 ;; #:hide BINDINGS
1688 ;;
1689 ;; BINDINGS is a list of bindings which should not be imported.
1690 ;;
1691 ;; #:prefix PREFIX
1692 ;;
1693 ;; PREFIX is a symbol that will be appended to each exported name.
1694 ;; The default is to not perform any renaming.
1695 ;;
1696 ;; #:renamer RENAMER
1697 ;;
1698 ;; RENAMER is a procedure that takes a symbol and returns its new
1699 ;; name. The default is not perform any renaming.
1700 ;;
1701 ;; Signal "no code for module" error if module name is not resolvable
1702 ;; or its public interface is not available. Signal "no binding"
1703 ;; error if selected binding does not exist in the used module.
1704 ;;
1705 (define (resolve-interface name . args)
1706
1707 (define (get-keyword-arg args kw def)
1708 (cond ((memq kw args)
1709 => (lambda (kw-arg)
1710 (if (null? (cdr kw-arg))
1711 (error "keyword without value: " kw))
1712 (cadr kw-arg)))
1713 (else
1714 def)))
1715
1716 (let* ((select (get-keyword-arg args #:select #f))
1717 (hide (get-keyword-arg args #:hide '()))
1718 (renamer (or (get-keyword-arg args #:renamer #f)
1719 (let ((prefix (get-keyword-arg args #:prefix #f)))
1720 (and prefix (symbol-prefix-proc prefix)))
1721 identity))
1722 (module (resolve-module name))
1723 (public-i (and module (module-public-interface module))))
1724 (and (or (not module) (not public-i))
1725 (error "no code for module" name))
1726 (if (and (not select) (null? hide) (eq? renamer identity))
1727 public-i
1728 (let ((selection (or select (module-map (lambda (sym var) sym)
1729 public-i)))
1730 (custom-i (make-module 31)))
1731 (set-module-kind! custom-i 'custom-interface)
1732 (set-module-name! custom-i name)
1733 ;; XXX - should use a lazy binder so that changes to the
1734 ;; used module are picked up automatically.
1735 (for-each (lambda (bspec)
1736 (let* ((direct? (symbol? bspec))
1737 (orig (if direct? bspec (car bspec)))
1738 (seen (if direct? bspec (cdr bspec)))
1739 (var (or (module-local-variable public-i orig)
1740 (module-local-variable module orig)
1741 (error
1742 ;; fixme: format manually for now
1743 (simple-format
1744 #f "no binding `~A' in module ~A"
1745 orig name)))))
1746 (if (memq orig hide)
1747 (set! hide (delq! orig hide))
1748 (module-add! custom-i
1749 (renamer seen)
1750 var))))
1751 selection)
1752 ;; Check that we are not hiding bindings which don't exist
1753 (for-each (lambda (binding)
1754 (if (not (module-local-variable public-i binding))
1755 (error
1756 (simple-format
1757 #f "no binding `~A' to hide in module ~A"
1758 binding name))))
1759 hide)
1760 custom-i))))
1761
1762 (define (symbol-prefix-proc prefix)
1763 (lambda (symbol)
1764 (symbol-append prefix symbol)))
1765
1766 ;; This function is called from "modules.c". If you change it, be
1767 ;; sure to update "modules.c" as well.
1768
1769 (define (process-define-module args)
1770 (let* ((module-id (car args))
1771 (module (resolve-module module-id #f))
1772 (kws (cdr args))
1773 (unrecognized (lambda (arg)
1774 (error "unrecognized define-module argument" arg))))
1775 (beautify-user-module! module)
1776 (let loop ((kws kws)
1777 (reversed-interfaces '())
1778 (exports '())
1779 (re-exports '())
1780 (replacements '()))
1781 (if (null? kws)
1782 (begin
1783 (module-use-interfaces! module (reverse reversed-interfaces))
1784 (module-export! module exports)
1785 (module-replace! module replacements)
1786 (module-re-export! module re-exports))
1787 (case (car kws)
1788 ((#:use-module #:use-syntax)
1789 (or (pair? (cdr kws))
1790 (unrecognized kws))
1791 (let* ((interface-args (cadr kws))
1792 (interface (apply resolve-interface interface-args)))
1793 (and (eq? (car kws) #:use-syntax)
1794 (or (symbol? (caar interface-args))
1795 (error "invalid module name for use-syntax"
1796 (car interface-args)))
1797 (set-module-transformer!
1798 module
1799 (module-ref interface
1800 (car (last-pair (car interface-args)))
1801 #f)))
1802 (loop (cddr kws)
1803 (cons interface reversed-interfaces)
1804 exports
1805 re-exports
1806 replacements)))
1807 ((#:autoload)
1808 (or (and (pair? (cdr kws)) (pair? (cddr kws)))
1809 (unrecognized kws))
1810 (loop (cdddr kws)
1811 (cons (make-autoload-interface module
1812 (cadr kws)
1813 (caddr kws))
1814 reversed-interfaces)
1815 exports
1816 re-exports
1817 replacements))
1818 ((#:no-backtrace)
1819 (set-system-module! module #t)
1820 (loop (cdr kws) reversed-interfaces exports re-exports replacements))
1821 ((#:pure)
1822 (purify-module! module)
1823 (loop (cdr kws) reversed-interfaces exports re-exports replacements))
1824 ((#:duplicates)
1825 (if (not (pair? (cdr kws)))
1826 (unrecognized kws))
1827 (set-car! (module-duplicates-info module)
1828 (lookup-duplicates-handlers (cadr kws)))
1829 (loop (cddr kws) reversed-interfaces exports re-exports replacements))
1830 ((#:export #:export-syntax)
1831 (or (pair? (cdr kws))
1832 (unrecognized kws))
1833 (loop (cddr kws)
1834 reversed-interfaces
1835 (append (cadr kws) exports)
1836 re-exports
1837 replacements))
1838 ((#:re-export #:re-export-syntax)
1839 (or (pair? (cdr kws))
1840 (unrecognized kws))
1841 (loop (cddr kws)
1842 reversed-interfaces
1843 exports
1844 (append (cadr kws) re-exports)
1845 replacements))
1846 ((#:replace #:replace-syntax)
1847 (or (pair? (cdr kws))
1848 (unrecognized kws))
1849 (loop (cddr kws)
1850 reversed-interfaces
1851 exports
1852 re-exports
1853 (append (cadr kws) replacements)))
1854 (else
1855 (unrecognized kws)))))
1856 (run-hook module-defined-hook module)
1857 module))
1858
1859 ;; `module-defined-hook' is a hook that is run whenever a new module
1860 ;; is defined. Its members are called with one argument, the new
1861 ;; module.
1862 (define module-defined-hook (make-hook 1))
1863
1864 ;;; {Autoload}
1865
1866 (define (make-autoload-interface module name bindings)
1867 (let ((b (lambda (a sym definep)
1868 (and (memq sym bindings)
1869 (let ((i (module-public-interface (resolve-module name))))
1870 (if (not i)
1871 (error "missing interface for module" name))
1872 ;; Replace autoload-interface with interface
1873 (set-car! (memq a (module-uses module)) i)
1874 (module-local-variable i sym))))))
1875 (module-constructor #() '() b #f #f name 'autoload
1876 '() (make-weak-value-hash-table 31) 0)))
1877
1878 ;;; {Compiled module}
1879
1880 (define load-compiled #f)
1881
1882 \f
1883 ;;; {Autoloading modules}
1884
1885 (define autoloads-in-progress '())
1886
1887 ;; This function is called from "modules.c". If you change it, be
1888 ;; sure to update "modules.c" as well.
1889
1890 (define (try-module-autoload module-name)
1891 (let* ((reverse-name (reverse module-name))
1892 (name (symbol->string (car reverse-name)))
1893 (dir-hint-module-name (reverse (cdr reverse-name)))
1894 (dir-hint (apply string-append
1895 (map (lambda (elt)
1896 (string-append (symbol->string elt) "/"))
1897 dir-hint-module-name))))
1898 (resolve-module dir-hint-module-name #f)
1899 (and (not (autoload-done-or-in-progress? dir-hint name))
1900 (let ((didit #f))
1901 (define (load-file proc file)
1902 (save-module-excursion (lambda () (proc file)))
1903 (set! didit #t))
1904 (dynamic-wind
1905 (lambda () (autoload-in-progress! dir-hint name))
1906 (lambda ()
1907 (let ((file (in-vicinity dir-hint name)))
1908 (cond ((and load-compiled
1909 (%search-load-path (string-append file ".go")))
1910 => (lambda (full)
1911 (load-file load-compiled full)))
1912 ((%search-load-path file)
1913 => (lambda (full)
1914 (load-file primitive-load full))))))
1915 (lambda () (set-autoloaded! dir-hint name didit)))
1916 didit))))
1917
1918 \f
1919 ;;; Dynamic linking of modules
1920
1921 (define autoloads-done '((guile . guile)))
1922
1923 (define (autoload-done-or-in-progress? p m)
1924 (let ((n (cons p m)))
1925 (->bool (or (member n autoloads-done)
1926 (member n autoloads-in-progress)))))
1927
1928 (define (autoload-done! p m)
1929 (let ((n (cons p m)))
1930 (set! autoloads-in-progress
1931 (delete! n autoloads-in-progress))
1932 (or (member n autoloads-done)
1933 (set! autoloads-done (cons n autoloads-done)))))
1934
1935 (define (autoload-in-progress! p m)
1936 (let ((n (cons p m)))
1937 (set! autoloads-done
1938 (delete! n autoloads-done))
1939 (set! autoloads-in-progress (cons n autoloads-in-progress))))
1940
1941 (define (set-autoloaded! p m done?)
1942 (if done?
1943 (autoload-done! p m)
1944 (let ((n (cons p m)))
1945 (set! autoloads-done (delete! n autoloads-done))
1946 (set! autoloads-in-progress (delete! n autoloads-in-progress)))))
1947
1948
1949
1950 \f
1951 ;; {EVAL-CASE}
1952 ;;
1953 ;; (eval-case ((situation*) forms)* (else forms)?)
1954 ;;
1955 ;; Evaluate certain code based on the situation that eval-case is used
1956 ;; in. The only defined situation right now is `load-toplevel' which
1957 ;; triggers for code evaluated at the top-level, for example from the
1958 ;; REPL or when loading a file.
1959
1960 (define eval-case
1961 (procedure->memoizing-macro
1962 (lambda (exp env)
1963 (define (toplevel-env? env)
1964 (or (not (pair? env)) (not (pair? (car env)))))
1965 (define (syntax)
1966 (error "syntax error in eval-case"))
1967 (let loop ((clauses (cdr exp)))
1968 (cond
1969 ((null? clauses)
1970 #f)
1971 ((not (list? (car clauses)))
1972 (syntax))
1973 ((eq? 'else (caar clauses))
1974 (or (null? (cdr clauses))
1975 (syntax))
1976 (cons 'begin (cdar clauses)))
1977 ((not (list? (caar clauses)))
1978 (syntax))
1979 ((and (toplevel-env? env)
1980 (memq 'load-toplevel (caar clauses)))
1981 (cons 'begin (cdar clauses)))
1982 (else
1983 (loop (cdr clauses))))))))
1984
1985 \f
1986 ;;; {Macros}
1987 ;;;
1988
1989 (define (primitive-macro? m)
1990 (and (macro? m)
1991 (not (macro-transformer m))))
1992
1993 ;;; {Defmacros}
1994 ;;;
1995 (define macro-table (make-weak-key-hash-table 61))
1996 (define xformer-table (make-weak-key-hash-table 61))
1997
1998 (define (defmacro? m) (hashq-ref macro-table m))
1999 (define (assert-defmacro?! m) (hashq-set! macro-table m #t))
2000 (define (defmacro-transformer m) (hashq-ref xformer-table m))
2001 (define (set-defmacro-transformer! m t) (hashq-set! xformer-table m t))
2002
2003 (define defmacro:transformer
2004 (lambda (f)
2005 (let* ((xform (lambda (exp env)
2006 (copy-tree (apply f (cdr exp)))))
2007 (a (procedure->memoizing-macro xform)))
2008 (assert-defmacro?! a)
2009 (set-defmacro-transformer! a f)
2010 a)))
2011
2012
2013 (define defmacro
2014 (let ((defmacro-transformer
2015 (lambda (name parms . body)
2016 (let ((transformer `(lambda ,parms ,@body)))
2017 `(eval-case
2018 ((load-toplevel)
2019 (define ,name (defmacro:transformer ,transformer)))
2020 (else
2021 (error "defmacro can only be used at the top level")))))))
2022 (defmacro:transformer defmacro-transformer)))
2023
2024 (define defmacro:syntax-transformer
2025 (lambda (f)
2026 (procedure->syntax
2027 (lambda (exp env)
2028 (copy-tree (apply f (cdr exp)))))))
2029
2030
2031 ;; XXX - should the definition of the car really be looked up in the
2032 ;; current module?
2033
2034 (define (macroexpand-1 e)
2035 (cond
2036 ((pair? e) (let* ((a (car e))
2037 (val (and (symbol? a) (local-ref (list a)))))
2038 (if (defmacro? val)
2039 (apply (defmacro-transformer val) (cdr e))
2040 e)))
2041 (#t e)))
2042
2043 (define (macroexpand e)
2044 (cond
2045 ((pair? e) (let* ((a (car e))
2046 (val (and (symbol? a) (local-ref (list a)))))
2047 (if (defmacro? val)
2048 (macroexpand (apply (defmacro-transformer val) (cdr e)))
2049 e)))
2050 (#t e)))
2051
2052 (provide 'defmacro)
2053
2054 \f
2055
2056 ;;; {Run-time options}
2057
2058 (define define-option-interface
2059 (let* ((option-name car)
2060 (option-value cadr)
2061 (option-documentation caddr)
2062
2063 (print-option (lambda (option)
2064 (display (option-name option))
2065 (if (< (string-length
2066 (symbol->string (option-name option)))
2067 8)
2068 (display #\tab))
2069 (display #\tab)
2070 (display (option-value option))
2071 (display #\tab)
2072 (display (option-documentation option))
2073 (newline)))
2074
2075 ;; Below follow the macros defining the run-time option interfaces.
2076
2077 (make-options (lambda (interface)
2078 `(lambda args
2079 (cond ((null? args) (,interface))
2080 ((list? (car args))
2081 (,interface (car args)) (,interface))
2082 (else (for-each ,print-option
2083 (,interface #t)))))))
2084
2085 (make-enable (lambda (interface)
2086 `(lambda flags
2087 (,interface (append flags (,interface)))
2088 (,interface))))
2089
2090 (make-disable (lambda (interface)
2091 `(lambda flags
2092 (let ((options (,interface)))
2093 (for-each (lambda (flag)
2094 (set! options (delq! flag options)))
2095 flags)
2096 (,interface options)
2097 (,interface))))))
2098 (procedure->memoizing-macro
2099 (lambda (exp env)
2100 (let* ((option-group (cadr exp))
2101 (interface (car option-group))
2102 (options/enable/disable (cadr option-group)))
2103 `(begin
2104 (define ,(car options/enable/disable)
2105 ,(make-options interface))
2106 (define ,(cadr options/enable/disable)
2107 ,(make-enable interface))
2108 (define ,(caddr options/enable/disable)
2109 ,(make-disable interface))
2110 (defmacro ,(caaddr option-group) (opt val)
2111 `(,,(car options/enable/disable)
2112 (append (,,(car options/enable/disable))
2113 (list ',opt ,val))))))))))
2114
2115 (define-option-interface
2116 (eval-options-interface
2117 (eval-options eval-enable eval-disable)
2118 (eval-set!)))
2119
2120 (define-option-interface
2121 (debug-options-interface
2122 (debug-options debug-enable debug-disable)
2123 (debug-set!)))
2124
2125 (define-option-interface
2126 (evaluator-traps-interface
2127 (traps trap-enable trap-disable)
2128 (trap-set!)))
2129
2130 (define-option-interface
2131 (read-options-interface
2132 (read-options read-enable read-disable)
2133 (read-set!)))
2134
2135 (define-option-interface
2136 (print-options-interface
2137 (print-options print-enable print-disable)
2138 (print-set!)))
2139
2140 \f
2141
2142 ;;; {Running Repls}
2143 ;;;
2144
2145 (define (repl read evaler print)
2146 (let loop ((source (read (current-input-port))))
2147 (print (evaler source))
2148 (loop (read (current-input-port)))))
2149
2150 ;; A provisional repl that acts like the SCM repl:
2151 ;;
2152 (define scm-repl-silent #f)
2153 (define (assert-repl-silence v) (set! scm-repl-silent v))
2154
2155 (define *unspecified* (if #f #f))
2156 (define (unspecified? v) (eq? v *unspecified*))
2157
2158 (define scm-repl-print-unspecified #f)
2159 (define (assert-repl-print-unspecified v) (set! scm-repl-print-unspecified v))
2160
2161 (define scm-repl-verbose #f)
2162 (define (assert-repl-verbosity v) (set! scm-repl-verbose v))
2163
2164 (define scm-repl-prompt "guile> ")
2165
2166 (define (set-repl-prompt! v) (set! scm-repl-prompt v))
2167
2168 (define (default-lazy-handler key . args)
2169 (save-stack lazy-handler-dispatch)
2170 (apply throw key args))
2171
2172 (define (lazy-handler-dispatch key . args)
2173 (apply default-lazy-handler key args))
2174
2175 (define abort-hook (make-hook))
2176
2177 ;; these definitions are used if running a script.
2178 ;; otherwise redefined in error-catching-loop.
2179 (define (set-batch-mode?! arg) #t)
2180 (define (batch-mode?) #t)
2181
2182 (define (error-catching-loop thunk)
2183 (let ((status #f)
2184 (interactive #t))
2185 (define (loop first)
2186 (let ((next
2187 (catch #t
2188
2189 (lambda ()
2190 (lazy-catch #t
2191 (lambda ()
2192 (call-with-unblocked-asyncs
2193 (lambda ()
2194 (with-traps
2195 (lambda ()
2196 (first)
2197
2198 ;; This line is needed because mark
2199 ;; doesn't do closures quite right.
2200 ;; Unreferenced locals should be
2201 ;; collected.
2202 ;;
2203 (set! first #f)
2204 (let loop ((v (thunk)))
2205 (loop (thunk)))
2206 #f)))))
2207
2208 lazy-handler-dispatch))
2209
2210 (lambda (key . args)
2211 (case key
2212 ((quit)
2213 (set! status args)
2214 #f)
2215
2216 ((switch-repl)
2217 (apply throw 'switch-repl args))
2218
2219 ((abort)
2220 ;; This is one of the closures that require
2221 ;; (set! first #f) above
2222 ;;
2223 (lambda ()
2224 (run-hook abort-hook)
2225 (force-output (current-output-port))
2226 (display "ABORT: " (current-error-port))
2227 (write args (current-error-port))
2228 (newline (current-error-port))
2229 (if interactive
2230 (begin
2231 (if (and
2232 (not has-shown-debugger-hint?)
2233 (not (memq 'backtrace
2234 (debug-options-interface)))
2235 (stack? (fluid-ref the-last-stack)))
2236 (begin
2237 (newline (current-error-port))
2238 (display
2239 "Type \"(backtrace)\" to get more information or \"(debug)\" to enter the debugger.\n"
2240 (current-error-port))
2241 (set! has-shown-debugger-hint? #t)))
2242 (force-output (current-error-port)))
2243 (begin
2244 (primitive-exit 1)))
2245 (set! stack-saved? #f)))
2246
2247 (else
2248 ;; This is the other cons-leak closure...
2249 (lambda ()
2250 (cond ((= (length args) 4)
2251 (apply handle-system-error key args))
2252 (else
2253 (apply bad-throw key args))))))))))
2254 (if next (loop next) status)))
2255 (set! set-batch-mode?! (lambda (arg)
2256 (cond (arg
2257 (set! interactive #f)
2258 (restore-signals))
2259 (#t
2260 (error "sorry, not implemented")))))
2261 (set! batch-mode? (lambda () (not interactive)))
2262 (call-with-blocked-asyncs
2263 (lambda () (loop (lambda () #t))))))
2264
2265 ;;(define the-last-stack (make-fluid)) Defined by scm_init_backtrace ()
2266 (define before-signal-stack (make-fluid))
2267 (define stack-saved? #f)
2268
2269 (define (save-stack . narrowing)
2270 (or stack-saved?
2271 (cond ((not (memq 'debug (debug-options-interface)))
2272 (fluid-set! the-last-stack #f)
2273 (set! stack-saved? #t))
2274 (else
2275 (fluid-set!
2276 the-last-stack
2277 (case (stack-id #t)
2278 ((repl-stack)
2279 (apply make-stack #t save-stack primitive-eval #t 0 narrowing))
2280 ((load-stack)
2281 (apply make-stack #t save-stack 0 #t 0 narrowing))
2282 ((tk-stack)
2283 (apply make-stack #t save-stack tk-stack-mark #t 0 narrowing))
2284 ((#t)
2285 (apply make-stack #t save-stack 0 1 narrowing))
2286 (else
2287 (let ((id (stack-id #t)))
2288 (and (procedure? id)
2289 (apply make-stack #t save-stack id #t 0 narrowing))))))
2290 (set! stack-saved? #t)))))
2291
2292 (define before-error-hook (make-hook))
2293 (define after-error-hook (make-hook))
2294 (define before-backtrace-hook (make-hook))
2295 (define after-backtrace-hook (make-hook))
2296
2297 (define has-shown-debugger-hint? #f)
2298
2299 (define (handle-system-error key . args)
2300 (let ((cep (current-error-port)))
2301 (cond ((not (stack? (fluid-ref the-last-stack))))
2302 ((memq 'backtrace (debug-options-interface))
2303 (run-hook before-backtrace-hook)
2304 (newline cep)
2305 (display "Backtrace:\n")
2306 (display-backtrace (fluid-ref the-last-stack) cep)
2307 (newline cep)
2308 (run-hook after-backtrace-hook)))
2309 (run-hook before-error-hook)
2310 (apply display-error (fluid-ref the-last-stack) cep args)
2311 (run-hook after-error-hook)
2312 (force-output cep)
2313 (throw 'abort key)))
2314
2315 (define (quit . args)
2316 (apply throw 'quit args))
2317
2318 (define exit quit)
2319
2320 ;;(define has-shown-backtrace-hint? #f) Defined by scm_init_backtrace ()
2321
2322 ;; Replaced by C code:
2323 ;;(define (backtrace)
2324 ;; (if (fluid-ref the-last-stack)
2325 ;; (begin
2326 ;; (newline)
2327 ;; (display-backtrace (fluid-ref the-last-stack) (current-output-port))
2328 ;; (newline)
2329 ;; (if (and (not has-shown-backtrace-hint?)
2330 ;; (not (memq 'backtrace (debug-options-interface))))
2331 ;; (begin
2332 ;; (display
2333 ;;"Type \"(debug-enable 'backtrace)\" if you would like a backtrace
2334 ;;automatically if an error occurs in the future.\n")
2335 ;; (set! has-shown-backtrace-hint? #t))))
2336 ;; (display "No backtrace available.\n")))
2337
2338 (define (error-catching-repl r e p)
2339 (error-catching-loop
2340 (lambda ()
2341 (call-with-values (lambda () (e (r)))
2342 (lambda the-values (for-each p the-values))))))
2343
2344 (define (gc-run-time)
2345 (cdr (assq 'gc-time-taken (gc-stats))))
2346
2347 (define before-read-hook (make-hook))
2348 (define after-read-hook (make-hook))
2349 (define before-eval-hook (make-hook 1))
2350 (define after-eval-hook (make-hook 1))
2351 (define before-print-hook (make-hook 1))
2352 (define after-print-hook (make-hook 1))
2353
2354 ;;; The default repl-reader function. We may override this if we've
2355 ;;; the readline library.
2356 (define repl-reader
2357 (lambda (prompt)
2358 (display prompt)
2359 (force-output)
2360 (run-hook before-read-hook)
2361 (read (current-input-port))))
2362
2363 (define (scm-style-repl)
2364
2365 (letrec (
2366 (start-gc-rt #f)
2367 (start-rt #f)
2368 (repl-report-start-timing (lambda ()
2369 (set! start-gc-rt (gc-run-time))
2370 (set! start-rt (get-internal-run-time))))
2371 (repl-report (lambda ()
2372 (display ";;; ")
2373 (display (inexact->exact
2374 (* 1000 (/ (- (get-internal-run-time) start-rt)
2375 internal-time-units-per-second))))
2376 (display " msec (")
2377 (display (inexact->exact
2378 (* 1000 (/ (- (gc-run-time) start-gc-rt)
2379 internal-time-units-per-second))))
2380 (display " msec in gc)\n")))
2381
2382 (consume-trailing-whitespace
2383 (lambda ()
2384 (let ((ch (peek-char)))
2385 (cond
2386 ((eof-object? ch))
2387 ((or (char=? ch #\space) (char=? ch #\tab))
2388 (read-char)
2389 (consume-trailing-whitespace))
2390 ((char=? ch #\newline)
2391 (read-char))))))
2392 (-read (lambda ()
2393 (let ((val
2394 (let ((prompt (cond ((string? scm-repl-prompt)
2395 scm-repl-prompt)
2396 ((thunk? scm-repl-prompt)
2397 (scm-repl-prompt))
2398 (scm-repl-prompt "> ")
2399 (else ""))))
2400 (repl-reader prompt))))
2401
2402 ;; As described in R4RS, the READ procedure updates the
2403 ;; port to point to the first character past the end of
2404 ;; the external representation of the object. This
2405 ;; means that it doesn't consume the newline typically
2406 ;; found after an expression. This means that, when
2407 ;; debugging Guile with GDB, GDB gets the newline, which
2408 ;; it often interprets as a "continue" command, making
2409 ;; breakpoints kind of useless. So, consume any
2410 ;; trailing newline here, as well as any whitespace
2411 ;; before it.
2412 ;; But not if EOF, for control-D.
2413 (if (not (eof-object? val))
2414 (consume-trailing-whitespace))
2415 (run-hook after-read-hook)
2416 (if (eof-object? val)
2417 (begin
2418 (repl-report-start-timing)
2419 (if scm-repl-verbose
2420 (begin
2421 (newline)
2422 (display ";;; EOF -- quitting")
2423 (newline)))
2424 (quit 0)))
2425 val)))
2426
2427 (-eval (lambda (sourc)
2428 (repl-report-start-timing)
2429 (run-hook before-eval-hook sourc)
2430 (let ((val (start-stack 'repl-stack
2431 ;; If you change this procedure
2432 ;; (primitive-eval), please also
2433 ;; modify the repl-stack case in
2434 ;; save-stack so that stack cutting
2435 ;; continues to work.
2436 (primitive-eval sourc))))
2437 (run-hook after-eval-hook sourc)
2438 val)))
2439
2440
2441 (-print (let ((maybe-print (lambda (result)
2442 (if (or scm-repl-print-unspecified
2443 (not (unspecified? result)))
2444 (begin
2445 (write result)
2446 (newline))))))
2447 (lambda (result)
2448 (if (not scm-repl-silent)
2449 (begin
2450 (run-hook before-print-hook result)
2451 (maybe-print result)
2452 (run-hook after-print-hook result)
2453 (if scm-repl-verbose
2454 (repl-report))
2455 (force-output))))))
2456
2457 (-quit (lambda (args)
2458 (if scm-repl-verbose
2459 (begin
2460 (display ";;; QUIT executed, repl exitting")
2461 (newline)
2462 (repl-report)))
2463 args))
2464
2465 (-abort (lambda ()
2466 (if scm-repl-verbose
2467 (begin
2468 (display ";;; ABORT executed.")
2469 (newline)
2470 (repl-report)))
2471 (repl -read -eval -print))))
2472
2473 (let ((status (error-catching-repl -read
2474 -eval
2475 -print)))
2476 (-quit status))))
2477
2478
2479 \f
2480 ;;; {IOTA functions: generating lists of numbers}
2481
2482 (define (iota n)
2483 (let loop ((count (1- n)) (result '()))
2484 (if (< count 0) result
2485 (loop (1- count) (cons count result)))))
2486
2487 \f
2488 ;;; {While}
2489 ;;;
2490 ;;; with `continue' and `break'.
2491 ;;;
2492
2493 (defmacro while (cond . body)
2494 `(letrec ((continue (lambda () (or (not ,cond) (begin (begin ,@ body) (continue)))))
2495 (break (lambda val (apply throw 'break val))))
2496 (catch 'break
2497 (lambda () (continue))
2498 (lambda v (cadr v)))))
2499
2500 ;;; {collect}
2501 ;;;
2502 ;;; Similar to `begin' but returns a list of the results of all constituent
2503 ;;; forms instead of the result of the last form.
2504 ;;; (The definition relies on the current left-to-right
2505 ;;; order of evaluation of operands in applications.)
2506
2507 (defmacro collect forms
2508 (cons 'list forms))
2509
2510 ;;; {with-fluids}
2511
2512 ;; with-fluids is a convenience wrapper for the builtin procedure
2513 ;; `with-fluids*'. The syntax is just like `let':
2514 ;;
2515 ;; (with-fluids ((fluid val)
2516 ;; ...)
2517 ;; body)
2518
2519 (defmacro with-fluids (bindings . body)
2520 `(with-fluids* (list ,@(map car bindings)) (list ,@(map cadr bindings))
2521 (lambda () ,@body)))
2522
2523 \f
2524
2525 ;;; {Macros}
2526 ;;;
2527
2528 ;; actually....hobbit might be able to hack these with a little
2529 ;; coaxing
2530 ;;
2531
2532 (defmacro define-macro (first . rest)
2533 (let ((name (if (symbol? first) first (car first)))
2534 (transformer
2535 (if (symbol? first)
2536 (car rest)
2537 `(lambda ,(cdr first) ,@rest))))
2538 `(eval-case
2539 ((load-toplevel)
2540 (define ,name (defmacro:transformer ,transformer)))
2541 (else
2542 (error "define-macro can only be used at the top level")))))
2543
2544
2545 (defmacro define-syntax-macro (first . rest)
2546 (let ((name (if (symbol? first) first (car first)))
2547 (transformer
2548 (if (symbol? first)
2549 (car rest)
2550 `(lambda ,(cdr first) ,@rest))))
2551 `(eval-case
2552 ((load-toplevel)
2553 (define ,name (defmacro:syntax-transformer ,transformer)))
2554 (else
2555 (error "define-syntax-macro can only be used at the top level")))))
2556
2557 \f
2558 ;;; {Module System Macros}
2559 ;;;
2560
2561 ;; Return a list of expressions that evaluate to the appropriate
2562 ;; arguments for resolve-interface according to SPEC.
2563
2564 (define (compile-interface-spec spec)
2565 (define (make-keyarg sym key quote?)
2566 (cond ((or (memq sym spec)
2567 (memq key spec))
2568 => (lambda (rest)
2569 (if quote?
2570 (list key (list 'quote (cadr rest)))
2571 (list key (cadr rest)))))
2572 (else
2573 '())))
2574 (define (map-apply func list)
2575 (map (lambda (args) (apply func args)) list))
2576 (define keys
2577 ;; sym key quote?
2578 '((:select #:select #t)
2579 (:hide #:hide #t)
2580 (:prefix #:prefix #t)
2581 (:renamer #:renamer #f)))
2582 (if (not (pair? (car spec)))
2583 `(',spec)
2584 `(',(car spec)
2585 ,@(apply append (map-apply make-keyarg keys)))))
2586
2587 (define (keyword-like-symbol->keyword sym)
2588 (symbol->keyword (string->symbol (substring (symbol->string sym) 1))))
2589
2590 (define (compile-define-module-args args)
2591 ;; Just quote everything except #:use-module and #:use-syntax. We
2592 ;; need to know about all arguments regardless since we want to turn
2593 ;; symbols that look like keywords into real keywords, and the
2594 ;; keyword args in a define-module form are not regular
2595 ;; (i.e. no-backtrace doesn't take a value).
2596 (let loop ((compiled-args `((quote ,(car args))))
2597 (args (cdr args)))
2598 (cond ((null? args)
2599 (reverse! compiled-args))
2600 ;; symbol in keyword position
2601 ((symbol? (car args))
2602 (loop compiled-args
2603 (cons (keyword-like-symbol->keyword (car args)) (cdr args))))
2604 ((memq (car args) '(#:no-backtrace #:pure))
2605 (loop (cons (car args) compiled-args)
2606 (cdr args)))
2607 ((null? (cdr args))
2608 (error "keyword without value:" (car args)))
2609 ((memq (car args) '(#:use-module #:use-syntax))
2610 (loop (cons* `(list ,@(compile-interface-spec (cadr args)))
2611 (car args)
2612 compiled-args)
2613 (cddr args)))
2614 ((eq? (car args) #:autoload)
2615 (loop (cons* `(quote ,(caddr args))
2616 `(quote ,(cadr args))
2617 (car args)
2618 compiled-args)
2619 (cdddr args)))
2620 (else
2621 (loop (cons* `(quote ,(cadr args))
2622 (car args)
2623 compiled-args)
2624 (cddr args))))))
2625
2626 (defmacro define-module args
2627 `(eval-case
2628 ((load-toplevel)
2629 (let ((m (process-define-module
2630 (list ,@(compile-define-module-args args)))))
2631 (set-current-module m)
2632 m))
2633 (else
2634 (error "define-module can only be used at the top level"))))
2635
2636 ;; The guts of the use-modules macro. Add the interfaces of the named
2637 ;; modules to the use-list of the current module, in order.
2638
2639 ;; This function is called by "modules.c". If you change it, be sure
2640 ;; to change scm_c_use_module as well.
2641
2642 (define (process-use-modules module-interface-args)
2643 (module-use-interfaces! (current-module)
2644 (map (lambda (mif-args)
2645 (or (apply resolve-interface mif-args)
2646 (error "no such module" mif-args)))
2647 module-interface-args)))
2648
2649 (defmacro use-modules modules
2650 `(eval-case
2651 ((load-toplevel)
2652 (process-use-modules
2653 (list ,@(map (lambda (m)
2654 `(list ,@(compile-interface-spec m)))
2655 modules)))
2656 *unspecified*)
2657 (else
2658 (error "use-modules can only be used at the top level"))))
2659
2660 (defmacro use-syntax (spec)
2661 `(eval-case
2662 ((load-toplevel)
2663 ,@(if (pair? spec)
2664 `((process-use-modules (list
2665 (list ,@(compile-interface-spec spec))))
2666 (set-module-transformer! (current-module)
2667 ,(car (last-pair spec))))
2668 `((set-module-transformer! (current-module) ,spec)))
2669 *unspecified*)
2670 (else
2671 (error "use-syntax can only be used at the top level"))))
2672
2673 ;; Dirk:FIXME:: This incorrect (according to R5RS) syntax needs to be changed
2674 ;; as soon as guile supports hygienic macros.
2675 (define define-private define)
2676
2677 (defmacro define-public args
2678 (define (syntax)
2679 (error "bad syntax" (list 'define-public args)))
2680 (define (defined-name n)
2681 (cond
2682 ((symbol? n) n)
2683 ((pair? n) (defined-name (car n)))
2684 (else (syntax))))
2685 (cond
2686 ((null? args)
2687 (syntax))
2688 (#t
2689 (let ((name (defined-name (car args))))
2690 `(begin
2691 (define-private ,@args)
2692 (eval-case ((load-toplevel) (export ,name))))))))
2693
2694 (defmacro defmacro-public args
2695 (define (syntax)
2696 (error "bad syntax" (list 'defmacro-public args)))
2697 (define (defined-name n)
2698 (cond
2699 ((symbol? n) n)
2700 (else (syntax))))
2701 (cond
2702 ((null? args)
2703 (syntax))
2704 (#t
2705 (let ((name (defined-name (car args))))
2706 `(begin
2707 (eval-case ((load-toplevel) (export ,name)))
2708 (defmacro ,@args))))))
2709
2710 ;; Export a local variable
2711
2712 ;; This function is called from "modules.c". If you change it, be
2713 ;; sure to update "modules.c" as well.
2714
2715 (define (module-export! m names)
2716 (let ((public-i (module-public-interface m)))
2717 (for-each (lambda (name)
2718 (let ((var (module-ensure-local-variable! m name)))
2719 (module-add! public-i name var)))
2720 names)))
2721
2722 (define (module-replace! m names)
2723 (let ((public-i (module-public-interface m)))
2724 (for-each (lambda (name)
2725 (let ((var (module-ensure-local-variable! m name)))
2726 (set-object-property! var 'replace #t)
2727 (module-add! public-i name var)))
2728 names)))
2729
2730 ;; Re-export a imported variable
2731 ;;
2732 (define (module-re-export! m names)
2733 (let ((public-i (module-public-interface m)))
2734 (for-each (lambda (name)
2735 (let ((var (module-variable m name)))
2736 (cond ((not var)
2737 (error "Undefined variable:" name))
2738 ((eq? var (module-local-variable m name))
2739 (error "re-exporting local variable:" name))
2740 (else
2741 (module-add! public-i name var)))))
2742 names)))
2743
2744 (defmacro export names
2745 `(eval-case
2746 ((load-toplevel)
2747 (module-export! (current-module) ',names))
2748 (else
2749 (error "export can only be used at the top level"))))
2750
2751 (defmacro re-export names
2752 `(eval-case
2753 ((load-toplevel)
2754 (module-re-export! (current-module) ',names))
2755 (else
2756 (error "re-export can only be used at the top level"))))
2757
2758 (defmacro export-syntax names
2759 `(export ,@names))
2760
2761 (defmacro re-export-syntax names
2762 `(re-export ,@names))
2763
2764 (define load load-module)
2765
2766 \f
2767 ;;; {Parameters}
2768 ;;;
2769
2770 (define make-mutable-parameter
2771 (let ((make (lambda (fluid converter)
2772 (lambda args
2773 (if (null? args)
2774 (fluid-ref fluid)
2775 (fluid-set! fluid (converter (car args))))))))
2776 (lambda (init . converter)
2777 (let ((fluid (make-fluid))
2778 (converter (if (null? converter)
2779 identity
2780 (car converter))))
2781 (fluid-set! fluid (converter init))
2782 (make fluid converter)))))
2783
2784 \f
2785 ;;; {Handling of duplicate imported bindings}
2786 ;;;
2787
2788 ;; Duplicate handlers take the following arguments:
2789 ;;
2790 ;; module importing module
2791 ;; name conflicting name
2792 ;; int1 old interface where name occurs
2793 ;; val1 value of binding in old interface
2794 ;; int2 new interface where name occurs
2795 ;; val2 value of binding in new interface
2796 ;; var previous resolution or #f
2797 ;; val value of previous resolution
2798 ;;
2799 ;; A duplicate handler can take three alternative actions:
2800 ;;
2801 ;; 1. return #f => leave responsibility to next handler
2802 ;; 2. exit with an error
2803 ;; 3. return a variable resolving the conflict
2804 ;;
2805
2806 (define duplicate-handlers
2807 (let ((m (make-module 7)))
2808
2809 (define (check module name int1 val1 int2 val2 var val)
2810 (scm-error 'misc-error
2811 #f
2812 "~A: ~A imported from ~A and ~A"
2813 (list (module-name module)
2814 name
2815 (module-name int1)
2816 (module-name int2))
2817 #f))
2818
2819 (define (warn module name int1 val1 int2 val2 var val)
2820 (format #t
2821 "~A: ~A imported from ~A and ~A\n"
2822 (module-name module)
2823 name
2824 (module-name int1)
2825 (module-name int2))
2826 #f)
2827
2828 (define (replace module name int1 val1 int2 val2 var val)
2829 (let ((old (or (and var (object-property var 'replace) var)
2830 (module-variable int1 name)))
2831 (new (module-variable int2 name)))
2832 (if (object-property old 'replace)
2833 (and (or (eq? old new)
2834 (not (object-property new 'replace)))
2835 old)
2836 (and (object-property new 'replace)
2837 new))))
2838
2839 (define (warn-override-core module name int1 val1 int2 val2 var val)
2840 (and (eq? int1 the-scm-module)
2841 (begin
2842 (format #t
2843 "WARNING: ~A: imported module ~A overrides core binding ~A\n"
2844 (module-name module)
2845 (module-name int2)
2846 name)
2847 (module-local-variable int2 name))))
2848
2849 (define (first module name int1 val1 int2 val2 var val)
2850 (or var (module-local-variable int1 name)))
2851
2852 (define (last module name int1 val1 int2 val2 var val)
2853 (module-local-variable int2 name))
2854
2855 (set-module-name! m 'duplicate-handlers)
2856 (set-module-kind! m 'interface)
2857 (module-define! m 'check check)
2858 (module-define! m 'warn warn)
2859 (module-define! m 'replace replace)
2860 (module-define! m 'warn-override-core warn-override-core)
2861 (module-define! m 'first first)
2862 (module-define! m 'last last)
2863 m))
2864
2865 (define (lookup-duplicates-handlers handler-names)
2866 (and handler-names
2867 (map (lambda (handler-name)
2868 (or (module-symbol-local-binding
2869 duplicate-handlers handler-name #f)
2870 (error "invalid duplicate handler name:"
2871 handler-name)))
2872 (if (list? handler-names)
2873 handler-names
2874 (list handler-names)))))
2875
2876 (define default-module-duplicates-handler
2877 (make-mutable-parameter '(replace warn-override-core check)
2878 lookup-duplicates-handlers))
2879
2880 (define (make-duplicates-interface)
2881 (let ((m (make-module)))
2882 (set-module-kind! m 'custom-interface)
2883 (set-module-name! m 'duplicates)
2884 m))
2885
2886 (define (process-duplicates module interface)
2887 (let* ((duplicates-info (module-duplicates-info module))
2888 (duplicates-handlers (car duplicates-info))
2889 (duplicates-interface (cdr duplicates-info)))
2890 (module-for-each
2891 (lambda (name var)
2892 (cond ((module-import-interface module name)
2893 =>
2894 (lambda (prev-interface)
2895 (let ((var1 (module-local-variable prev-interface name))
2896 (var2 (module-local-variable interface name)))
2897 (if (not (eq? var1 var2))
2898 (begin
2899 (if (not duplicates-interface)
2900 (begin
2901 (set! duplicates-interface
2902 (make-duplicates-interface))
2903 (set-cdr! duplicates-info duplicates-interface)))
2904 (let* ((var (module-local-variable duplicates-interface
2905 name))
2906 (val (and var
2907 (variable-bound? var)
2908 (variable-ref var))))
2909 (let loop ((duplicates-handlers duplicates-handlers))
2910 (cond ((null? duplicates-handlers))
2911 (((car duplicates-handlers)
2912 module
2913 name
2914 prev-interface
2915 (and (variable-bound? var1)
2916 (variable-ref var1))
2917 interface
2918 (and (variable-bound? var2)
2919 (variable-ref var2))
2920 var
2921 val)
2922 =>
2923 (lambda (var)
2924 (module-add! duplicates-interface name var)))
2925 (else
2926 (loop (cdr duplicates-handlers)))))))))))))
2927 interface)))
2928
2929 \f
2930
2931 ;;; {`cond-expand' for SRFI-0 support.}
2932 ;;;
2933 ;;; This syntactic form expands into different commands or
2934 ;;; definitions, depending on the features provided by the Scheme
2935 ;;; implementation.
2936 ;;;
2937 ;;; Syntax:
2938 ;;;
2939 ;;; <cond-expand>
2940 ;;; --> (cond-expand <cond-expand-clause>+)
2941 ;;; | (cond-expand <cond-expand-clause>* (else <command-or-definition>))
2942 ;;; <cond-expand-clause>
2943 ;;; --> (<feature-requirement> <command-or-definition>*)
2944 ;;; <feature-requirement>
2945 ;;; --> <feature-identifier>
2946 ;;; | (and <feature-requirement>*)
2947 ;;; | (or <feature-requirement>*)
2948 ;;; | (not <feature-requirement>)
2949 ;;; <feature-identifier>
2950 ;;; --> <a symbol which is the name or alias of a SRFI>
2951 ;;;
2952 ;;; Additionally, this implementation provides the
2953 ;;; <feature-identifier>s `guile' and `r5rs', so that programs can
2954 ;;; determine the implementation type and the supported standard.
2955 ;;;
2956 ;;; Currently, the following feature identifiers are supported:
2957 ;;;
2958 ;;; guile r5rs srfi-0
2959 ;;;
2960 ;;; Remember to update the features list when adding more SRFIs.
2961
2962 (define %cond-expand-features
2963 ;; Adjust the above comment when changing this.
2964 '(guile r5rs srfi-0))
2965
2966 ;; This table maps module public interfaces to the list of features.
2967 ;;
2968 (define %cond-expand-table (make-hash-table 31))
2969
2970 ;; Add one or more features to the `cond-expand' feature list of the
2971 ;; module `module'.
2972 ;;
2973 (define (cond-expand-provide module features)
2974 (let ((mod (module-public-interface module)))
2975 (and mod
2976 (hashq-set! %cond-expand-table mod
2977 (append (hashq-ref %cond-expand-table mod '())
2978 features)))))
2979
2980 (define cond-expand
2981 (procedure->memoizing-macro
2982 (lambda (exp env)
2983 (let ((clauses (cdr exp))
2984 (syntax-error (lambda (cl)
2985 (error "invalid clause in `cond-expand'" cl))))
2986 (letrec
2987 ((test-clause
2988 (lambda (clause)
2989 (cond
2990 ((symbol? clause)
2991 (or (memq clause %cond-expand-features)
2992 (let lp ((uses (module-uses (env-module env))))
2993 (if (pair? uses)
2994 (or (memq clause
2995 (hashq-ref %cond-expand-table
2996 (car uses) '()))
2997 (lp (cdr uses)))
2998 #f))))
2999 ((pair? clause)
3000 (cond
3001 ((eq? 'and (car clause))
3002 (let lp ((l (cdr clause)))
3003 (cond ((null? l)
3004 #t)
3005 ((pair? l)
3006 (and (test-clause (car l)) (lp (cdr l))))
3007 (else
3008 (syntax-error clause)))))
3009 ((eq? 'or (car clause))
3010 (let lp ((l (cdr clause)))
3011 (cond ((null? l)
3012 #f)
3013 ((pair? l)
3014 (or (test-clause (car l)) (lp (cdr l))))
3015 (else
3016 (syntax-error clause)))))
3017 ((eq? 'not (car clause))
3018 (cond ((not (pair? (cdr clause)))
3019 (syntax-error clause))
3020 ((pair? (cddr clause))
3021 ((syntax-error clause))))
3022 (not (test-clause (cadr clause))))
3023 (else
3024 (syntax-error clause))))
3025 (else
3026 (syntax-error clause))))))
3027 (let lp ((c clauses))
3028 (cond
3029 ((null? c)
3030 (error "Unfulfilled `cond-expand'"))
3031 ((not (pair? c))
3032 (syntax-error c))
3033 ((not (pair? (car c)))
3034 (syntax-error (car c)))
3035 ((test-clause (caar c))
3036 `(begin ,@(cdar c)))
3037 ((eq? (caar c) 'else)
3038 (if (pair? (cdr c))
3039 (syntax-error c))
3040 `(begin ,@(cdar c)))
3041 (else
3042 (lp (cdr c))))))))))
3043
3044 ;; This procedure gets called from the startup code with a list of
3045 ;; numbers, which are the numbers of the SRFIs to be loaded on startup.
3046 ;;
3047 (define (use-srfis srfis)
3048 (let lp ((s srfis))
3049 (if (pair? s)
3050 (let* ((srfi (string->symbol
3051 (string-append "srfi-" (number->string (car s)))))
3052 (mod-i (resolve-interface (list 'srfi srfi))))
3053 (module-use! (current-module) mod-i)
3054 (lp (cdr s))))))
3055
3056 \f
3057
3058 ;;; {Load emacs interface support if emacs option is given.}
3059
3060 (define (named-module-use! user usee)
3061 (module-use! (resolve-module user) (resolve-interface usee)))
3062
3063 (define (load-emacs-interface)
3064 (and (provided? 'debug-extensions)
3065 (debug-enable 'backtrace))
3066 (named-module-use! '(guile-user) '(ice-9 emacs)))
3067
3068 \f
3069
3070 (define using-readline?
3071 (let ((using-readline? (make-fluid)))
3072 (make-procedure-with-setter
3073 (lambda () (fluid-ref using-readline?))
3074 (lambda (v) (fluid-set! using-readline? v)))))
3075
3076 (define (top-repl)
3077 (let ((guile-user-module (resolve-module '(guile-user))))
3078
3079 ;; Load emacs interface support if emacs option is given.
3080 (if (and (module-defined? guile-user-module 'use-emacs-interface)
3081 (module-ref guile-user-module 'use-emacs-interface))
3082 (load-emacs-interface))
3083
3084 ;; Use some convenient modules (in reverse order)
3085
3086 (if (provided? 'regex)
3087 (module-use! guile-user-module (resolve-interface '(ice-9 regex))))
3088 (if (provided? 'threads)
3089 (module-use! guile-user-module (resolve-interface '(ice-9 threads))))
3090 ;; load debugger on demand
3091 (module-use! guile-user-module
3092 (make-autoload-interface guile-user-module
3093 '(ice-9 debugger) '(debug)))
3094 (module-use! guile-user-module (resolve-interface '(ice-9 session)))
3095 (module-use! guile-user-module (resolve-interface '(ice-9 debug)))
3096 ;; so that builtin bindings will be checked first
3097 (module-use! guile-user-module (resolve-interface '(guile)))
3098
3099 (set-current-module guile-user-module)
3100
3101 (let ((old-handlers #f)
3102 (signals (if (provided? 'posix)
3103 `((,SIGINT . "User interrupt")
3104 (,SIGFPE . "Arithmetic error")
3105 (,SIGBUS . "Bad memory access (bus error)")
3106 (,SIGSEGV
3107 . "Bad memory access (Segmentation violation)"))
3108 '())))
3109
3110 (dynamic-wind
3111
3112 ;; call at entry
3113 (lambda ()
3114 (let ((make-handler (lambda (msg)
3115 (lambda (sig)
3116 ;; Make a backup copy of the stack
3117 (fluid-set! before-signal-stack
3118 (fluid-ref the-last-stack))
3119 (save-stack 2)
3120 (scm-error 'signal
3121 #f
3122 msg
3123 #f
3124 (list sig))))))
3125 (set! old-handlers
3126 (map (lambda (sig-msg)
3127 (sigaction (car sig-msg)
3128 (make-handler (cdr sig-msg))))
3129 signals))))
3130
3131 ;; the protected thunk.
3132 (lambda ()
3133 (let ((status (scm-style-repl)))
3134 (run-hook exit-hook)
3135 status))
3136
3137 ;; call at exit.
3138 (lambda ()
3139 (map (lambda (sig-msg old-handler)
3140 (if (not (car old-handler))
3141 ;; restore original C handler.
3142 (sigaction (car sig-msg) #f)
3143 ;; restore Scheme handler, SIG_IGN or SIG_DFL.
3144 (sigaction (car sig-msg)
3145 (car old-handler)
3146 (cdr old-handler))))
3147 signals old-handlers))))))
3148
3149 (defmacro false-if-exception (expr)
3150 `(catch #t (lambda () ,expr)
3151 (lambda args #f)))
3152
3153 ;;; This hook is run at the very end of an interactive session.
3154 ;;;
3155 (define exit-hook (make-hook))
3156
3157 \f
3158 (append! %load-path (list "."))
3159
3160 ;; Place the user in the guile-user module.
3161 ;;
3162
3163 (define-module (guile-user))
3164
3165 ;;; boot-9.scm ends here