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