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