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