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