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