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