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