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