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