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