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