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