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