more clear comments in boot-9.scm
[bpt/guile.git] / module / ice-9 / boot-9.scm
CommitLineData
87e00370 1;;; -*- mode: scheme; coding: utf-8; -*-
0f2d19dd 2
b3da54d1
LC
3;;;; Copyright (C) 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003,
4;;;; 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012
5;;;; Free Software Foundation, Inc.
20edfbbd 6;;;;
73be1d9e
MV
7;;;; This library is free software; you can redistribute it and/or
8;;;; modify it under the terms of the GNU Lesser General Public
9;;;; License as published by the Free Software Foundation; either
53befeb7 10;;;; version 3 of the License, or (at your option) any later version.
73be1d9e
MV
11;;;;
12;;;; This library is distributed in the hope that it will be useful,
0f2d19dd 13;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
73be1d9e
MV
14;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15;;;; Lesser General Public License for more details.
16;;;;
17;;;; You should have received a copy of the GNU Lesser General Public
18;;;; License along with this library; if not, write to the Free Software
92205699 19;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
a482f2cc 20;;;;
3d2ada2f 21
0f2d19dd
JB
22\f
23
20edfbbd
TTN
24;;; Commentary:
25
0f2d19dd
JB
26;;; This file is the first thing loaded into Guile. It adds many mundane
27;;; definitions and a few that are interesting.
28;;;
20edfbbd 29;;; The module system (hence the hierarchical namespace) are defined in this
0f2d19dd
JB
30;;; file.
31;;;
32
20edfbbd
TTN
33;;; Code:
34
0f2d19dd 35\f
9fb41cea 36
9c35c579
AW
37;; Before compiling, make sure any symbols are resolved in the (guile)
38;; module, the primary location of those symbols, rather than in
39;; (guile-user), the default module that we compile in.
40
41(eval-when (compile)
42 (set-current-module (resolve-module '(guile))))
43
416f26c7
AW
44\f
45
46;;; {Error handling}
47;;;
48
49;; Define delimited continuation operators, and implement catch and throw in
50;; terms of them.
51
d648f569
AW
52(define make-prompt-tag
53 (lambda* (#:optional (stem "prompt"))
54 (gensym stem)))
55
c6a32a2c
AW
56(define default-prompt-tag
57 ;; not sure if we should expose this to the user as a fluid
58 (let ((%default-prompt-tag (make-prompt-tag)))
59 (lambda ()
60 %default-prompt-tag)))
8fc43b12
AW
61
62(define (call-with-prompt tag thunk handler)
416f26c7 63 (@prompt tag (thunk) handler))
8fc43b12 64(define (abort-to-prompt tag . args)
416f26c7
AW
65 (@abort tag args))
66
67
416f26c7
AW
68;; Define catch and with-throw-handler, using some common helper routines and a
69;; shared fluid. Hide the helpers in a lexical contour.
70
37620f3f 71(define with-throw-handler #f)
416f26c7 72(let ()
416f26c7
AW
73 (define (default-exception-handler k . args)
74 (cond
75 ((eq? k 'quit)
76 (primitive-exit (cond
77 ((not (pair? args)) 0)
78 ((integer? (car args)) (car args))
79 ((not (car args)) 1)
80 (else 0))))
81 (else
82 (format (current-error-port) "guile: uncaught throw to ~a: ~a\n" k args)
83 (primitive-exit 1))))
84
9447207f
AW
85 (define %running-exception-handlers (make-fluid '()))
86 (define %exception-handler (make-fluid default-exception-handler))
87
416f26c7 88 (define (default-throw-handler prompt-tag catch-k)
9447207f 89 (let ((prev (fluid-ref %exception-handler)))
416f26c7
AW
90 (lambda (thrown-k . args)
91 (if (or (eq? thrown-k catch-k) (eqv? catch-k #t))
8fc43b12 92 (apply abort-to-prompt prompt-tag thrown-k args)
416f26c7
AW
93 (apply prev thrown-k args)))))
94
95 (define (custom-throw-handler prompt-tag catch-k pre)
9447207f 96 (let ((prev (fluid-ref %exception-handler)))
416f26c7
AW
97 (lambda (thrown-k . args)
98 (if (or (eq? thrown-k catch-k) (eqv? catch-k #t))
9447207f 99 (let ((running (fluid-ref %running-exception-handlers)))
416f26c7
AW
100 (with-fluids ((%running-exception-handlers (cons pre running)))
101 (if (not (memq pre running))
102 (apply pre thrown-k args))
103 ;; fall through
104 (if prompt-tag
8fc43b12 105 (apply abort-to-prompt prompt-tag thrown-k args)
416f26c7
AW
106 (apply prev thrown-k args))))
107 (apply prev thrown-k args)))))
108
37620f3f
AW
109 (set! catch
110 (lambda* (k thunk handler #:optional pre-unwind-handler)
111 "Invoke @var{thunk} in the dynamic context of @var{handler} for
416f26c7
AW
112exceptions matching @var{key}. If thunk throws to the symbol
113@var{key}, then @var{handler} is invoked this way:
114@lisp
115 (handler key args ...)
116@end lisp
117
118@var{key} is a symbol or @code{#t}.
119
120@var{thunk} takes no arguments. If @var{thunk} returns
121normally, that is the return value of @code{catch}.
122
123Handler is invoked outside the scope of its own @code{catch}.
124If @var{handler} again throws to the same key, a new handler
125from further up the call chain is invoked.
126
127If the key is @code{#t}, then a throw to @emph{any} symbol will
128match this call to @code{catch}.
129
130If a @var{pre-unwind-handler} is given and @var{thunk} throws
131an exception that matches @var{key}, Guile calls the
132@var{pre-unwind-handler} before unwinding the dynamic state and
133invoking the main @var{handler}. @var{pre-unwind-handler} should
134be a procedure with the same signature as @var{handler}, that
135is @code{(lambda (key . args))}. It is typically used to save
136the stack at the point where the exception occurred, but can also
137query other parts of the dynamic state at that point, such as
138fluid values.
139
140A @var{pre-unwind-handler} can exit either normally or non-locally.
141If it exits normally, Guile unwinds the stack and dynamic context
142and then calls the normal (third argument) handler. If it exits
143non-locally, that exit determines the continuation."
37620f3f 144 (if (not (or (symbol? k) (eqv? k #t)))
222056dc 145 (scm-error 'wrong-type-arg "catch"
37620f3f
AW
146 "Wrong type argument in position ~a: ~a"
147 (list 1 k) (list k)))
148 (let ((tag (make-prompt-tag "catch")))
149 (call-with-prompt
150 tag
151 (lambda ()
152 (with-fluids
153 ((%exception-handler
154 (if pre-unwind-handler
155 (custom-throw-handler tag k pre-unwind-handler)
156 (default-throw-handler tag k))))
157 (thunk)))
158 (lambda (cont k . args)
159 (apply handler k args))))))
160
161 (set! with-throw-handler
162 (lambda (k thunk pre-unwind-handler)
163 "Add @var{handler} to the dynamic context as a throw handler
91a214eb 164for key @var{k}, then invoke @var{thunk}."
37620f3f 165 (if (not (or (symbol? k) (eqv? k #t)))
222056dc 166 (scm-error 'wrong-type-arg "with-throw-handler"
37620f3f
AW
167 "Wrong type argument in position ~a: ~a"
168 (list 1 k) (list k)))
169 (with-fluids ((%exception-handler
170 (custom-throw-handler #f k pre-unwind-handler)))
171 (thunk))))
172
173 (set! throw
174 (lambda (key . args)
175 "Invoke the catch form matching @var{key}, passing @var{args} to the
416f26c7
AW
176@var{handler}.
177
178@var{key} is a symbol. It will match catches of the same symbol or of @code{#t}.
179
180If there is no handler at all, Guile prints an error and then exits."
37620f3f 181 (if (not (symbol? key))
9447207f 182 ((fluid-ref %exception-handler) 'wrong-type-arg "throw"
37620f3f 183 "Wrong type argument in position ~a: ~a" (list 1 key) (list key))
9447207f 184 (apply (fluid-ref %exception-handler) key args)))))
416f26c7
AW
185
186
187\f
188
f28dc43c 189;;; {Language primitives}
928258fb
AW
190;;;
191
f28dc43c
AW
192;; These are are the procedural wrappers around the primitives of
193;; Guile's language: @apply, @call-with-current-continuation, etc.
194;;
195;; Usually, a call to a primitive is compiled specially. The compiler
196;; knows about all these kinds of expressions. But the primitives may
197;; be referenced not only as operators, but as values as well. These
198;; stub procedures are the "values" of apply, dynamic-wind, and other
199;; such primitives.
200;;
41832152
AW
201(define (apply fun . args)
202 (@apply fun (apply:nconc2last args)))
203(define (call-with-current-continuation proc)
204 (@call-with-current-continuation proc))
205(define (call-with-values producer consumer)
206 (@call-with-values producer consumer))
207(define (dynamic-wind in thunk out)
208 "All three arguments must be 0-argument procedures.
209Guard @var{in} is called, then @var{thunk}, then
210guard @var{out}.
211
212If, any time during the execution of @var{thunk}, the
213continuation of the @code{dynamic_wind} expression is escaped
214non-locally, @var{out} is called. If the continuation of
215the dynamic-wind is re-entered, @var{in} is called. Thus
216@var{in} and @var{out} may be called any number of
217times.
218@lisp
219 (define x 'normal-binding)
220@result{} x
221 (define a-cont
222 (call-with-current-continuation
223 (lambda (escape)
224 (let ((old-x x))
225 (dynamic-wind
226 ;; in-guard:
227 ;;
228 (lambda () (set! x 'special-binding))
229
230 ;; thunk
231 ;;
232 (lambda () (display x) (newline)
233 (call-with-current-continuation escape)
234 (display x) (newline)
235 x)
236
237 ;; out-guard:
238 ;;
239 (lambda () (set! x old-x)))))))
240
241;; Prints:
242special-binding
243;; Evaluates to:
244@result{} a-cont
245x
246@result{} normal-binding
247 (a-cont #f)
248;; Prints:
249special-binding
250;; Evaluates to:
251@result{} a-cont ;; the value of the (define a-cont...)
252x
253@result{} normal-binding
254a-cont
255@result{} special-binding
256@end lisp"
257 (@dynamic-wind in (thunk) out))
258
259;;;; Basic Port Code
260
261;;; Specifically, the parts of the low-level port code that are written in
262;;; Scheme rather than C.
263;;;
264;;; WARNING: the parts of this interface that refer to file ports
265;;; are going away. It would be gone already except that it is used
266;;; "internally" in a few places.
267
268
269;;; OPEN_READ, OPEN_WRITE, and OPEN_BOTH are used to request the
270;;; proper mode to open files in.
271;;;
272;;; If we want to support systems that do CRLF->LF translation, like
273;;; Windows, then we should have a symbol in scmconfig.h made visible
274;;; to the Scheme level that we can test here, and autoconf magic to
275;;; #define it when appropriate. Windows will probably just have a
276;;; hand-generated scmconfig.h file.
277(define OPEN_READ "r")
278(define OPEN_WRITE "w")
279(define OPEN_BOTH "r+")
280
281(define *null-device* "/dev/null")
282
283(define (open-input-file str)
284 "Takes a string naming an existing file and returns an input port
285capable of delivering characters from the file. If the file
286cannot be opened, an error is signalled."
287 (open-file str OPEN_READ))
288
289(define (open-output-file str)
290 "Takes a string naming an output file to be created and returns an
291output port capable of writing characters to a new file by that
292name. If the file cannot be opened, an error is signalled. If a
293file with the given name already exists, the effect is unspecified."
294 (open-file str OPEN_WRITE))
295
296(define (open-io-file str)
297 "Open file with name STR for both input and output."
298 (open-file str OPEN_BOTH))
299
41832152
AW
300(define (call-with-input-file str proc)
301 "PROC should be a procedure of one argument, and STR should be a
302string naming a file. The file must
303already exist. These procedures call PROC
304with one argument: the port obtained by opening the named file for
305input or output. If the file cannot be opened, an error is
306signalled. If the procedure returns, then the port is closed
307automatically and the values yielded by the procedure are returned.
308If the procedure does not return, then the port will not be closed
309automatically unless it is possible to prove that the port will
310never again be used for a read or write operation."
311 (let ((p (open-input-file str)))
312 (call-with-values
313 (lambda () (proc p))
314 (lambda vals
315 (close-input-port p)
316 (apply values vals)))))
317
318(define (call-with-output-file str proc)
319 "PROC should be a procedure of one argument, and STR should be a
320string naming a file. The behaviour is unspecified if the file
321already exists. These procedures call PROC
322with one argument: the port obtained by opening the named file for
323input or output. If the file cannot be opened, an error is
324signalled. If the procedure returns, then the port is closed
325automatically and the values yielded by the procedure are returned.
326If the procedure does not return, then the port will not be closed
327automatically unless it is possible to prove that the port will
328never again be used for a read or write operation."
329 (let ((p (open-output-file str)))
330 (call-with-values
331 (lambda () (proc p))
332 (lambda vals
333 (close-output-port p)
334 (apply values vals)))))
335
336(define (with-input-from-port port thunk)
337 (let* ((swaports (lambda () (set! port (set-current-input-port port)))))
338 (dynamic-wind swaports thunk swaports)))
339
340(define (with-output-to-port port thunk)
341 (let* ((swaports (lambda () (set! port (set-current-output-port port)))))
342 (dynamic-wind swaports thunk swaports)))
343
344(define (with-error-to-port port thunk)
345 (let* ((swaports (lambda () (set! port (set-current-error-port port)))))
346 (dynamic-wind swaports thunk swaports)))
347
348(define (with-input-from-file file thunk)
349 "THUNK must be a procedure of no arguments, and FILE must be a
350string naming a file. The file must already exist. The file is opened for
351input, an input port connected to it is made
352the default value returned by `current-input-port',
353and the THUNK is called with no arguments.
354When the THUNK returns, the port is closed and the previous
355default is restored. Returns the values yielded by THUNK. If an
356escape procedure is used to escape from the continuation of these
357procedures, their behavior is implementation dependent."
358 (call-with-input-file file
359 (lambda (p) (with-input-from-port p thunk))))
360
361(define (with-output-to-file file thunk)
362 "THUNK must be a procedure of no arguments, and FILE must be a
363string naming a file. The effect is unspecified if the file already exists.
364The file is opened for output, an output port connected to it is made
365the default value returned by `current-output-port',
366and the THUNK is called with no arguments.
367When the THUNK returns, the port is closed and the previous
368default is restored. Returns the values yielded by THUNK. If an
369escape procedure is used to escape from the continuation of these
370procedures, their behavior is implementation dependent."
371 (call-with-output-file file
372 (lambda (p) (with-output-to-port p thunk))))
373
374(define (with-error-to-file file thunk)
375 "THUNK must be a procedure of no arguments, and FILE must be a
376string naming a file. The effect is unspecified if the file already exists.
377The file is opened for output, an output port connected to it is made
378the default value returned by `current-error-port',
379and the THUNK is called with no arguments.
380When the THUNK returns, the port is closed and the previous
381default is restored. Returns the values yielded by THUNK. If an
382escape procedure is used to escape from the continuation of these
383procedures, their behavior is implementation dependent."
384 (call-with-output-file file
385 (lambda (p) (with-error-to-port p thunk))))
386
387(define (with-input-from-string string thunk)
388 "THUNK must be a procedure of no arguments.
389The test of STRING is opened for
390input, an input port connected to it is made,
391and the THUNK is called with no arguments.
392When the THUNK returns, the port is closed.
393Returns the values yielded by THUNK. If an
394escape procedure is used to escape from the continuation of these
395procedures, their behavior is implementation dependent."
396 (call-with-input-string string
397 (lambda (p) (with-input-from-port p thunk))))
398
399(define (with-output-to-string thunk)
400 "Calls THUNK and returns its output as a string."
401 (call-with-output-string
402 (lambda (p) (with-output-to-port p thunk))))
403
404(define (with-error-to-string thunk)
405 "Calls THUNK and returns its error output as a string."
406 (call-with-output-string
407 (lambda (p) (with-error-to-port p thunk))))
408
409(define the-eof-object (call-with-input-string "" (lambda (p) (read-char p))))
928258fb
AW
410
411\f
412
eb5d1f88
AW
413;;; {Simple Debugging Tools}
414;;;
415
416;; peek takes any number of arguments, writes them to the
417;; current ouput port, and returns the last argument.
418;; It is handy to wrap around an expression to look at
419;; a value each time is evaluated, e.g.:
420;;
9b5a0d84
AW
421;; (+ 10 (troublesome-fn))
422;; => (+ 10 (pk 'troublesome-fn-returned (troublesome-fn)))
eb5d1f88
AW
423;;
424
425(define (peek . stuff)
426 (newline)
427 (display ";;; ")
428 (write stuff)
429 (newline)
430 (car (last-pair stuff)))
431
432(define pk peek)
433
3972de76
AW
434;; Temporary definition; replaced later.
435(define current-warning-port current-error-port)
b7742c6b 436
eb5d1f88 437(define (warn . stuff)
2c27dd57 438 (with-output-to-port (current-warning-port)
eb5d1f88
AW
439 (lambda ()
440 (newline)
441 (display ";;; WARNING ")
442 (display stuff)
443 (newline)
444 (car (last-pair stuff)))))
445
446\f
447
21ed9efe 448;;; {Features}
3d2ada2f 449;;;
21ed9efe
MD
450
451(define (provide sym)
452 (if (not (memq sym *features*))
453 (set! *features* (cons sym *features*))))
454
3d2ada2f
DH
455;; Return #t iff FEATURE is available to this Guile interpreter. In SLIB,
456;; provided? also checks to see if the module is available. We should do that
457;; too, but don't.
458
50706e94
JB
459(define (provided? feature)
460 (and (memq feature *features*) #t))
461
4d248541
AW
462\f
463
9b3cc659
AW
464;;; {Structs}
465;;;
466
467(define (make-struct/no-tail vtable . args)
468 (apply make-struct vtable 0 args))
469
470\f
471
a2230b65
AW
472;;; Boot versions of `map' and `for-each', enough to get the expander
473;;; running.
474;;;
475(define map
476 (case-lambda
477 ((f l)
478 (let map1 ((l l))
479 (if (null? l)
480 '()
481 (cons (f (car l)) (map1 (cdr l))))))
482 ((f l1 l2)
483 (let map2 ((l1 l1) (l2 l2))
484 (if (null? l1)
485 '()
486 (cons (f (car l1) (car l2))
487 (map2 (cdr l1) (cdr l2))))))
488 ((f l1 . rest)
489 (let lp ((l1 l1) (rest rest))
490 (if (null? l1)
491 '()
492 (cons (apply f (car l1) (map car rest))
493 (lp (cdr l1) (map cdr rest))))))))
494
495(define for-each
496 (case-lambda
497 ((f l)
498 (let for-each1 ((l l))
499 (if (pair? l)
500 (begin
501 (f (car l))
502 (for-each1 (cdr l))))))
503 ((f l1 l2)
504 (let for-each2 ((l1 l1) (l2 l2))
505 (if (pair? l1)
506 (begin
507 (f (car l1) (car l2))
508 (for-each2 (cdr l1) (cdr l2))))))
509 ((f l1 . rest)
510 (let lp ((l1 l1) (rest rest))
511 (if (pair? l1)
512 (begin
513 (apply f (car l1) (map car rest))
514 (lp (cdr l1) (map cdr rest))))))))
515
4d248541
AW
516;;; {and-map and or-map}
517;;;
518;;; (and-map fn lst) is like (and (fn (car lst)) (fn (cadr lst)) (fn...) ...)
519;;; (or-map fn lst) is like (or (fn (car lst)) (fn (cadr lst)) (fn...) ...)
520;;;
521
522;; and-map f l
523;;
524;; Apply f to successive elements of l until exhaustion or f returns #f.
525;; If returning early, return #f. Otherwise, return the last value returned
526;; by f. If f has never been called because l is empty, return #t.
527;;
528(define (and-map f lst)
529 (let loop ((result #t)
9b5a0d84 530 (l lst))
4d248541 531 (and result
9b5a0d84
AW
532 (or (and (null? l)
533 result)
534 (loop (f (car l)) (cdr l))))))
4d248541
AW
535
536;; or-map f l
537;;
538;; Apply f to successive elements of l until exhaustion or while f returns #f.
539;; If returning early, return the return value of f.
540;;
541(define (or-map f lst)
542 (let loop ((result #f)
9b5a0d84 543 (l lst))
4d248541 544 (or result
9b5a0d84
AW
545 (and (not (null? l))
546 (loop (f (car l)) (cdr l))))))
4d248541
AW
547
548\f
549
3d2ada2f 550;; let format alias simple-format until the more complete version is loaded
52cfc69b 551
8641dd9e
GB
552(define format simple-format)
553
fdc6aebf
KR
554;; this is scheme wrapping the C code so the final pred call is a tail call,
555;; per SRFI-13 spec
a4c8a02e
AW
556(define string-any
557 (lambda* (char_pred s #:optional (start 0) (end (string-length s)))
fdc6aebf 558 (if (and (procedure? char_pred)
9b5a0d84
AW
559 (> end start)
560 (<= end (string-length s))) ;; let c-code handle range error
561 (or (string-any-c-code char_pred s start (1- end))
562 (char_pred (string-ref s (1- end))))
563 (string-any-c-code char_pred s start end))))
fdc6aebf
KR
564
565;; this is scheme wrapping the C code so the final pred call is a tail call,
566;; per SRFI-13 spec
a4c8a02e
AW
567(define string-every
568 (lambda* (char_pred s #:optional (start 0) (end (string-length s)))
fdc6aebf 569 (if (and (procedure? char_pred)
9b5a0d84
AW
570 (> end start)
571 (<= end (string-length s))) ;; let c-code handle range error
572 (and (string-every-c-code char_pred s start (1- end))
573 (char_pred (string-ref s (1- end))))
574 (string-every-c-code char_pred s start end))))
fdc6aebf 575
1b05b324
MV
576;; A variant of string-fill! that we keep for compatability
577;;
578(define (substring-fill! str start end fill)
579 (string-fill! str fill start end))
580
21ed9efe 581\f
79451588 582
12eae603
AW
583;; Define a minimal stub of the module API for psyntax, before modules
584;; have booted.
efa6f9d9 585(define (module-name x)
a26934a8 586 '(guile))
05a5e5d6
AW
587(define (module-add! module sym var)
588 (hashq-set! (%get-pre-modules-obarray) sym var))
3d5f3091
AW
589(define (module-define! module sym val)
590 (let ((v (hashq-ref (%get-pre-modules-obarray) sym)))
591 (if v
592 (variable-set! v val)
05a5e5d6 593 (module-add! (current-module) sym (make-variable val)))))
3d5f3091
AW
594(define (module-ref module sym)
595 (let ((v (module-variable module sym)))
596 (if v (variable-ref v) (error "badness!" (pk module) (pk sym)))))
12eae603
AW
597(define (resolve-module . args)
598 #f)
3d5f3091 599
6a952e0e 600;; API provided by psyntax
e4721dde 601(define syntax-violation #f)
22225fc1
AW
602(define datum->syntax #f)
603(define syntax->datum #f)
750ae8b7 604(define syntax-source #f)
22225fc1
AW
605(define identifier? #f)
606(define generate-temporaries #f)
13182603 607(define bound-identifier=? #f)
13182603 608(define free-identifier=? #f)
5a0132b3 609
8a73a6d2 610;; $sc-dispatch is an implementation detail of psyntax. It is used by
6a952e0e 611;; expanded macros, to dispatch an input against a set of patterns.
5a0132b3
AW
612(define $sc-dispatch #f)
613
6a952e0e 614;; Load it up!
13182603 615(primitive-load-path "ice-9/psyntax-pp")
4f692ace
AW
616;; The binding for `macroexpand' has now been overridden, making psyntax the
617;; expander now.
79451588 618
a1a482e0
AW
619(define-syntax and
620 (syntax-rules ()
621 ((_) #t)
622 ((_ x) x)
623 ((_ x y ...) (if x (and y ...) #f))))
624
625(define-syntax or
626 (syntax-rules ()
627 ((_) #f)
628 ((_ x) x)
629 ((_ x y ...) (let ((t x)) (if t t (or y ...))))))
630
e7cf0457
MW
631(include-from-path "ice-9/quasisyntax")
632
9accf3d9
AW
633(define-syntax-rule (when test stmt stmt* ...)
634 (if test (begin stmt stmt* ...)))
635
636(define-syntax-rule (unless test stmt stmt* ...)
637 (if (not test) (begin stmt stmt* ...)))
638
a1a482e0 639(define-syntax cond
e7cf0457
MW
640 (lambda (whole-expr)
641 (define (fold f seed xs)
642 (let loop ((xs xs) (seed seed))
643 (if (null? xs) seed
644 (loop (cdr xs) (f (car xs) seed)))))
645 (define (reverse-map f xs)
646 (fold (lambda (x seed) (cons (f x) seed))
647 '() xs))
648 (syntax-case whole-expr ()
649 ((_ clause clauses ...)
650 #`(begin
651 #,@(fold (lambda (clause-builder tail)
652 (clause-builder tail))
653 #'()
654 (reverse-map
655 (lambda (clause)
656 (define* (bad-clause #:optional (msg "invalid clause"))
657 (syntax-violation 'cond msg whole-expr clause))
658 (syntax-case clause (=> else)
659 ((else e e* ...)
660 (lambda (tail)
661 (if (null? tail)
662 #'((begin e e* ...))
663 (bad-clause "else must be the last clause"))))
664 ((else . _) (bad-clause))
665 ((test => receiver)
666 (lambda (tail)
667 #`((let ((t test))
668 (if t
669 (receiver t)
670 #,@tail)))))
671 ((test => receiver ...)
672 (bad-clause "wrong number of receiver expressions"))
673 ((generator guard => receiver)
674 (lambda (tail)
675 #`((call-with-values (lambda () generator)
676 (lambda vals
677 (if (apply guard vals)
678 (apply receiver vals)
679 #,@tail))))))
680 ((generator guard => receiver ...)
681 (bad-clause "wrong number of receiver expressions"))
682 ((test)
683 (lambda (tail)
684 #`((let ((t test))
685 (if t t #,@tail)))))
686 ((test e e* ...)
687 (lambda (tail)
688 #`((if test
689 (begin e e* ...)
690 #,@tail))))
691 (_ (bad-clause))))
692 #'(clause clauses ...))))))))
a1a482e0
AW
693
694(define-syntax case
e7cf0457
MW
695 (lambda (whole-expr)
696 (define (fold f seed xs)
697 (let loop ((xs xs) (seed seed))
698 (if (null? xs) seed
699 (loop (cdr xs) (f (car xs) seed)))))
700 (define (fold2 f a b xs)
701 (let loop ((xs xs) (a a) (b b))
702 (if (null? xs) (values a b)
703 (call-with-values
704 (lambda () (f (car xs) a b))
705 (lambda (a b)
706 (loop (cdr xs) a b))))))
707 (define (reverse-map-with-seed f seed xs)
708 (fold2 (lambda (x ys seed)
709 (call-with-values
710 (lambda () (f x seed))
711 (lambda (y seed)
712 (values (cons y ys) seed))))
713 '() seed xs))
714 (syntax-case whole-expr ()
715 ((_ expr clause clauses ...)
716 (with-syntax ((key #'key))
717 #`(let ((key expr))
718 #,@(fold
719 (lambda (clause-builder tail)
720 (clause-builder tail))
721 #'()
722 (reverse-map-with-seed
723 (lambda (clause seen)
724 (define* (bad-clause #:optional (msg "invalid clause"))
725 (syntax-violation 'case msg whole-expr clause))
726 (syntax-case clause ()
727 ((test . rest)
728 (with-syntax
729 ((clause-expr
730 (syntax-case #'rest (=>)
731 ((=> receiver) #'(receiver key))
732 ((=> receiver ...)
733 (bad-clause
734 "wrong number of receiver expressions"))
735 ((e e* ...) #'(begin e e* ...))
736 (_ (bad-clause)))))
737 (syntax-case #'test (else)
738 ((datums ...)
739 (let ((seen
740 (fold
741 (lambda (datum seen)
742 (define (warn-datum type)
743 ((@ (system base message)
744 warning)
745 type
746 (append (source-properties datum)
747 (source-properties
748 (syntax->datum #'test)))
749 datum
750 (syntax->datum clause)
751 (syntax->datum whole-expr)))
752 (if (memv datum seen)
753 (warn-datum 'duplicate-case-datum))
754 (if (or (pair? datum)
755 (array? datum)
756 (generalized-vector? datum))
757 (warn-datum 'bad-case-datum))
758 (cons datum seen))
759 seen
760 (map syntax->datum #'(datums ...)))))
761 (values (lambda (tail)
762 #`((if (memv key '(datums ...))
763 clause-expr
764 #,@tail)))
765 seen)))
766 (else (values (lambda (tail)
767 (if (null? tail)
768 #'(clause-expr)
769 (bad-clause
770 "else must be the last clause")))
771 seen))
772 (_ (bad-clause)))))
773 (_ (bad-clause))))
774 '() #'(clause clauses ...)))))))))
a1a482e0
AW
775
776(define-syntax do
777 (syntax-rules ()
778 ((do ((var init step ...) ...)
779 (test expr ...)
780 command ...)
781 (letrec
782 ((loop
783 (lambda (var ...)
784 (if test
785 (begin
786 (if #f #f)
787 expr ...)
788 (begin
789 command
790 ...
791 (loop (do "step" var step ...)
792 ...))))))
793 (loop init ...)))
794 ((do "step" x)
795 x)
796 ((do "step" x y)
797 y)))
798
0c65f52c
AW
799(define-syntax-rule (delay exp)
800 (make-promise (lambda () exp)))
79451588 801
41147ee7
AW
802(define-syntax current-source-location
803 (lambda (x)
804 (syntax-case x ()
805 ((_)
806 (with-syntax ((s (datum->syntax x (syntax-source x))))
807 #''s)))))
808
925172cf
AW
809;; We provide this accessor out of convenience. current-line and
810;; current-column aren't so interesting, because they distort what they
811;; are measuring; better to use syntax-source from a macro.
812;;
813(define-syntax current-filename
814 (lambda (x)
815 "A macro that expands to the current filename: the filename that
816the (current-filename) form appears in. Expands to #f if this
817information is unavailable."
21ad60a1
AW
818 (false-if-exception
819 (canonicalize-path (assq-ref (syntax-source x) 'filename)))))
925172cf 820
0c65f52c
AW
821(define-syntax-rule (define-once sym val)
822 (define sym
823 (if (module-locally-bound? (current-module) 'sym) sym val)))
41147ee7 824
a2230b65
AW
825;;; The real versions of `map' and `for-each', with cycle detection, and
826;;; that use reverse! instead of recursion in the case of `map'.
827;;;
828(define map
829 (case-lambda
830 ((f l)
831 (let map1 ((hare l) (tortoise l) (move? #f) (out '()))
832 (if (pair? hare)
833 (if move?
834 (if (eq? tortoise hare)
835 (scm-error 'wrong-type-arg "map" "Circular list: ~S"
836 (list l) #f)
837 (map1 (cdr hare) (cdr tortoise) #f
838 (cons (f (car hare)) out)))
839 (map1 (cdr hare) tortoise #t
840 (cons (f (car hare)) out)))
841 (if (null? hare)
842 (reverse! out)
843 (scm-error 'wrong-type-arg "map" "Not a list: ~S"
844 (list l) #f)))))
845
846 ((f l1 l2)
847 (let map2 ((h1 l1) (h2 l2) (t1 l1) (t2 l2) (move? #f) (out '()))
848 (cond
849 ((pair? h1)
850 (cond
851 ((not (pair? h2))
852 (scm-error 'wrong-type-arg "map"
853 (if (list? h2)
854 "List of wrong length: ~S"
855 "Not a list: ~S")
856 (list l2) #f))
857 ((not move?)
858 (map2 (cdr h1) (cdr h2) t1 t2 #t
859 (cons (f (car h1) (car h2)) out)))
860 ((eq? t1 h1)
861 (scm-error 'wrong-type-arg "map" "Circular list: ~S"
862 (list l1) #f))
863 ((eq? t2 h2)
864 (scm-error 'wrong-type-arg "map" "Circular list: ~S"
865 (list l2) #f))
866 (else
867 (map2 (cdr h1) (cdr h2) (cdr t1) (cdr t2) #f
868 (cons (f (car h1) (car h2)) out)))))
869
870 ((and (null? h1) (null? h2))
871 (reverse! out))
872
873 ((null? h1)
874 (scm-error 'wrong-type-arg "map"
875 (if (list? h2)
876 "List of wrong length: ~S"
877 "Not a list: ~S")
878 (list l2) #f))
879 (else
880 (scm-error 'wrong-type-arg "map"
881 "Not a list: ~S"
882 (list l1) #f)))))
883
884 ((f l1 . rest)
885 (let ((len (length l1)))
886 (let mapn ((rest rest))
887 (or (null? rest)
888 (if (= (length (car rest)) len)
889 (mapn (cdr rest))
890 (scm-error 'wrong-type-arg "map" "List of wrong length: ~S"
891 (list (car rest)) #f)))))
892 (let mapn ((l1 l1) (rest rest) (out '()))
893 (if (null? l1)
894 (reverse! out)
895 (mapn (cdr l1) (map cdr rest)
896 (cons (apply f (car l1) (map car rest)) out)))))))
897
898(define map-in-order map)
899
900(define for-each
901 (case-lambda
902 ((f l)
903 (let for-each1 ((hare l) (tortoise l) (move? #f))
904 (if (pair? hare)
905 (if move?
906 (if (eq? tortoise hare)
907 (scm-error 'wrong-type-arg "for-each" "Circular list: ~S"
908 (list l) #f)
909 (begin
910 (f (car hare))
911 (for-each1 (cdr hare) (cdr tortoise) #f)))
912 (begin
913 (f (car hare))
914 (for-each1 (cdr hare) tortoise #t)))
915
916 (if (not (null? hare))
917 (scm-error 'wrong-type-arg "for-each" "Not a list: ~S"
918 (list l) #f)))))
919
920 ((f l1 l2)
921 (let for-each2 ((h1 l1) (h2 l2) (t1 l1) (t2 l2) (move? #f))
922 (cond
923 ((and (pair? h1) (pair? h2))
924 (cond
925 ((not move?)
926 (f (car h1) (car h2))
927 (for-each2 (cdr h1) (cdr h2) t1 t2 #t))
928 ((eq? t1 h1)
929 (scm-error 'wrong-type-arg "for-each" "Circular list: ~S"
930 (list l1) #f))
931 ((eq? t2 h2)
932 (scm-error 'wrong-type-arg "for-each" "Circular list: ~S"
933 (list l2) #f))
934 (else
935 (f (car h1) (car h2))
936 (for-each2 (cdr h1) (cdr h2) (cdr t1) (cdr t2) #f))))
937
938 ((if (null? h1)
939 (or (null? h2) (pair? h2))
940 (and (pair? h1) (null? h2)))
941 (if #f #f))
942
943 ((list? h1)
944 (scm-error 'wrong-type-arg "for-each" "Unexpected tail: ~S"
945 (list h2) #f))
946 (else
947 (scm-error 'wrong-type-arg "for-each" "Unexpected tail: ~S"
948 (list h1) #f)))))
949
950 ((f l1 . rest)
951 (let ((len (length l1)))
952 (let for-eachn ((rest rest))
953 (or (null? rest)
954 (if (= (length (car rest)) len)
955 (for-eachn (cdr rest))
956 (scm-error 'wrong-type-arg "for-each" "List of wrong length: ~S"
957 (list (car rest)) #f)))))
958
959 (let for-eachn ((l1 l1) (rest rest))
960 (if (pair? l1)
961 (begin
962 (apply f (car l1) (map car rest))
963 (for-eachn (cdr l1) (map cdr rest))))))))
964
965
79451588 966\f
48fdec21 967
40b91dc8
AW
968;;;
969;;; Extensible exception printing.
970;;;
971
972(define set-exception-printer! #f)
e8df456a
AW
973;; There is already a definition of print-exception from backtrace.c
974;; that we will override.
40b91dc8
AW
975
976(let ((exception-printers '()))
977 (define (print-location frame port)
978 (let ((source (and=> frame frame-source)))
979 ;; source := (addr . (filename . (line . column)))
980 (if source
981 (let ((filename (or (cadr source) "<unnamed port>"))
982 (line (caddr source))
983 (col (cdddr source)))
153c4a4a 984 (format port "~a:~a:~a: " filename (1+ line) col))
40b91dc8
AW
985 (format port "ERROR: "))))
986
987 (set! set-exception-printer!
988 (lambda (key proc)
989 (set! exception-printers (acons key proc exception-printers))))
990
991 (set! print-exception
992 (lambda (port frame key args)
993 (define (default-printer)
994 (format port "Throw to key `~a' with args `~s'." key args))
995
996 (if frame
997 (let ((proc (frame-procedure frame)))
998 (print-location frame port)
999 (format port "In procedure ~a:\n"
1000 (or (procedure-name proc) proc))))
1001
1002 (print-location frame port)
1003 (catch #t
1004 (lambda ()
1005 (let ((printer (assq-ref exception-printers key)))
1006 (if printer
1007 (printer port key args default-printer)
1008 (default-printer))))
1009 (lambda (k . args)
1010 (format port "Error while printing exception.")))
1011 (newline port)
1012 (force-output port))))
1013
1014;;;
1015;;; Printers for those keys thrown by Guile.
1016;;;
1017(let ()
1018 (define (scm-error-printer port key args default-printer)
1019 ;; Abuse case-lambda as a pattern matcher, given that we don't have
1020 ;; ice-9 match at this point.
1021 (apply (case-lambda
1022 ((subr msg args . rest)
1023 (if subr
1024 (format port "In procedure ~a: " subr))
4e33a132 1025 (apply format port msg (or args '())))
40b91dc8
AW
1026 (_ (default-printer)))
1027 args))
1028
1029 (define (syntax-error-printer port key args default-printer)
1030 (apply (case-lambda
dc20f5a8 1031 ((who what where form subform . extra)
40b91dc8
AW
1032 (format port "Syntax error:\n")
1033 (if where
1034 (let ((file (or (assq-ref where 'filename) "unknown file"))
1035 (line (and=> (assq-ref where 'line) 1+))
1036 (col (assq-ref where 'column)))
1037 (format port "~a:~a:~a: " file line col))
1038 (format port "unknown location: "))
1039 (if who
1040 (format port "~a: " who))
1041 (format port "~a" what)
1042 (if subform
1043 (format port " in subform ~s of ~s" subform form)
1044 (if form
1045 (format port " in form ~s" form))))
1046 (_ (default-printer)))
1047 args))
1048
e7b2efd5
LC
1049 (define (getaddrinfo-error-printer port key args default-printer)
1050 (format port "In procedure getaddrinfo: ~a" (gai-strerror (car args))))
1051
40b91dc8
AW
1052 (set-exception-printer! 'goops-error scm-error-printer)
1053 (set-exception-printer! 'host-not-found scm-error-printer)
1054 (set-exception-printer! 'keyword-argument-error scm-error-printer)
1055 (set-exception-printer! 'misc-error scm-error-printer)
1056 (set-exception-printer! 'no-data scm-error-printer)
1057 (set-exception-printer! 'no-recovery scm-error-printer)
1058 (set-exception-printer! 'null-pointer-error scm-error-printer)
1059 (set-exception-printer! 'out-of-range scm-error-printer)
1060 (set-exception-printer! 'program-error scm-error-printer)
1061 (set-exception-printer! 'read-error scm-error-printer)
1062 (set-exception-printer! 'regular-expression-syntax scm-error-printer)
1063 (set-exception-printer! 'signal scm-error-printer)
1064 (set-exception-printer! 'stack-overflow scm-error-printer)
1065 (set-exception-printer! 'system-error scm-error-printer)
1066 (set-exception-printer! 'try-again scm-error-printer)
1067 (set-exception-printer! 'unbound-variable scm-error-printer)
1068 (set-exception-printer! 'wrong-number-of-args scm-error-printer)
1069 (set-exception-printer! 'wrong-type-arg scm-error-printer)
1070
e7b2efd5
LC
1071 (set-exception-printer! 'syntax-error syntax-error-printer)
1072
1073 (set-exception-printer! 'getaddrinfo-error getaddrinfo-error-printer))
40b91dc8
AW
1074
1075
1076\f
1077
3d2ada2f
DH
1078;;; {Defmacros}
1079;;;
3d2ada2f 1080
13182603
AW
1081(define-syntax define-macro
1082 (lambda (x)
97ce9dbf 1083 "Define a defmacro."
13182603 1084 (syntax-case x ()
97ce9dbf 1085 ((_ (macro . args) doc body1 body ...)
a927454d
AW
1086 (string? (syntax->datum #'doc))
1087 #'(define-macro macro doc (lambda args body1 body ...)))
97ce9dbf 1088 ((_ (macro . args) body ...)
a927454d 1089 #'(define-macro macro #f (lambda args body ...)))
97ce9dbf 1090 ((_ macro doc transformer)
a927454d
AW
1091 (or (string? (syntax->datum #'doc))
1092 (not (syntax->datum #'doc)))
1093 #'(define-syntax macro
1094 (lambda (y)
1095 doc
a5e95abe
AW
1096 #((macro-type . defmacro)
1097 (defmacro-args args))
a927454d
AW
1098 (syntax-case y ()
1099 ((_ . args)
1100 (let ((v (syntax->datum #'args)))
1101 (datum->syntax y (apply transformer v)))))))))))
13182603
AW
1102
1103(define-syntax defmacro
1104 (lambda (x)
97ce9dbf 1105 "Define a defmacro, with the old lispy defun syntax."
13182603 1106 (syntax-case x ()
97ce9dbf 1107 ((_ macro args doc body1 body ...)
a927454d
AW
1108 (string? (syntax->datum #'doc))
1109 #'(define-macro macro doc (lambda args body1 body ...)))
97ce9dbf 1110 ((_ macro args body ...)
a927454d 1111 #'(define-macro macro #f (lambda args body ...))))))
3d2ada2f
DH
1112
1113(provide 'defmacro)
48fdec21
MV
1114
1115\f
1116
3d2ada2f
DH
1117;;; {Deprecation}
1118;;;
3d2ada2f 1119
ec0f307e
AW
1120(define-syntax begin-deprecated
1121 (lambda (x)
1122 (syntax-case x ()
1123 ((_ form form* ...)
1124 (if (include-deprecated-features)
1125 #'(begin form form* ...)
1126 #'(begin))))))
0f2d19dd
JB
1127
1128\f
3d2ada2f 1129
79451588 1130;;; {Trivial Functions}
0f2d19dd 1131;;;
79451588 1132
6b08d75b 1133(define (identity x) x)
18f06db9
LC
1134
1135(define (compose proc . rest)
1136 "Compose PROC with the procedures in REST, such that the last one in
1137REST is applied first and PROC last, and return the resulting procedure.
1138The given procedures must have compatible arity."
1139 (if (null? rest)
1140 proc
1141 (let ((g (apply compose rest)))
1142 (lambda args
1143 (call-with-values (lambda () (apply g args)) proc)))))
1144
1145(define (negate proc)
1146 "Return a procedure with the same arity as PROC that returns the `not'
1147of PROC's result."
1148 (lambda args
1149 (not (apply proc args))))
1150
1151(define (const value)
1152 "Return a procedure that accepts any number of arguments and returns
1153VALUE."
1154 (lambda _
1155 value))
1156
132e5fac 1157(define (and=> value procedure) (and value (procedure value)))
e8ed460e 1158(define call/cc call-with-current-continuation)
79451588 1159
0c65f52c
AW
1160(define-syntax-rule (false-if-exception expr)
1161 (catch #t
1162 (lambda () expr)
1163 (lambda (k . args) #f)))
3d2ada2f
DH
1164
1165\f
1166
1167;;; {General Properties}
1168;;;
1169
02b582ce
AW
1170;; Properties are a lispy way to associate random info with random objects.
1171;; Traditionally properties are implemented as an alist or a plist actually
1172;; pertaining to the object in question.
1173;;
1174;; These "object properties" have the advantage that they can be associated with
1175;; any object, even if the object has no plist. Object properties are good when
1176;; you are extending pre-existing objects in unexpected ways. They also present
1177;; a pleasing, uniform procedure-with-setter interface. But if you have a data
1178;; type that always has properties, it's often still best to store those
1179;; properties within the object itself.
3d2ada2f
DH
1180
1181(define (make-object-property)
633f3a18
AW
1182 ;; Weak tables are thread-safe.
1183 (let ((prop (make-weak-key-hash-table)))
3d2ada2f 1184 (make-procedure-with-setter
633f3a18
AW
1185 (lambda (obj) (hashq-ref prop obj))
1186 (lambda (obj val) (hashq-set! prop obj val)))))
79488112 1187
3d2ada2f 1188
0f2d19dd 1189\f
6b08d75b 1190
0f2d19dd
JB
1191;;; {Symbol Properties}
1192;;;
1193
02b582ce
AW
1194;;; Symbol properties are something you see in old Lisp code. In most current
1195;;; Guile code, symbols are not used as a data structure -- they are used as
1196;;; keys into other data structures.
1197
0f2d19dd
JB
1198(define (symbol-property sym prop)
1199 (let ((pair (assoc prop (symbol-pref sym))))
1200 (and pair (cdr pair))))
1201
1202(define (set-symbol-property! sym prop val)
1203 (let ((pair (assoc prop (symbol-pref sym))))
1204 (if pair
9b5a0d84
AW
1205 (set-cdr! pair val)
1206 (symbol-pset! sym (acons prop val (symbol-pref sym))))))
0f2d19dd
JB
1207
1208(define (symbol-property-remove! sym prop)
1209 (let ((pair (assoc prop (symbol-pref sym))))
1210 (if pair
9b5a0d84 1211 (symbol-pset! sym (delq! pair (symbol-pref sym))))))
0f2d19dd
JB
1212
1213\f
1e531c3a 1214
0f2d19dd
JB
1215;;; {Arrays}
1216;;;
1217
2042e178
MV
1218(define (array-shape a)
1219 (map (lambda (ind) (if (number? ind) (list 0 (+ -1 ind)) ind))
1220 (array-dimensions a)))
0f2d19dd
JB
1221
1222\f
3d2ada2f 1223
0f2d19dd
JB
1224;;; {Keywords}
1225;;;
1226
010b159f
AW
1227;;; It's much better if you can use lambda* / define*, of course.
1228
0f2d19dd
JB
1229(define (kw-arg-ref args kw)
1230 (let ((rem (member kw args)))
1231 (and rem (pair? (cdr rem)) (cadr rem))))
1232
1233\f
fa7e9274 1234
9f9aa47b 1235;;; {Structs}
3d2ada2f 1236;;;
fa7e9274
MV
1237
1238(define (struct-layout s)
9f9aa47b 1239 (struct-ref (struct-vtable s) vtable-index-layout))
fa7e9274
MV
1240
1241\f
d7faeb2e 1242
0f2d19dd
JB
1243;;; {Records}
1244;;;
1245
fa7e9274
MV
1246;; Printing records: by default, records are printed as
1247;;
1248;; #<type-name field1: val1 field2: val2 ...>
1249;;
1250;; You can change that by giving a custom printing function to
1251;; MAKE-RECORD-TYPE (after the list of field symbols). This function
1252;; will be called like
1253;;
1254;; (<printer> object port)
1255;;
1256;; It should print OBJECT to PORT.
1257
cf8f1a90 1258(define (inherit-print-state old-port new-port)
8a30733e
MD
1259 (if (get-print-state old-port)
1260 (port-with-print-state new-port (get-print-state old-port))
cf8f1a90
MV
1261 new-port))
1262
e31f22eb 1263;; 0: type-name, 1: fields, 2: constructor
20edfbbd 1264(define record-type-vtable
f7bbc75d
AW
1265 (let ((s (make-vtable (string-append standard-vtable-fields "prprpw")
1266 (lambda (s p)
1267 (display "#<record-type " p)
1268 (display (record-type-name s) p)
1269 (display ">" p)))))
1270 (set-struct-vtable-name! s 'record-type)
1271 s))
0f2d19dd
JB
1272
1273(define (record-type? obj)
1274 (and (struct? obj) (eq? record-type-vtable (struct-vtable obj))))
1275
b2669c41 1276(define* (make-record-type type-name fields #:optional printer)
31ac29b6 1277 ;; Pre-generate constructors for nfields < 20.
e31f22eb
AW
1278 (define-syntax make-constructor
1279 (lambda (x)
1280 (define *max-static-argument-count* 20)
1281 (define (make-formals n)
1282 (let lp ((i 0))
1283 (if (< i n)
1284 (cons (datum->syntax
1285 x
1286 (string->symbol
1287 (string (integer->char (+ (char->integer #\a) i)))))
1288 (lp (1+ i)))
1289 '())))
1290 (syntax-case x ()
1291 ((_ rtd exp) (not (identifier? #'exp))
1292 #'(let ((n exp))
1293 (make-constructor rtd n)))
1294 ((_ rtd nfields)
1295 #`(case nfields
1296 #,@(let lp ((n 0))
1297 (if (< n *max-static-argument-count*)
1298 (cons (with-syntax (((formal ...) (make-formals n))
1299 (n n))
1300 #'((n)
1301 (lambda (formal ...)
1302 (make-struct rtd 0 formal ...))))
1303 (lp (1+ n)))
1304 '()))
1305 (else
1306 (lambda args
1307 (if (= (length args) nfields)
1308 (apply make-struct rtd 0 args)
1309 (scm-error 'wrong-number-of-args
1310 (format #f "make-~a" type-name)
1311 "Wrong number of arguments" '() #f)))))))))
1312
51797cec
AW
1313 (define (default-record-printer s p)
1314 (display "#<" p)
1315 (display (record-type-name (record-type-descriptor s)) p)
1316 (let loop ((fields (record-type-fields (record-type-descriptor s)))
1317 (off 0))
1318 (cond
1319 ((not (null? fields))
1320 (display " " p)
1321 (display (car fields) p)
1322 (display ": " p)
1323 (display (struct-ref s off) p)
1324 (loop (cdr fields) (+ 1 off)))))
1325 (display ">" p))
1326
e31f22eb
AW
1327 (let ((rtd (make-struct record-type-vtable 0
1328 (make-struct-layout
1329 (apply string-append
1330 (map (lambda (f) "pw") fields)))
b2669c41 1331 (or printer default-record-printer)
e31f22eb
AW
1332 type-name
1333 (copy-tree fields))))
1334 (struct-set! rtd (+ vtable-offset-user 2)
1335 (make-constructor rtd (length fields)))
51797cec
AW
1336 ;; Temporary solution: Associate a name to the record type descriptor
1337 ;; so that the object system can create a wrapper class for it.
e31f22eb
AW
1338 (set-struct-vtable-name! rtd (if (symbol? type-name)
1339 type-name
1340 (string->symbol type-name)))
1341 rtd))
0f2d19dd
JB
1342
1343(define (record-type-name obj)
1344 (if (record-type? obj)
9f9aa47b 1345 (struct-ref obj vtable-offset-user)
0f2d19dd
JB
1346 (error 'not-a-record-type obj)))
1347
1348(define (record-type-fields obj)
1349 (if (record-type? obj)
9f9aa47b 1350 (struct-ref obj (+ 1 vtable-offset-user))
0f2d19dd
JB
1351 (error 'not-a-record-type obj)))
1352
d44a0d12
AW
1353(define* (record-constructor rtd #:optional field-names)
1354 (if (not field-names)
e31f22eb 1355 (struct-ref rtd (+ 2 vtable-offset-user))
d44a0d12
AW
1356 (primitive-eval
1357 `(lambda ,field-names
1358 (make-struct ',rtd 0 ,@(map (lambda (f)
1359 (if (memq f field-names)
1360 f
1361 #f))
1362 (record-type-fields rtd)))))))
3bf27608 1363
0f2d19dd
JB
1364(define (record-predicate rtd)
1365 (lambda (obj) (and (struct? obj) (eq? rtd (struct-vtable obj)))))
1366
3ba9acb1 1367(define (%record-type-error rtd obj) ;; private helper
afc4ccd4
KR
1368 (or (eq? rtd (record-type-descriptor obj))
1369 (scm-error 'wrong-type-arg "%record-type-check"
9b5a0d84
AW
1370 "Wrong type record (want `~S'): ~S"
1371 (list (record-type-name rtd) obj)
1372 #f)))
afc4ccd4 1373
0f2d19dd 1374(define (record-accessor rtd field-name)
3bf27608 1375 (let ((pos (list-index (record-type-fields rtd) field-name)))
0f2d19dd 1376 (if (not pos)
9b5a0d84 1377 (error 'no-such-field field-name))
3bf27608
AW
1378 (lambda (obj)
1379 (if (eq? (struct-vtable obj) rtd)
1380 (struct-ref obj pos)
1381 (%record-type-error rtd obj)))))
0f2d19dd
JB
1382
1383(define (record-modifier rtd field-name)
3bf27608 1384 (let ((pos (list-index (record-type-fields rtd) field-name)))
0f2d19dd 1385 (if (not pos)
9b5a0d84 1386 (error 'no-such-field field-name))
3bf27608
AW
1387 (lambda (obj val)
1388 (if (eq? (struct-vtable obj) rtd)
1389 (struct-set! obj pos val)
1390 (%record-type-error rtd obj)))))
0f2d19dd
JB
1391
1392(define (record? obj)
1393 (and (struct? obj) (record-type? (struct-vtable obj))))
1394
1395(define (record-type-descriptor obj)
1396 (if (struct? obj)
1397 (struct-vtable obj)
1398 (error 'not-a-record obj)))
1399
21ed9efe
MD
1400(provide 'record)
1401
0f2d19dd 1402\f
3d2ada2f 1403
0f2d19dd
JB
1404;;; {Booleans}
1405;;;
1406
1407(define (->bool x) (not (not x)))
1408
1409\f
3d2ada2f 1410
0f2d19dd
JB
1411;;; {Symbols}
1412;;;
1413
1414(define (symbol-append . args)
06f0414c 1415 (string->symbol (apply string-append (map symbol->string args))))
0f2d19dd
JB
1416
1417(define (list->symbol . args)
1418 (string->symbol (apply list->string args)))
1419
1420(define (symbol . args)
1421 (string->symbol (apply string args)))
1422
0f2d19dd 1423\f
3d2ada2f 1424
0f2d19dd
JB
1425;;; {Lists}
1426;;;
1427
1428(define (list-index l k)
1429 (let loop ((n 0)
9b5a0d84 1430 (l l))
0f2d19dd 1431 (and (not (null? l))
9b5a0d84
AW
1432 (if (eq? (car l) k)
1433 n
1434 (loop (+ n 1) (cdr l))))))
0f2d19dd 1435
1729d8ff 1436\f
3d2ada2f 1437
073167ef
LC
1438;; Load `posix.scm' even when not (provided? 'posix) so that we get the
1439;; `stat' accessors.
1440(primitive-load-path "ice-9/posix")
6fa8995c 1441
52cfc69b 1442(if (provided? 'socket)
1e6ebf54 1443 (primitive-load-path "ice-9/networking"))
3afb28ce 1444
f3197274 1445;; For reference, Emacs file-exists-p uses stat in this same way.
6fa8995c 1446(define file-exists?
52cfc69b 1447 (if (provided? 'posix)
6fa8995c 1448 (lambda (str)
9b5a0d84 1449 (->bool (stat str #f)))
6fa8995c 1450 (lambda (str)
9b5a0d84
AW
1451 (let ((port (catch 'system-error (lambda () (open-file str OPEN_READ))
1452 (lambda args #f))))
1453 (if port (begin (close-port port) #t)
1454 #f)))))
6fa8995c
GH
1455
1456(define file-is-directory?
52cfc69b 1457 (if (provided? 'posix)
6fa8995c 1458 (lambda (str)
9b5a0d84 1459 (eq? (stat:type (stat str)) 'directory))
6fa8995c 1460 (lambda (str)
9b5a0d84
AW
1461 (let ((port (catch 'system-error
1462 (lambda () (open-file (string-append str "/.")
1463 OPEN_READ))
1464 (lambda args #f))))
1465 (if port (begin (close-port port) #t)
1466 #f)))))
0f2d19dd 1467
019ac1c9
MV
1468(define (system-error-errno args)
1469 (if (eq? (car args) 'system-error)
1470 (car (list-ref args 4))
1471 #f))
1472
0f2d19dd 1473\f
3d2ada2f 1474
0f2d19dd
JB
1475;;; {Error Handling}
1476;;;
1477
4eeaf67c
AW
1478(define error
1479 (case-lambda
1480 (()
4eeaf67c
AW
1481 (scm-error 'misc-error #f "?" #f #f))
1482 ((message . args)
4eeaf67c
AW
1483 (let ((msg (string-join (cons "~A" (make-list (length args) "~S")))))
1484 (scm-error 'misc-error #f msg (cons message args) #f)))))
be2d2c70 1485
0f2d19dd 1486\f
bce074ee 1487
b38507c1
AW
1488;;; {Time Structures}
1489;;;
1490
708bf0f3
GH
1491(define (tm:sec obj) (vector-ref obj 0))
1492(define (tm:min obj) (vector-ref obj 1))
1493(define (tm:hour obj) (vector-ref obj 2))
1494(define (tm:mday obj) (vector-ref obj 3))
1495(define (tm:mon obj) (vector-ref obj 4))
1496(define (tm:year obj) (vector-ref obj 5))
1497(define (tm:wday obj) (vector-ref obj 6))
1498(define (tm:yday obj) (vector-ref obj 7))
1499(define (tm:isdst obj) (vector-ref obj 8))
1500(define (tm:gmtoff obj) (vector-ref obj 9))
1501(define (tm:zone obj) (vector-ref obj 10))
1502
1503(define (set-tm:sec obj val) (vector-set! obj 0 val))
1504(define (set-tm:min obj val) (vector-set! obj 1 val))
1505(define (set-tm:hour obj val) (vector-set! obj 2 val))
1506(define (set-tm:mday obj val) (vector-set! obj 3 val))
1507(define (set-tm:mon obj val) (vector-set! obj 4 val))
1508(define (set-tm:year obj val) (vector-set! obj 5 val))
1509(define (set-tm:wday obj val) (vector-set! obj 6 val))
1510(define (set-tm:yday obj val) (vector-set! obj 7 val))
1511(define (set-tm:isdst obj val) (vector-set! obj 8 val))
1512(define (set-tm:gmtoff obj val) (vector-set! obj 9 val))
1513(define (set-tm:zone obj val) (vector-set! obj 10 val))
1514
6afcd3b2
GH
1515(define (tms:clock obj) (vector-ref obj 0))
1516(define (tms:utime obj) (vector-ref obj 1))
1517(define (tms:stime obj) (vector-ref obj 2))
1518(define (tms:cutime obj) (vector-ref obj 3))
1519(define (tms:cstime obj) (vector-ref obj 4))
1520
b38507c1
AW
1521\f
1522
1523;;; {File Descriptors and Ports}
1524;;;
1525
1334c61a 1526(define file-position ftell)
52c9a338
AW
1527(define* (file-set-position port offset #:optional (whence SEEK_SET))
1528 (seek port offset whence))
8b13c6b3 1529
e38303a2
GH
1530(define (move->fdes fd/port fd)
1531 (cond ((integer? fd/port)
9b5a0d84
AW
1532 (dup->fdes fd/port fd)
1533 (close fd/port)
1534 fd)
1535 (else
1536 (primitive-move->fdes fd/port fd)
1537 (set-port-revealed! fd/port 1)
1538 fd/port)))
8b13c6b3
GH
1539
1540(define (release-port-handle port)
1541 (let ((revealed (port-revealed port)))
1542 (if (> revealed 0)
9b5a0d84 1543 (set-port-revealed! port (- revealed 1)))))
0f2d19dd 1544
02851b26
AW
1545(define dup->port
1546 (case-lambda
1547 ((port/fd mode)
1548 (fdopen (dup->fdes port/fd) mode))
1549 ((port/fd mode new-fd)
1550 (let ((port (fdopen (dup->fdes port/fd new-fd) mode)))
1551 (set-port-revealed! port 1)
1552 port))))
1553
1554(define dup->inport
1555 (case-lambda
1556 ((port/fd)
1557 (dup->port port/fd "r"))
1558 ((port/fd new-fd)
1559 (dup->port port/fd "r" new-fd))))
1560
1561(define dup->outport
1562 (case-lambda
1563 ((port/fd)
1564 (dup->port port/fd "w"))
1565 ((port/fd new-fd)
1566 (dup->port port/fd "w" new-fd))))
1567
1568(define dup
1569 (case-lambda
1570 ((port/fd)
1571 (if (integer? port/fd)
1572 (dup->fdes port/fd)
1573 (dup->port port/fd (port-mode port/fd))))
1574 ((port/fd new-fd)
1575 (if (integer? port/fd)
1576 (dup->fdes port/fd new-fd)
1577 (dup->port port/fd (port-mode port/fd) new-fd)))))
e38303a2
GH
1578
1579(define (duplicate-port port modes)
1580 (dup->port port modes))
1581
1582(define (fdes->inport fdes)
1583 (let loop ((rest-ports (fdes->ports fdes)))
1584 (cond ((null? rest-ports)
9b5a0d84
AW
1585 (let ((result (fdopen fdes "r")))
1586 (set-port-revealed! result 1)
1587 result))
1588 ((input-port? (car rest-ports))
1589 (set-port-revealed! (car rest-ports)
1590 (+ (port-revealed (car rest-ports)) 1))
1591 (car rest-ports))
1592 (else
1593 (loop (cdr rest-ports))))))
e38303a2
GH
1594
1595(define (fdes->outport fdes)
1596 (let loop ((rest-ports (fdes->ports fdes)))
1597 (cond ((null? rest-ports)
9b5a0d84
AW
1598 (let ((result (fdopen fdes "w")))
1599 (set-port-revealed! result 1)
1600 result))
1601 ((output-port? (car rest-ports))
1602 (set-port-revealed! (car rest-ports)
1603 (+ (port-revealed (car rest-ports)) 1))
1604 (car rest-ports))
1605 (else
1606 (loop (cdr rest-ports))))))
e38303a2
GH
1607
1608(define (port->fdes port)
1609 (set-port-revealed! port (+ (port-revealed port) 1))
1610 (fileno port))
1611
956055a9
GH
1612(define (setenv name value)
1613 (if value
1614 (putenv (string-append name "=" value))
1615 (putenv name)))
1616
5c1254da
MV
1617(define (unsetenv name)
1618 "Remove the entry for NAME from the environment."
1619 (putenv name))
1620
0f2d19dd 1621\f
3d2ada2f 1622
0f2d19dd
JB
1623;;; {Load Paths}
1624;;;
1625
3cab8392
JB
1626(define (in-vicinity vicinity file)
1627 (let ((tail (let ((len (string-length vicinity)))
9b5a0d84
AW
1628 (if (zero? len)
1629 #f
1630 (string-ref vicinity (- len 1))))))
3cab8392 1631 (string-append vicinity
9b5a0d84
AW
1632 (if (or (not tail)
1633 (eq? tail #\/))
1634 ""
1635 "/")
1636 file)))
02ceadb8 1637
0f2d19dd 1638\f
3d2ada2f 1639
ef00e7f4 1640;;; {Help for scm_shell}
3d2ada2f 1641;;;
ef00e7f4
JB
1642;;; The argument-processing code used by Guile-based shells generates
1643;;; Scheme code based on the argument list. This page contains help
1644;;; functions for the code it generates.
3d2ada2f 1645;;;
ef00e7f4 1646
ef00e7f4
JB
1647(define (command-line) (program-arguments))
1648
5aa7fe69
JB
1649;; This is mostly for the internal use of the code generated by
1650;; scm_compile_shell_switches.
eef6519b 1651
ef00e7f4 1652(define (load-user-init)
1f08acd9 1653 (let* ((home (or (getenv "HOME")
9b5a0d84
AW
1654 (false-if-exception (passwd:dir (getpwuid (getuid))))
1655 "/")) ;; fallback for cygwin etc.
1656 (init-file (in-vicinity home ".guile")))
1f08acd9 1657 (if (file-exists? init-file)
9b5a0d84 1658 (primitive-load init-file))))
ef00e7f4
JB
1659
1660\f
3d2ada2f 1661
107139ea
AW
1662;;; {The interpreter stack}
1663;;;
1664
06dcb9df 1665;; %stacks defined in stacks.c
a6cd3555 1666(define (%start-stack tag thunk)
8fc43b12
AW
1667 (let ((prompt-tag (make-prompt-tag "start-stack")))
1668 (call-with-prompt
1669 prompt-tag
1670 (lambda ()
1671 (with-fluids ((%stacks (acons tag prompt-tag
1672 (or (fluid-ref %stacks) '()))))
1673 (thunk)))
1674 (lambda (k . args)
52738540 1675 (%start-stack tag (lambda () (apply k args)))))))
0c65f52c
AW
1676
1677(define-syntax-rule (start-stack tag exp)
1678 (%start-stack tag (lambda () exp)))
107139ea
AW
1679
1680\f
1681
a06181a2 1682;;; {Loading by paths}
3d2ada2f 1683;;;
a06181a2
JB
1684
1685;;; Load a Scheme source file named NAME, searching for it in the
1686;;; directories listed in %load-path, and applying each of the file
1687;;; name extensions listed in %load-extensions.
1688(define (load-from-path name)
1689 (start-stack 'load-stack
9b5a0d84 1690 (primitive-load-path name)))
0f2d19dd 1691
925172cf
AW
1692(define-syntax-rule (add-to-load-path elt)
1693 "Add ELT to Guile's load path, at compile-time and at run-time."
21ad60a1
AW
1694 (eval-when (compile load eval)
1695 (set! %load-path (cons elt %load-path))))
925172cf 1696
85e95b47
AW
1697(define %load-verbosely #f)
1698(define (assert-load-verbosity v) (set! %load-verbosely v))
1699
1700(define (%load-announce file)
1701 (if %load-verbosely
2c27dd57 1702 (with-output-to-port (current-warning-port)
9b5a0d84
AW
1703 (lambda ()
1704 (display ";;; ")
1705 (display "loading ")
1706 (display file)
1707 (newline)
1708 (force-output)))))
85e95b47
AW
1709
1710(set! %load-hook %load-announce)
1711
0f2d19dd 1712\f
3d2ada2f 1713
0f2d19dd
JB
1714;;; {Reader Extensions}
1715;;;
0f2d19dd
JB
1716;;; Reader code for various "#c" forms.
1717;;;
1718
9447207f 1719(define read-eval? (make-fluid #f))
600c9584
RB
1720(read-hash-extend #\.
1721 (lambda (c port)
1722 (if (fluid-ref read-eval?)
1723 (eval (read port) (interaction-environment))
1724 (error
71335c0d 1725 "#. read expansion found and read-eval? is #f."))))
75a97b92 1726
0f2d19dd 1727\f
3d2ada2f 1728
0f2d19dd
JB
1729;;; {Low Level Modules}
1730;;;
1731;;; These are the low level data structures for modules.
1732;;;
37f5dfe5
DH
1733;;; Every module object is of the type 'module-type', which is a record
1734;;; consisting of the following members:
1735;;;
1736;;; - eval-closure: the function that defines for its module the strategy that
1737;;; shall be followed when looking up symbols in the module.
1738;;;
1739;;; An eval-closure is a function taking two arguments: the symbol to be
1740;;; looked up and a boolean value telling whether a binding for the symbol
1741;;; should be created if it does not exist yet. If the symbol lookup
1742;;; succeeded (either because an existing binding was found or because a new
1743;;; binding was created), a variable object representing the binding is
1744;;; returned. Otherwise, the value #f is returned. Note that the eval
1745;;; closure does not take the module to be searched as an argument: During
1746;;; construction of the eval-closure, the eval-closure has to store the
1747;;; module it belongs to in its environment. This means, that any
1748;;; eval-closure can belong to only one module.
1749;;;
1750;;; The eval-closure of a module can be defined arbitrarily. However, three
1751;;; special cases of eval-closures are to be distinguished: During startup
1752;;; the module system is not yet activated. In this phase, no modules are
1753;;; defined and all bindings are automatically stored by the system in the
1754;;; pre-modules-obarray. Since no eval-closures exist at this time, the
1755;;; functions which require an eval-closure as their argument need to be
1756;;; passed the value #f.
1757;;;
1758;;; The other two special cases of eval-closures are the
1759;;; standard-eval-closure and the standard-interface-eval-closure. Both
1760;;; behave equally for the case that no new binding is to be created. The
1761;;; difference between the two comes in, when the boolean argument to the
1762;;; eval-closure indicates that a new binding shall be created if it is not
1763;;; found.
1764;;;
1765;;; Given that no new binding shall be created, both standard eval-closures
1766;;; define the following standard strategy of searching bindings in the
1767;;; module: First, the module's obarray is searched for the symbol. Second,
1768;;; if no binding for the symbol was found in the module's obarray, the
1769;;; module's binder procedure is exececuted. If this procedure did not
1770;;; return a binding for the symbol, the modules referenced in the module's
1771;;; uses list are recursively searched for a binding of the symbol. If the
1772;;; binding can not be found in these modules also, the symbol lookup has
1773;;; failed.
1774;;;
1775;;; If a new binding shall be created, the standard-interface-eval-closure
1776;;; immediately returns indicating failure. That is, it does not even try
1777;;; to look up the symbol. In contrast, the standard-eval-closure would
1778;;; first search the obarray, and if no binding was found there, would
1779;;; create a new binding in the obarray, therefore not calling the binder
1780;;; procedure or searching the modules in the uses list.
1781;;;
1782;;; The explanation of the following members obarray, binder and uses
1783;;; assumes that the symbol lookup follows the strategy that is defined in
1784;;; the standard-eval-closure and the standard-interface-eval-closure.
1785;;;
1786;;; - obarray: a hash table that maps symbols to variable objects. In this
1787;;; hash table, the definitions are found that are local to the module (that
1788;;; is, not imported from other modules). When looking up bindings in the
1789;;; module, this hash table is searched first.
1790;;;
1791;;; - binder: either #f or a function taking a module and a symbol argument.
1792;;; If it is a function it is called after the obarray has been
1793;;; unsuccessfully searched for a binding. It then can provide bindings
1794;;; that would otherwise not be found locally in the module.
1795;;;
1796;;; - uses: a list of modules from which non-local bindings can be inherited.
1797;;; These modules are the third place queried for bindings after the obarray
1798;;; has been unsuccessfully searched and the binder function did not deliver
1799;;; a result either.
1800;;;
1801;;; - transformer: either #f or a function taking a scheme expression as
1802;;; delivered by read. If it is a function, it will be called to perform
1803;;; syntax transformations (e. g. makro expansion) on the given scheme
1804;;; expression. The output of the transformer function will then be passed
1805;;; to Guile's internal memoizer. This means that the output must be valid
1806;;; scheme code. The only exception is, that the output may make use of the
1807;;; syntax extensions provided to identify the modules that a binding
1808;;; belongs to.
1809;;;
1810;;; - name: the name of the module. This is used for all kinds of printing
1811;;; outputs. In certain places the module name also serves as a way of
1812;;; identification. When adding a module to the uses list of another
1813;;; module, it is made sure that the new uses list will not contain two
1814;;; modules of the same name.
1815;;;
1816;;; - kind: classification of the kind of module. The value is (currently?)
1817;;; only used for printing. It has no influence on how a module is treated.
1818;;; Currently the following values are used when setting the module kind:
1819;;; 'module, 'directory, 'interface, 'custom-interface. If no explicit kind
1820;;; is set, it defaults to 'module.
1821;;;
608860a5
LC
1822;;; - duplicates-handlers: a list of procedures that get called to make a
1823;;; choice between two duplicate bindings when name clashes occur. See the
1824;;; `duplicate-handlers' global variable below.
37f5dfe5 1825;;;
608860a5
LC
1826;;; - observers: a list of procedures that get called when the module is
1827;;; modified.
37f5dfe5 1828;;;
608860a5
LC
1829;;; - weak-observers: a weak-key hash table of procedures that get called
1830;;; when the module is modified. See `module-observe-weak' for details.
37f5dfe5
DH
1831;;;
1832;;; In addition, the module may (must?) contain a binding for
608860a5
LC
1833;;; `%module-public-interface'. This variable should be bound to a module
1834;;; representing the exported interface of a module. See the
1835;;; `module-public-interface' and `module-export!' procedures.
37f5dfe5 1836;;;
0f2d19dd
JB
1837;;; !!! warning: The interface to lazy binder procedures is going
1838;;; to be changed in an incompatible way to permit all the basic
1839;;; module ops to be virtualized.
1840;;;
1841;;; (make-module size use-list lazy-binding-proc) => module
1842;;; module-{obarray,uses,binder}[|-set!]
1843;;; (module? obj) => [#t|#f]
1844;;; (module-locally-bound? module symbol) => [#t|#f]
1845;;; (module-bound? module symbol) => [#t|#f]
1846;;; (module-symbol-locally-interned? module symbol) => [#t|#f]
1847;;; (module-symbol-interned? module symbol) => [#t|#f]
1848;;; (module-local-variable module symbol) => [#<variable ...> | #f]
1849;;; (module-variable module symbol) => [#<variable ...> | #f]
1850;;; (module-symbol-binding module symbol opt-value)
9b5a0d84 1851;;; => [ <obj> | opt-value | an error occurs ]
0f2d19dd
JB
1852;;; (module-make-local-var! module symbol) => #<variable...>
1853;;; (module-add! module symbol var) => unspecified
1854;;; (module-remove! module symbol) => unspecified
1855;;; (module-for-each proc module) => unspecified
1856;;; (make-scm-module) => module ; a lazy copy of the symhash module
1857;;; (set-current-module module) => unspecified
1858;;; (current-module) => #<module...>
1859;;;
1860;;;
1861
1862\f
3d2ada2f 1863
44cf1f0f 1864;;; {Printing Modules}
3d2ada2f
DH
1865;;;
1866
44cf1f0f 1867;; This is how modules are printed. You can re-define it.
31ac29b6 1868(define (%print-module mod port)
0f2d19dd
JB
1869 (display "#<" port)
1870 (display (or (module-kind mod) "module") port)
dc1eed52
AW
1871 (display " " port)
1872 (display (module-name mod) port)
0f2d19dd
JB
1873 (display " " port)
1874 (display (number->string (object-address mod) 16) port)
1875 (display ">" port))
1876
31ac29b6
AW
1877(letrec-syntax
1878 ;; Locally extend the syntax to allow record accessors to be defined at
1879 ;; compile-time. Cache the rtd locally to the constructor, the getters and
1880 ;; the setters, in order to allow for redefinition of the record type; not
1881 ;; relevant in the case of modules, but perhaps if we make this public, it
1882 ;; could matter.
1883
1884 ((define-record-type
1885 (lambda (x)
1886 (define (make-id scope . fragments)
49689a3f 1887 (datum->syntax scope
31ac29b6
AW
1888 (apply symbol-append
1889 (map (lambda (x)
1890 (if (symbol? x) x (syntax->datum x)))
1891 fragments))))
1892
1893 (define (getter rtd type-name field slot)
1894 #`(define #,(make-id rtd type-name '- field)
1895 (let ((rtd #,rtd))
1896 (lambda (#,type-name)
1897 (if (eq? (struct-vtable #,type-name) rtd)
1898 (struct-ref #,type-name #,slot)
1899 (%record-type-error rtd #,type-name))))))
1900
1901 (define (setter rtd type-name field slot)
1902 #`(define #,(make-id rtd 'set- type-name '- field '!)
1903 (let ((rtd #,rtd))
1904 (lambda (#,type-name val)
1905 (if (eq? (struct-vtable #,type-name) rtd)
1906 (struct-set! #,type-name #,slot val)
1907 (%record-type-error rtd #,type-name))))))
1908
1909 (define (accessors rtd type-name fields n exp)
1910 (syntax-case fields ()
1911 (() exp)
1912 (((field #:no-accessors) field* ...) (identifier? #'field)
1913 (accessors rtd type-name #'(field* ...) (1+ n)
1914 exp))
1915 (((field #:no-setter) field* ...) (identifier? #'field)
1916 (accessors rtd type-name #'(field* ...) (1+ n)
1917 #`(begin #,exp
1918 #,(getter rtd type-name #'field n))))
1919 (((field #:no-getter) field* ...) (identifier? #'field)
1920 (accessors rtd type-name #'(field* ...) (1+ n)
1921 #`(begin #,exp
1922 #,(setter rtd type-name #'field n))))
1923 ((field field* ...) (identifier? #'field)
1924 (accessors rtd type-name #'(field* ...) (1+ n)
1925 #`(begin #,exp
1926 #,(getter rtd type-name #'field n)
1927 #,(setter rtd type-name #'field n))))))
1928
1929 (define (predicate rtd type-name fields exp)
1930 (accessors
1931 rtd type-name fields 0
1932 #`(begin
1933 #,exp
1934 (define (#,(make-id rtd type-name '?) obj)
1935 (and (struct? obj) (eq? (struct-vtable obj) #,rtd))))))
1936
1937 (define (field-list fields)
1938 (syntax-case fields ()
1939 (() '())
1940 (((f . opts) . rest) (identifier? #'f)
1941 (cons #'f (field-list #'rest)))
1942 ((f . rest) (identifier? #'f)
1943 (cons #'f (field-list #'rest)))))
1944
1945 (define (constructor rtd type-name fields exp)
1946 (let ((ctor (make-id rtd type-name '-constructor))
1947 (args (field-list fields)))
1948 (predicate rtd type-name fields
1949 #`(begin #,exp
1950 (define #,ctor
1951 (let ((rtd #,rtd))
1952 (lambda #,args
1953 (make-struct rtd 0 #,@args))))
1954 (struct-set! #,rtd (+ vtable-offset-user 2)
1955 #,ctor)))))
1956
1957 (define (type type-name printer fields)
1958 (define (make-layout)
1959 (let lp ((fields fields) (slots '()))
1960 (syntax-case fields ()
1961 (() (datum->syntax #'here
1962 (make-struct-layout
1963 (apply string-append slots))))
1964 ((_ . rest) (lp #'rest (cons "pw" slots))))))
1965
1966 (let ((rtd (make-id type-name type-name '-type)))
1967 (constructor rtd type-name fields
1968 #`(begin
1969 (define #,rtd
1970 (make-struct record-type-vtable 0
1971 '#,(make-layout)
1972 #,printer
1973 '#,type-name
1974 '#,(field-list fields)))
1975 (set-struct-vtable-name! #,rtd '#,type-name)))))
1976
1977 (syntax-case x ()
1978 ((_ type-name printer (field ...))
1979 (type #'type-name #'printer #'(field ...)))))))
1980
1981 ;; module-type
1982 ;;
1983 ;; A module is characterized by an obarray in which local symbols
1984 ;; are interned, a list of modules, "uses", from which non-local
1985 ;; bindings can be inherited, and an optional lazy-binder which
1986 ;; is a (CLOSURE module symbol) which, as a last resort, can provide
1987 ;; bindings that would otherwise not be found locally in the module.
1988 ;;
1989 ;; NOTE: If you change the set of fields or their order, you also need to
1990 ;; change the constants in libguile/modules.h.
1991 ;;
1992 ;; NOTE: The getter `module-eval-closure' is used in libguile/modules.c.
1993 ;; NOTE: The getter `module-transfomer' is defined libguile/modules.c.
1994 ;; NOTE: The getter `module-name' is defined later, due to boot reasons.
4e48b495 1995 ;; NOTE: The getter `module-public-interface' is used in libguile/modules.c.
31ac29b6
AW
1996 ;;
1997 (define-record-type module
1998 (lambda (obj port) (%print-module obj port))
1999 (obarray
2000 uses
2001 binder
2002 eval-closure
2003 (transformer #:no-getter)
2004 (name #:no-getter)
2005 kind
2006 duplicates-handlers
2007 (import-obarray #:no-setter)
2008 observers
2009 (weak-observers #:no-setter)
f905381d 2010 version
81fc66cf 2011 submodules
4e48b495 2012 submodule-binder
78f79f18
AW
2013 public-interface
2014 filename)))
31ac29b6 2015
0f2d19dd 2016
8b718458 2017;; make-module &opt size uses binder
0f2d19dd 2018;;
8b718458
JB
2019;; Create a new module, perhaps with a particular size of obarray,
2020;; initial uses list, or binding procedure.
0f2d19dd 2021;;
e9729cbb 2022(define* (make-module #:optional (size 31) (uses '()) (binder #f))
e9729cbb
AW
2023 (if (not (integer? size))
2024 (error "Illegal size to make-module." size))
2025 (if (not (and (list? uses)
2026 (and-map module? uses)))
2027 (error "Incorrect use list." uses))
2028 (if (and binder (not (procedure? binder)))
2029 (error
2030 "Lazy-binder expected to be a procedure or #f." binder))
2031
2032 (let ((module (module-constructor (make-hash-table size)
2033 uses binder #f macroexpand
2034 #f #f #f
917b0e72 2035 (make-hash-table)
e9729cbb
AW
2036 '()
2037 (make-weak-key-hash-table 31) #f
2038 (make-hash-table 7) #f #f #f)))
2039
2040 ;; We can't pass this as an argument to module-constructor,
2041 ;; because we need it to close over a pointer to the module
2042 ;; itself.
2043 (set-module-eval-closure! module (standard-eval-closure module))
2044
2045 module))
0f2d19dd 2046
8b718458 2047
0f2d19dd 2048\f
3d2ada2f 2049
1777c18b
MD
2050;;; {Observer protocol}
2051;;;
2052
2053(define (module-observe module proc)
2054 (set-module-observers! module (cons proc (module-observers module)))
2055 (cons module proc))
2056
723ae5b3 2057(define* (module-observe-weak module observer-id #:optional (proc observer-id))
608860a5
LC
2058 ;; Register PROC as an observer of MODULE under name OBSERVER-ID (which can
2059 ;; be any Scheme object). PROC is invoked and passed MODULE any time
2060 ;; MODULE is modified. PROC gets unregistered when OBSERVER-ID gets GC'd
2061 ;; (thus, it is never unregistered if OBSERVER-ID is an immediate value,
2062 ;; for instance).
2063
2064 ;; The two-argument version is kept for backward compatibility: when called
2065 ;; with two arguments, the observer gets unregistered when closure PROC
2066 ;; gets GC'd (making it impossible to use an anonymous lambda for PROC).
723ae5b3 2067 (hashq-set! (module-weak-observers module) observer-id proc))
1777c18b
MD
2068
2069(define (module-unobserve token)
2070 (let ((module (car token))
9b5a0d84 2071 (id (cdr token)))
1777c18b 2072 (if (integer? id)
9b5a0d84
AW
2073 (hash-remove! (module-weak-observers module) id)
2074 (set-module-observers! module (delq1! id (module-observers module)))))
1777c18b
MD
2075 *unspecified*)
2076
d57da08b 2077(define module-defer-observers #f)
03d6cddc 2078(define module-defer-observers-mutex (make-mutex 'recursive))
d57da08b
MD
2079(define module-defer-observers-table (make-hash-table))
2080
1a961d7e 2081(define (module-modified m)
d57da08b
MD
2082 (if module-defer-observers
2083 (hash-set! module-defer-observers-table m #t)
2084 (module-call-observers m)))
2085
2086;;; This function can be used to delay calls to observers so that they
2087;;; can be called once only in the face of massive updating of modules.
2088;;;
2089(define (call-with-deferred-observers thunk)
2090 (dynamic-wind
2091 (lambda ()
9b5a0d84
AW
2092 (lock-mutex module-defer-observers-mutex)
2093 (set! module-defer-observers #t))
d57da08b
MD
2094 thunk
2095 (lambda ()
9b5a0d84
AW
2096 (set! module-defer-observers #f)
2097 (hash-for-each (lambda (m dummy)
2098 (module-call-observers m))
2099 module-defer-observers-table)
2100 (hash-clear! module-defer-observers-table)
2101 (unlock-mutex module-defer-observers-mutex))))
d57da08b
MD
2102
2103(define (module-call-observers m)
1777c18b 2104 (for-each (lambda (proc) (proc m)) (module-observers m))
608860a5
LC
2105
2106 ;; We assume that weak observers don't (un)register themselves as they are
2107 ;; called since this would preclude proper iteration over the hash table
2108 ;; elements.
2109 (hash-for-each (lambda (id proc) (proc m)) (module-weak-observers m)))
1777c18b
MD
2110
2111\f
3d2ada2f 2112
0f2d19dd
JB
2113;;; {Module Searching in General}
2114;;;
2115;;; We sometimes want to look for properties of a symbol
2116;;; just within the obarray of one module. If the property
2117;;; holds, then it is said to hold ``locally'' as in, ``The symbol
2118;;; DISPLAY is locally rebound in the module `safe-guile'.''
2119;;;
2120;;;
2121;;; Other times, we want to test for a symbol property in the obarray
2122;;; of M and, if it is not found there, try each of the modules in the
2123;;; uses list of M. This is the normal way of testing for some
2124;;; property, so we state these properties without qualification as
2125;;; in: ``The symbol 'fnord is interned in module M because it is
2126;;; interned locally in module M2 which is a member of the uses list
2127;;; of M.''
2128;;;
2129
2130;; module-search fn m
20edfbbd 2131;;
0f2d19dd
JB
2132;; return the first non-#f result of FN applied to M and then to
2133;; the modules in the uses of m, and so on recursively. If all applications
2134;; return #f, then so does this function.
2135;;
2136(define (module-search fn m v)
2137 (define (loop pos)
2138 (and (pair? pos)
9b5a0d84
AW
2139 (or (module-search fn (car pos) v)
2140 (loop (cdr pos)))))
0f2d19dd
JB
2141 (or (fn m v)
2142 (loop (module-uses m))))
2143
2144
2145;;; {Is a symbol bound in a module?}
2146;;;
2147;;; Symbol S in Module M is bound if S is interned in M and if the binding
2148;;; of S in M has been set to some well-defined value.
2149;;;
2150
2151;; module-locally-bound? module symbol
2152;;
2153;; Is a symbol bound (interned and defined) locally in a given module?
2154;;
2155(define (module-locally-bound? m v)
2156 (let ((var (module-local-variable m v)))
2157 (and var
9b5a0d84 2158 (variable-bound? var))))
0f2d19dd
JB
2159
2160;; module-bound? module symbol
2161;;
2162;; Is a symbol bound (interned and defined) anywhere in a given module
2163;; or its uses?
2164;;
2165(define (module-bound? m v)
f176c584
AW
2166 (let ((var (module-variable m v)))
2167 (and var
9b5a0d84 2168 (variable-bound? var))))
0f2d19dd
JB
2169
2170;;; {Is a symbol interned in a module?}
2171;;;
20edfbbd 2172;;; Symbol S in Module M is interned if S occurs in
0f2d19dd
JB
2173;;; of S in M has been set to some well-defined value.
2174;;;
2175;;; It is possible to intern a symbol in a module without providing
2176;;; an initial binding for the corresponding variable. This is done
2177;;; with:
2178;;; (module-add! module symbol (make-undefined-variable))
2179;;;
2180;;; In that case, the symbol is interned in the module, but not
2181;;; bound there. The unbound symbol shadows any binding for that
2182;;; symbol that might otherwise be inherited from a member of the uses list.
2183;;;
2184
2185(define (module-obarray-get-handle ob key)
2186 ((if (symbol? key) hashq-get-handle hash-get-handle) ob key))
2187
2188(define (module-obarray-ref ob key)
2189 ((if (symbol? key) hashq-ref hash-ref) ob key))
2190
2191(define (module-obarray-set! ob key val)
2192 ((if (symbol? key) hashq-set! hash-set!) ob key val))
2193
2194(define (module-obarray-remove! ob key)
2195 ((if (symbol? key) hashq-remove! hash-remove!) ob key))
2196
2197;; module-symbol-locally-interned? module symbol
20edfbbd 2198;;
0f2d19dd
JB
2199;; is a symbol interned (not neccessarily defined) locally in a given module
2200;; or its uses? Interned symbols shadow inherited bindings even if
2201;; they are not themselves bound to a defined value.
2202;;
2203(define (module-symbol-locally-interned? m v)
2204 (not (not (module-obarray-get-handle (module-obarray m) v))))
2205
2206;; module-symbol-interned? module symbol
20edfbbd 2207;;
0f2d19dd
JB
2208;; is a symbol interned (not neccessarily defined) anywhere in a given module
2209;; or its uses? Interned symbols shadow inherited bindings even if
2210;; they are not themselves bound to a defined value.
2211;;
2212(define (module-symbol-interned? m v)
2213 (module-search module-symbol-locally-interned? m v))
2214
2215
2216;;; {Mapping modules x symbols --> variables}
2217;;;
2218
2219;; module-local-variable module symbol
2220;; return the local variable associated with a MODULE and SYMBOL.
2221;;
2222;;; This function is very important. It is the only function that can
2223;;; return a variable from a module other than the mutators that store
2224;;; new variables in modules. Therefore, this function is the location
2225;;; of the "lazy binder" hack.
2226;;;
2227;;; If symbol is defined in MODULE, and if the definition binds symbol
2228;;; to a variable, return that variable object.
2229;;;
2230;;; If the symbols is not found at first, but the module has a lazy binder,
2231;;; then try the binder.
2232;;;
2233;;; If the symbol is not found at all, return #f.
2234;;;
608860a5
LC
2235;;; (This is now written in C, see `modules.c'.)
2236;;;
0f2d19dd
JB
2237
2238;;; {Mapping modules x symbols --> bindings}
2239;;;
2240;;; These are similar to the mapping to variables, except that the
2241;;; variable is dereferenced.
2242;;;
2243
2244;; module-symbol-binding module symbol opt-value
20edfbbd 2245;;
0f2d19dd
JB
2246;; return the binding of a variable specified by name within
2247;; a given module, signalling an error if the variable is unbound.
2248;; If the OPT-VALUE is passed, then instead of signalling an error,
2249;; return OPT-VALUE.
2250;;
2251(define (module-symbol-local-binding m v . opt-val)
2252 (let ((var (module-local-variable m v)))
7b07e5ef 2253 (if (and var (variable-bound? var))
9b5a0d84
AW
2254 (variable-ref var)
2255 (if (not (null? opt-val))
2256 (car opt-val)
2257 (error "Locally unbound variable." v)))))
0f2d19dd
JB
2258
2259;; module-symbol-binding module symbol opt-value
20edfbbd 2260;;
0f2d19dd
JB
2261;; return the binding of a variable specified by name within
2262;; a given module, signalling an error if the variable is unbound.
2263;; If the OPT-VALUE is passed, then instead of signalling an error,
2264;; return OPT-VALUE.
2265;;
2266(define (module-symbol-binding m v . opt-val)
2267 (let ((var (module-variable m v)))
7b07e5ef 2268 (if (and var (variable-bound? var))
9b5a0d84
AW
2269 (variable-ref var)
2270 (if (not (null? opt-val))
2271 (car opt-val)
2272 (error "Unbound variable." v)))))
0f2d19dd
JB
2273
2274
2275\f
3d2ada2f 2276
0f2d19dd
JB
2277;;; {Adding Variables to Modules}
2278;;;
0f2d19dd
JB
2279
2280;; module-make-local-var! module symbol
20edfbbd 2281;;
0f2d19dd
JB
2282;; ensure a variable for V in the local namespace of M.
2283;; If no variable was already there, then create a new and uninitialzied
2284;; variable.
2285;;
d57da08b
MD
2286;; This function is used in modules.c.
2287;;
0f2d19dd
JB
2288(define (module-make-local-var! m v)
2289 (or (let ((b (module-obarray-ref (module-obarray m) v)))
9b5a0d84
AW
2290 (and (variable? b)
2291 (begin
2292 ;; Mark as modified since this function is called when
2293 ;; the standard eval closure defines a binding
2294 (module-modified m)
2295 b)))
0c5f718b 2296
608860a5
LC
2297 ;; Create a new local variable.
2298 (let ((local-var (make-undefined-variable)))
2299 (module-add! m v local-var)
2300 local-var)))
0f2d19dd 2301
89d06712 2302;; module-ensure-local-variable! module symbol
9540368e 2303;;
89d06712
MV
2304;; Ensure that there is a local variable in MODULE for SYMBOL. If
2305;; there is no binding for SYMBOL, create a new uninitialized
2306;; variable. Return the local variable.
9540368e 2307;;
89d06712
MV
2308(define (module-ensure-local-variable! module symbol)
2309 (or (module-local-variable module symbol)
9540368e 2310 (let ((var (make-undefined-variable)))
9b5a0d84
AW
2311 (module-add! module symbol var)
2312 var)))
9540368e 2313
0f2d19dd 2314;; module-add! module symbol var
20edfbbd 2315;;
0f2d19dd
JB
2316;; ensure a particular variable for V in the local namespace of M.
2317;;
2318(define (module-add! m v var)
2319 (if (not (variable? var))
2320 (error "Bad variable to module-add!" var))
1777c18b 2321 (module-obarray-set! (module-obarray m) v var)
1a961d7e 2322 (module-modified m))
0f2d19dd 2323
20edfbbd
TTN
2324;; module-remove!
2325;;
0f2d19dd
JB
2326;; make sure that a symbol is undefined in the local namespace of M.
2327;;
2328(define (module-remove! m v)
c35738c1 2329 (module-obarray-remove! (module-obarray m) v)
1a961d7e 2330 (module-modified m))
0f2d19dd
JB
2331
2332(define (module-clear! m)
c35738c1 2333 (hash-clear! (module-obarray m))
1a961d7e 2334 (module-modified m))
0f2d19dd
JB
2335
2336;; MODULE-FOR-EACH -- exported
20edfbbd 2337;;
0f2d19dd
JB
2338;; Call PROC on each symbol in MODULE, with arguments of (SYMBOL VARIABLE).
2339;;
2340(define (module-for-each proc module)
c35738c1 2341 (hash-for-each proc (module-obarray module)))
0f2d19dd
JB
2342
2343(define (module-map proc module)
711a9fd7 2344 (hash-map->list proc (module-obarray module)))
c35738c1 2345
0f27ab8a
AW
2346;; Submodules
2347;;
2348;; Modules exist in a separate namespace from values, because you generally do
2349;; not want the name of a submodule, which you might not even use, to collide
2350;; with local variables that happen to be named the same as the submodule.
2351;;
2352(define (module-ref-submodule module name)
81fc66cf
AW
2353 (or (hashq-ref (module-submodules module) name)
2354 (and (module-submodule-binder module)
2355 ((module-submodule-binder module) module name))))
0f27ab8a
AW
2356
2357(define (module-define-submodule! module name submodule)
f6a5308b 2358 (hashq-set! (module-submodules module) name submodule))
0f27ab8a 2359
0f2d19dd
JB
2360\f
2361
0f2d19dd
JB
2362;;; {Module-based Loading}
2363;;;
2364
2365(define (save-module-excursion thunk)
2366 (let ((inner-module (current-module))
9b5a0d84 2367 (outer-module #f))
0f2d19dd 2368 (dynamic-wind (lambda ()
9b5a0d84
AW
2369 (set! outer-module (current-module))
2370 (set-current-module inner-module)
2371 (set! inner-module #f))
2372 thunk
2373 (lambda ()
2374 (set! inner-module (current-module))
2375 (set-current-module outer-module)
2376 (set! outer-module #f)))))
0f2d19dd 2377
0f2d19dd 2378\f
3d2ada2f 2379
44cf1f0f 2380;;; {MODULE-REF -- exported}
3d2ada2f
DH
2381;;;
2382
0f2d19dd
JB
2383;; Returns the value of a variable called NAME in MODULE or any of its
2384;; used modules. If there is no such variable, then if the optional third
2385;; argument DEFAULT is present, it is returned; otherwise an error is signaled.
20edfbbd 2386;;
0f2d19dd
JB
2387(define (module-ref module name . rest)
2388 (let ((variable (module-variable module name)))
2389 (if (and variable (variable-bound? variable))
9b5a0d84
AW
2390 (variable-ref variable)
2391 (if (null? rest)
2392 (error "No variable named" name 'in module)
2393 (car rest) ; default value
2394 ))))
0f2d19dd
JB
2395
2396;; MODULE-SET! -- exported
2397;;
2398;; Sets the variable called NAME in MODULE (or in a module that MODULE uses)
2399;; to VALUE; if there is no such variable, an error is signaled.
20edfbbd 2400;;
0f2d19dd
JB
2401(define (module-set! module name value)
2402 (let ((variable (module-variable module name)))
2403 (if variable
9b5a0d84
AW
2404 (variable-set! variable value)
2405 (error "No variable named" name 'in module))))
0f2d19dd
JB
2406
2407;; MODULE-DEFINE! -- exported
2408;;
2409;; Sets the variable called NAME in MODULE to VALUE; if there is no such
2410;; variable, it is added first.
20edfbbd 2411;;
0f2d19dd
JB
2412(define (module-define! module name value)
2413 (let ((variable (module-local-variable module name)))
2414 (if variable
9b5a0d84
AW
2415 (begin
2416 (variable-set! variable value)
2417 (module-modified module))
2418 (let ((variable (make-variable value)))
2419 (module-add! module name variable)))))
0f2d19dd 2420
ed218d98
MV
2421;; MODULE-DEFINED? -- exported
2422;;
2423;; Return #t iff NAME is defined in MODULE (or in a module that MODULE
2424;; uses)
2425;;
2426(define (module-defined? module name)
2427 (let ((variable (module-variable module name)))
2428 (and variable (variable-bound? variable))))
2429
0f2d19dd
JB
2430;; MODULE-USE! module interface
2431;;
2432;; Add INTERFACE to the list of interfaces used by MODULE.
20edfbbd 2433;;
0f2d19dd 2434(define (module-use! module interface)
b1907902
AW
2435 (if (not (or (eq? module interface)
2436 (memq interface (module-uses module))))
608860a5
LC
2437 (begin
2438 ;; Newly used modules must be appended rather than consed, so that
2439 ;; `module-variable' traverses the use list starting from the first
2440 ;; used module.
51c0fd80
AR
2441 (set-module-uses! module (append (module-uses module)
2442 (list interface)))
8f44138a 2443 (hash-clear! (module-import-obarray module))
608860a5 2444 (module-modified module))))
0f2d19dd 2445
7b07e5ef
MD
2446;; MODULE-USE-INTERFACES! module interfaces
2447;;
8d795c83
AW
2448;; Same as MODULE-USE!, but only notifies module observers after all
2449;; interfaces are added to the inports list.
7b07e5ef
MD
2450;;
2451(define (module-use-interfaces! module interfaces)
8d795c83
AW
2452 (let* ((cur (module-uses module))
2453 (new (let lp ((in interfaces) (out '()))
2454 (if (null? in)
2455 (reverse out)
2456 (lp (cdr in)
2457 (let ((iface (car in)))
2458 (if (or (memq iface cur) (memq iface out))
2459 out
2460 (cons iface out))))))))
2461 (set-module-uses! module (append cur new))
4181e920
AW
2462 (hash-clear! (module-import-obarray module))
2463 (module-modified module)))
7b07e5ef 2464
0f2d19dd 2465\f
3d2ada2f 2466
0f2d19dd
JB
2467;;; {Recursive Namespaces}
2468;;;
0f2d19dd 2469;;; A hierarchical namespace emerges if we consider some module to be
b910c4ac 2470;;; root, and submodules of that module to be nested namespaces.
0f2d19dd 2471;;;
b910c4ac 2472;;; The routines here manage variable names in hierarchical namespace.
0f2d19dd
JB
2473;;; Each variable name is a list of elements, looked up in successively nested
2474;;; modules.
2475;;;
9b5a0d84 2476;;; (nested-ref some-root-module '(foo bar baz))
b910c4ac
AW
2477;;; => <value of a variable named baz in the submodule bar of
2478;;; the submodule foo of some-root-module>
0f2d19dd
JB
2479;;;
2480;;;
2481;;; There are:
2482;;;
9b5a0d84
AW
2483;;; ;; a-root is a module
2484;;; ;; name is a list of symbols
0f2d19dd 2485;;;
9b5a0d84
AW
2486;;; nested-ref a-root name
2487;;; nested-set! a-root name val
2488;;; nested-define! a-root name val
2489;;; nested-remove! a-root name
0f2d19dd 2490;;;
b910c4ac
AW
2491;;; These functions manipulate values in namespaces. For referencing the
2492;;; namespaces themselves, use the following:
0f2d19dd 2493;;;
b910c4ac
AW
2494;;; nested-ref-module a-root name
2495;;; nested-define-module! a-root name mod
2496;;;
2497;;; (current-module) is a natural choice for a root so for convenience there are
0f2d19dd
JB
2498;;; also:
2499;;;
b910c4ac
AW
2500;;; local-ref name == nested-ref (current-module) name
2501;;; local-set! name val == nested-set! (current-module) name val
2502;;; local-define name val == nested-define! (current-module) name val
2503;;; local-remove name == nested-remove! (current-module) name
2504;;; local-ref-module name == nested-ref-module (current-module) name
2505;;; local-define-module! name m == nested-define-module! (current-module) name m
0f2d19dd
JB
2506;;;
2507
2508
0dd5491c 2509(define (nested-ref root names)
b910c4ac
AW
2510 (if (null? names)
2511 root
2512 (let loop ((cur root)
2513 (head (car names))
2514 (tail (cdr names)))
2515 (if (null? tail)
2516 (module-ref cur head #f)
2517 (let ((cur (module-ref-submodule cur head)))
2518 (and cur
2519 (loop cur (car tail) (cdr tail))))))))
0f2d19dd 2520
0dd5491c 2521(define (nested-set! root names val)
0f2d19dd 2522 (let loop ((cur root)
b910c4ac
AW
2523 (head (car names))
2524 (tail (cdr names)))
2525 (if (null? tail)
2526 (module-set! cur head val)
2527 (let ((cur (module-ref-submodule cur head)))
2528 (if (not cur)
2529 (error "failed to resolve module" names)
2530 (loop cur (car tail) (cdr tail)))))))
0f2d19dd 2531
0dd5491c 2532(define (nested-define! root names val)
0f2d19dd 2533 (let loop ((cur root)
b910c4ac
AW
2534 (head (car names))
2535 (tail (cdr names)))
2536 (if (null? tail)
2537 (module-define! cur head val)
2538 (let ((cur (module-ref-submodule cur head)))
2539 (if (not cur)
2540 (error "failed to resolve module" names)
2541 (loop cur (car tail) (cdr tail)))))))
0f2d19dd 2542
0dd5491c 2543(define (nested-remove! root names)
0f2d19dd 2544 (let loop ((cur root)
b910c4ac
AW
2545 (head (car names))
2546 (tail (cdr names)))
2547 (if (null? tail)
2548 (module-remove! cur head)
2549 (let ((cur (module-ref-submodule cur head)))
2550 (if (not cur)
2551 (error "failed to resolve module" names)
2552 (loop cur (car tail) (cdr tail)))))))
2553
2554
2555(define (nested-ref-module root names)
2556 (let loop ((cur root)
2557 (names names))
2558 (if (null? names)
2559 cur
2560 (let ((cur (module-ref-submodule cur (car names))))
2561 (and cur
2562 (loop cur (cdr names)))))))
2563
2564(define (nested-define-module! root names module)
2565 (if (null? names)
2566 (error "can't redefine root module" root module)
2567 (let loop ((cur root)
2568 (head (car names))
2569 (tail (cdr names)))
2570 (if (null? tail)
2571 (module-define-submodule! cur head module)
2572 (let ((cur (or (module-ref-submodule cur head)
2573 (let ((m (make-module 31)))
2574 (set-module-kind! m 'directory)
2575 (set-module-name! m (append (module-name cur)
2576 (list head)))
2577 (module-define-submodule! cur head m)
2578 m))))
2579 (loop cur (car tail) (cdr tail)))))))
2580
0f2d19dd 2581
1623ca68
AW
2582(define (local-ref names)
2583 (nested-ref (current-module) names))
2584
2585(define (local-set! names val)
2586 (nested-set! (current-module) names val))
2587
2588(define (local-define names val)
2589 (nested-define! (current-module) names val))
2590
2591(define (local-remove names)
2592 (nested-remove! (current-module) names))
2593
2594(define (local-ref-module names)
2595 (nested-ref-module (current-module) names))
2596
2597(define (local-define-module names mod)
2598 (nested-define-module! (current-module) names mod))
b910c4ac 2599
0f2d19dd
JB
2600
2601
2602\f
3d2ada2f 2603
cb67c838 2604;;; {The (guile) module}
0f2d19dd 2605;;;
cb67c838
AW
2606;;; The standard module, which has the core Guile bindings. Also called the
2607;;; "root module", as it is imported by many other modules, but it is not
2608;;; necessarily the root of anything; and indeed, the module named '() might be
2609;;; better thought of as a root.
0f2d19dd 2610;;;
bbd1d133 2611
edc185c7
MD
2612(define (set-system-module! m s)
2613 (set-procedure-property! (module-eval-closure m) 'system-module s))
0f2d19dd 2614
76aea207
AW
2615;; The root module uses the pre-modules-obarray as its obarray. This
2616;; special obarray accumulates all bindings that have been established
2617;; before the module system is fully booted.
2618;;
2619;; (The obarray continues to be used by code that has been closed over
2620;; before the module system has been booted.)
2621;;
2622(define the-root-module
2623 (let ((m (make-module 0)))
2624 (set-module-obarray! m (%get-pre-modules-obarray))
2625 (set-module-name! m '(guile))
2626 (set-system-module! m #t)
2627 m))
2628
2629;; The root interface is a module that uses the same obarray as the
2630;; root module. It does not allow new definitions, tho.
2631;;
2632(define the-scm-module
2633 (let ((m (make-module 0)))
2634 (set-module-obarray! m (%get-pre-modules-obarray))
2635 (set-module-eval-closure! m (standard-interface-eval-closure m))
2636 (set-module-name! m '(guile))
2637 (set-module-kind! m 'interface)
2638 (set-system-module! m #t)
7354a105
LC
2639
2640 ;; In Guile 1.8 and earlier M was its own public interface.
2641 (set-module-public-interface! m m)
2642
76aea207
AW
2643 m))
2644
2645(set-module-public-interface! the-root-module the-scm-module)
bbd1d133
AW
2646
2647\f
2648
2649;; Now that we have a root module, even though modules aren't fully booted,
2650;; expand the definition of resolve-module.
2651;;
2652(define (resolve-module name . args)
2653 (if (equal? name '(guile))
2654 the-root-module
2655 (error "unexpected module to resolve during module boot" name)))
2656
2657;; Cheat. These bindings are needed by modules.c, but we don't want
2658;; to move their real definition here because that would be unnatural.
2659;;
57ced5b9 2660(define define-module* #f)
bbd1d133
AW
2661(define process-use-modules #f)
2662(define module-export! #f)
2663(define default-duplicate-binding-procedures #f)
2664
2665;; This boots the module system. All bindings needed by modules.c
2666;; must have been defined by now.
296ff5e7 2667;;
bbd1d133
AW
2668(set-current-module the-root-module)
2669
2670
2671\f
2672
2673;; Now that modules are booted, give module-name its final definition.
2674;;
2675(define module-name
2676 (let ((accessor (record-accessor module-type 'name)))
2677 (lambda (mod)
2678 (or (accessor mod)
2679 (let ((name (list (gensym))))
cb67c838
AW
2680 ;; Name MOD and bind it in the module root so that it's visible to
2681 ;; `resolve-module'. This is important as `psyntax' stores module
2682 ;; names and relies on being able to `resolve-module' them.
bbd1d133 2683 (set-module-name! mod name)
9e0bfdba 2684 (nested-define-module! (resolve-module '() #f) name mod)
bbd1d133
AW
2685 (accessor mod))))))
2686
296ff5e7 2687(define (make-modules-in module name)
9e0bfdba
AW
2688 (or (nested-ref-module module name)
2689 (let ((m (make-module 31)))
2690 (set-module-kind! m 'directory)
2691 (set-module-name! m (append (module-name module) name))
2692 (nested-define-module! module name m)
2693 m)))
0f2d19dd 2694
296ff5e7
MV
2695(define (beautify-user-module! module)
2696 (let ((interface (module-public-interface module)))
2697 (if (or (not interface)
9b5a0d84
AW
2698 (eq? interface module))
2699 (let ((interface (make-module 31)))
2700 (set-module-name! interface (module-name module))
dca14012 2701 (set-module-version! interface (module-version module))
9b5a0d84
AW
2702 (set-module-kind! interface 'interface)
2703 (set-module-public-interface! module interface))))
296ff5e7 2704 (if (and (not (memq the-scm-module (module-uses module)))
9b5a0d84 2705 (not (eq? module the-root-module)))
608860a5
LC
2706 ;; Import the default set of bindings (from the SCM module) in MODULE.
2707 (module-use! module the-scm-module)))
432558b9 2708
dca14012 2709(define (version-matches? version-ref target)
dca14012
JG
2710 (define (sub-versions-match? v-refs t)
2711 (define (sub-version-matches? v-ref t)
befd1df9
AW
2712 (let ((matches? (lambda (v) (sub-version-matches? v t))))
2713 (cond
2714 ((number? v-ref) (eqv? v-ref t))
2715 ((list? v-ref)
2716 (case (car v-ref)
2717 ((>=) (>= t (cadr v-ref)))
2718 ((<=) (<= t (cadr v-ref)))
2719 ((and) (and-map matches? (cdr v-ref)))
2720 ((or) (or-map matches? (cdr v-ref)))
2721 ((not) (not (matches? (cadr v-ref))))
2722 (else (error "Invalid sub-version reference" v-ref))))
2723 (else (error "Invalid sub-version reference" v-ref)))))
dca14012
JG
2724 (or (null? v-refs)
2725 (and (not (null? t))
2726 (sub-version-matches? (car v-refs) (car t))
2727 (sub-versions-match? (cdr v-refs) (cdr t)))))
befd1df9
AW
2728
2729 (let ((matches? (lambda (v) (version-matches? v target))))
2730 (or (null? version-ref)
2731 (case (car version-ref)
2732 ((and) (and-map matches? (cdr version-ref)))
2733 ((or) (or-map matches? (cdr version-ref)))
2734 ((not) (not (matches? (cadr version-ref))))
2735 (else (sub-versions-match? version-ref target))))))
dca14012 2736
f95f82f8
AW
2737(define (make-fresh-user-module)
2738 (let ((m (make-module)))
2739 (beautify-user-module! m)
2740 m))
2741
1f60d9d2
MD
2742;; NOTE: This binding is used in libguile/modules.c.
2743;;
53f84bc8 2744(define resolve-module
cb67c838
AW
2745 (let ((root (make-module)))
2746 (set-module-name! root '())
2747 ;; Define the-root-module as '(guile).
d58ccc66 2748 (module-define-submodule! root 'guile the-root-module)
cb67c838 2749
7e314766 2750 (lambda* (name #:optional (autoload #t) (version #f) #:key (ensure #t))
6b7d701e 2751 (let ((already (nested-ref-module root name)))
cb67c838 2752 (cond
d58ccc66 2753 ((and already
cb67c838
AW
2754 (or (not autoload) (module-public-interface already)))
2755 ;; A hit, a palpable hit.
e44d2e4d 2756 (if (and version
cb67c838
AW
2757 (not (version-matches? version (module-version already))))
2758 (error "incompatible module version already loaded" name))
2759 already)
2760 (autoload
2761 ;; Try to autoload the module, and recurse.
2762 (try-load-module name version)
7e314766 2763 (resolve-module name #f #:ensure ensure))
cb67c838 2764 (else
51b22dbb 2765 ;; No module found (or if one was, it had no public interface), and
7e314766
AW
2766 ;; we're not autoloading. Make an empty module if #:ensure is true.
2767 (or already
2768 (and ensure
2769 (make-modules-in root name)))))))))
cb67c838 2770
296ff5e7 2771
dca14012
JG
2772(define (try-load-module name version)
2773 (try-module-autoload name version))
0f2d19dd 2774
c9b16cee 2775(define (reload-module m)
cdab9fc6 2776 "Revisit the source file corresponding to the module @var{m}."
c9b16cee
AW
2777 (let ((f (module-filename m)))
2778 (if f
2779 (save-module-excursion
2780 (lambda ()
2781 ;; Re-set the initial environment, as in try-module-autoload.
2782 (set-current-module (make-fresh-user-module))
2783 (primitive-load-path f)
2784 m))
2785 ;; Though we could guess, we *should* know it.
2786 (error "unknown file name for module" m))))
2787
90847923
MD
2788(define (purify-module! module)
2789 "Removes bindings in MODULE which are inherited from the (guile) module."
2790 (let ((use-list (module-uses module)))
2791 (if (and (pair? use-list)
9b5a0d84
AW
2792 (eq? (car (last-pair use-list)) the-scm-module))
2793 (set-module-uses! module (reverse (cdr (reverse use-list)))))))
90847923 2794
4eecfeb7 2795;; Return a module that is an interface to the module designated by
532cf805
MV
2796;; NAME.
2797;;
c614a00b 2798;; `resolve-interface' takes four keyword arguments:
532cf805
MV
2799;;
2800;; #:select SELECTION
2801;;
2802;; SELECTION is a list of binding-specs to be imported; A binding-spec
2803;; is either a symbol or a pair of symbols (ORIG . SEEN), where ORIG
2804;; is the name in the used module and SEEN is the name in the using
2805;; module. Note that SEEN is also passed through RENAMER, below. The
2806;; default is to select all bindings. If you specify no selection but
4eecfeb7 2807;; a renamer, only the bindings that already exist in the used module
532cf805
MV
2808;; are made available in the interface. Bindings that are added later
2809;; are not picked up.
2810;;
c614a00b 2811;; #:hide BINDINGS
532cf805 2812;;
c614a00b 2813;; BINDINGS is a list of bindings which should not be imported.
f595ccfe
MD
2814;;
2815;; #:prefix PREFIX
2816;;
2817;; PREFIX is a symbol that will be appended to each exported name.
2818;; The default is to not perform any renaming.
532cf805 2819;;
c614a00b
MD
2820;; #:renamer RENAMER
2821;;
2822;; RENAMER is a procedure that takes a symbol and returns its new
2823;; name. The default is not perform any renaming.
2824;;
532cf805
MV
2825;; Signal "no code for module" error if module name is not resolvable
2826;; or its public interface is not available. Signal "no binding"
2827;; error if selected binding does not exist in the used module.
2828;;
36d58fc3
AW
2829(define* (resolve-interface name #:key
2830 (select #f)
2831 (hide '())
2832 (prefix #f)
2833 (renamer (if prefix
2834 (symbol-prefix-proc prefix)
2835 identity))
2836 version)
47aabe86 2837 (let* ((module (resolve-module name #t version #:ensure #f))
b622dec7
TTN
2838 (public-i (and module (module-public-interface module))))
2839 (and (or (not module) (not public-i))
2840 (error "no code for module" name))
c614a00b 2841 (if (and (not select) (null? hide) (eq? renamer identity))
b622dec7 2842 public-i
532cf805 2843 (let ((selection (or select (module-map (lambda (sym var) sym)
9b5a0d84 2844 public-i)))
b622dec7 2845 (custom-i (make-module 31)))
c614a00b 2846 (set-module-kind! custom-i 'custom-interface)
9b5a0d84
AW
2847 (set-module-name! custom-i name)
2848 ;; XXX - should use a lazy binder so that changes to the
2849 ;; used module are picked up automatically.
2850 (for-each (lambda (bspec)
2851 (let* ((direct? (symbol? bspec))
2852 (orig (if direct? bspec (car bspec)))
2853 (seen (if direct? bspec (cdr bspec)))
2854 (var (or (module-local-variable public-i orig)
2855 (module-local-variable module orig)
2856 (error
2857 ;; fixme: format manually for now
2858 (simple-format
2859 #f "no binding `~A' in module ~A"
2860 orig name)))))
2861 (if (memq orig hide)
2862 (set! hide (delq! orig hide))
2863 (module-add! custom-i
2864 (renamer seen)
2865 var))))
2866 selection)
2867 ;; Check that we are not hiding bindings which don't exist
2868 (for-each (lambda (binding)
2869 (if (not (module-local-variable public-i binding))
2870 (error
2871 (simple-format
2872 #f "no binding `~A' to hide in module ~A"
2873 binding name))))
2874 hide)
b622dec7 2875 custom-i))))
fb1b76f4
TTN
2876
2877(define (symbol-prefix-proc prefix)
2878 (lambda (symbol)
2879 (symbol-append prefix symbol)))
0f2d19dd 2880
57ced5b9
AW
2881;; This function is called from "modules.c". If you change it, be
2882;; sure to update "modules.c" as well.
2883
f7f62d3a
AW
2884(define* (define-module* name
2885 #:key filename pure version (duplicates '())
2886 (imports '()) (exports '()) (replacements '())
2887 (re-exports '()) (autoloads '()) transformer)
2888 (define (list-of pred l)
2889 (or (null? l)
2890 (and (pair? l) (pred (car l)) (list-of pred (cdr l)))))
2891 (define (valid-export? x)
2892 (or (symbol? x) (and (pair? x) (symbol? (car x)) (symbol? (cdr x)))))
2893 (define (valid-autoload? x)
2894 (and (pair? x) (list-of symbol? (car x)) (list-of symbol? (cdr x))))
2895
2896 (define (resolve-imports imports)
2897 (define (resolve-import import-spec)
2898 (if (list? import-spec)
2899 (apply resolve-interface import-spec)
2900 (error "unexpected use-module specification" import-spec)))
2901 (let lp ((imports imports) (out '()))
2902 (cond
2903 ((null? imports) (reverse! out))
2904 ((pair? imports)
2905 (lp (cdr imports)
2906 (cons (resolve-import (car imports)) out)))
2907 (else (error "unexpected tail of imports list" imports)))))
2908
2909 ;; We could add a #:no-check arg, set by the define-module macro, if
2910 ;; these checks are taking too much time.
2911 ;;
2912 (let ((module (resolve-module name #f)))
2913 (beautify-user-module! module)
2914 (if filename
2915 (set-module-filename! module filename))
2916 (if pure
2917 (purify-module! module))
2918 (if version
2919 (begin
2920 (if (not (list-of integer? version))
2921 (error "expected list of integers for version"))
2922 (set-module-version! module version)
2923 (set-module-version! (module-public-interface module) version)))
f7f62d3a
AW
2924 (let ((imports (resolve-imports imports)))
2925 (call-with-deferred-observers
2926 (lambda ()
2927 (if (pair? imports)
2928 (module-use-interfaces! module imports))
2929 (if (list-of valid-export? exports)
2930 (if (pair? exports)
2931 (module-export! module exports))
2932 (error "expected exports to be a list of symbols or symbol pairs"))
2933 (if (list-of valid-export? replacements)
2934 (if (pair? replacements)
2935 (module-replace! module replacements))
2936 (error "expected replacements to be a list of symbols or symbol pairs"))
2937 (if (list-of valid-export? re-exports)
2938 (if (pair? re-exports)
2939 (module-re-export! module re-exports))
2940 (error "expected re-exports to be a list of symbols or symbol pairs"))
2941 ;; FIXME
2942 (if (not (null? autoloads))
6b1c5d9d
AW
2943 (apply module-autoload! module autoloads))
2944 ;; Wait until modules have been loaded to resolve duplicates
2945 ;; handlers.
2946 (if (pair? duplicates)
2947 (let ((handlers (lookup-duplicates-handlers duplicates)))
2948 (set-module-duplicates-handlers! module handlers))))))
f7f62d3a
AW
2949
2950 (if transformer
2951 (if (and (pair? transformer) (list-of symbol? transformer))
2952 (let ((iface (resolve-interface transformer))
2953 (sym (car (last-pair transformer))))
2954 (set-module-transformer! module (module-ref iface sym)))
2955 (error "expected transformer to be a module name" transformer)))
2956
2957 (run-hook module-defined-hook module)
2958 module))
2959
db853761
NJ
2960;; `module-defined-hook' is a hook that is run whenever a new module
2961;; is defined. Its members are called with one argument, the new
2962;; module.
2963(define module-defined-hook (make-hook 1))
2964
3d2ada2f
DH
2965\f
2966
71225060 2967;;; {Autoload}
3d2ada2f 2968;;;
71225060
MD
2969
2970(define (make-autoload-interface module name bindings)
2971 (let ((b (lambda (a sym definep)
9b5a0d84
AW
2972 (and (memq sym bindings)
2973 (let ((i (module-public-interface (resolve-module name))))
2974 (if (not i)
2975 (error "missing interface for module" name))
2976 (let ((autoload (memq a (module-uses module))))
2977 ;; Replace autoload-interface with actual interface if
2978 ;; that has not happened yet.
2979 (if (pair? autoload)
2980 (set-car! autoload i)))
2981 (module-local-variable i sym))))))
608860a5 2982 (module-constructor (make-hash-table 0) '() b #f #f name 'autoload #f
f905381d 2983 (make-hash-table 0) '() (make-weak-value-hash-table 31) #f
78f79f18 2984 (make-hash-table 0) #f #f #f)))
608860a5
LC
2985
2986(define (module-autoload! module . args)
2987 "Have @var{module} automatically load the module named @var{name} when one
2988of the symbols listed in @var{bindings} is looked up. @var{args} should be a
2989list of module-name/binding-list pairs, e.g., as in @code{(module-autoload!
2990module '(ice-9 q) '(make-q q-length))}."
2991 (let loop ((args args))
2992 (cond ((null? args)
2993 #t)
2994 ((null? (cdr args))
2995 (error "invalid name+binding autoload list" args))
2996 (else
2997 (let ((name (car args))
2998 (bindings (cadr args)))
2999 (module-use! module (make-autoload-interface module
3000 name bindings))
3001 (loop (cddr args)))))))
3002
71225060 3003
0f2d19dd 3004\f
3d2ada2f 3005
44cf1f0f 3006;;; {Autoloading modules}
3d2ada2f 3007;;;
0f2d19dd
JB
3008
3009(define autoloads-in-progress '())
3010
482a28f9
MV
3011;; This function is called from "modules.c". If you change it, be
3012;; sure to update "modules.c" as well.
3013
d9113d47 3014(define* (try-module-autoload module-name #:optional version)
0f2d19dd 3015 (let* ((reverse-name (reverse module-name))
9b5a0d84
AW
3016 (name (symbol->string (car reverse-name)))
3017 (dir-hint-module-name (reverse (cdr reverse-name)))
3018 (dir-hint (apply string-append
3019 (map (lambda (elt)
3020 (string-append (symbol->string elt) "/"))
3021 dir-hint-module-name))))
0209ca9a 3022 (resolve-module dir-hint-module-name #f)
0f2d19dd 3023 (and (not (autoload-done-or-in-progress? dir-hint name))
9b5a0d84
AW
3024 (let ((didit #f))
3025 (dynamic-wind
3026 (lambda () (autoload-in-progress! dir-hint name))
3027 (lambda ()
eddd16d7
AW
3028 (with-fluids ((current-reader #f))
3029 (save-module-excursion
3030 (lambda ()
39392995
AW
3031 ;; The initial environment when loading a module is a fresh
3032 ;; user module.
3033 (set-current-module (make-fresh-user-module))
e44d2e4d
AW
3034 ;; Here we could allow some other search strategy (other than
3035 ;; primitive-load-path), for example using versions encoded
3036 ;; into the file system -- but then we would have to figure
6f06e8d3 3037 ;; out how to locate the compiled file, do auto-compilation,
e44d2e4d
AW
3038 ;; etc. Punt for now, and don't use versions when locating
3039 ;; the file.
3040 (primitive-load-path (in-vicinity dir-hint name) #f)
eddd16d7 3041 (set! didit #t)))))
9b5a0d84
AW
3042 (lambda () (set-autoloaded! dir-hint name didit)))
3043 didit))))
0f2d19dd 3044
71225060 3045\f
3d2ada2f
DH
3046
3047;;; {Dynamic linking of modules}
3048;;;
d0cbd20c 3049
0f2d19dd
JB
3050(define autoloads-done '((guile . guile)))
3051
3052(define (autoload-done-or-in-progress? p m)
3053 (let ((n (cons p m)))
3054 (->bool (or (member n autoloads-done)
9b5a0d84 3055 (member n autoloads-in-progress)))))
0f2d19dd
JB
3056
3057(define (autoload-done! p m)
3058 (let ((n (cons p m)))
3059 (set! autoloads-in-progress
9b5a0d84 3060 (delete! n autoloads-in-progress))
0f2d19dd 3061 (or (member n autoloads-done)
9b5a0d84 3062 (set! autoloads-done (cons n autoloads-done)))))
0f2d19dd
JB
3063
3064(define (autoload-in-progress! p m)
3065 (let ((n (cons p m)))
3066 (set! autoloads-done
9b5a0d84 3067 (delete! n autoloads-done))
0f2d19dd
JB
3068 (set! autoloads-in-progress (cons n autoloads-in-progress))))
3069
3070(define (set-autoloaded! p m done?)
3071 (if done?
3072 (autoload-done! p m)
3073 (let ((n (cons p m)))
9b5a0d84
AW
3074 (set! autoloads-done (delete! n autoloads-done))
3075 (set! autoloads-in-progress (delete! n autoloads-in-progress)))))
0f2d19dd 3076
0f2d19dd
JB
3077\f
3078
83b38198 3079;;; {Run-time options}
3d2ada2f 3080;;;
83b38198 3081
122f296d
AW
3082(define-syntax define-option-interface
3083 (syntax-rules ()
3084 ((_ (interface (options enable disable) (option-set!)))
3085 (begin
3086 (define options
3087 (case-lambda
3088 (() (interface))
3089 ((arg)
3090 (if (list? arg)
3091 (begin (interface arg) (interface))
3092 (for-each
3093 (lambda (option)
3094 (apply (lambda (name value documentation)
3095 (display name)
3096 (if (< (string-length (symbol->string name)) 8)
3097 (display #\tab))
3098 (display #\tab)
3099 (display value)
3100 (display #\tab)
3101 (display documentation)
3102 (newline))
3103 option))
3104 (interface #t))))))
3105 (define (enable . flags)
3106 (interface (append flags (interface)))
3107 (interface))
3108 (define (disable . flags)
3109 (let ((options (interface)))
3110 (for-each (lambda (flag) (set! options (delq! flag options)))
3111 flags)
3112 (interface options)
3113 (interface)))
0c65f52c
AW
3114 (define-syntax-rule (option-set! opt val)
3115 (eval-when (eval load compile expand)
3116 (options (append (options) (list 'opt val)))))))))
e9bab9df 3117
e9bab9df
DH
3118(define-option-interface
3119 (debug-options-interface
3120 (debug-options debug-enable debug-disable)
3121 (debug-set!)))
3122
e9bab9df
DH
3123(define-option-interface
3124 (read-options-interface
3125 (read-options read-enable read-disable)
3126 (read-set!)))
3127
3128(define-option-interface
3129 (print-options-interface
3130 (print-options print-enable print-disable)
3131 (print-set!)))
83b38198
MD
3132
3133\f
3134
410e83c0
AW
3135;;; {The Unspecified Value}
3136;;;
3137;;; Currently Guile represents unspecified values via one particular value,
3138;;; which may be obtained by evaluating (if #f #f). It would be nice in the
3139;;; future if we could replace this with a return of 0 values, though.
9346b857 3140;;;
410e83c0
AW
3141
3142(define-syntax *unspecified*
3143 (identifier-syntax (if #f #f)))
3144
3145(define (unspecified? v) (eq? v *unspecified*))
3146
3147
3148\f
3149
90de5c4c
AW
3150;;; {Parameters}
3151;;;
3152
3153(define <parameter>
3154 ;; Three fields: the procedure itself, the fluid, and the converter.
3155 (make-struct <applicable-struct-vtable> 0 'pwprpr))
3156(set-struct-vtable-name! <parameter> '<parameter>)
3157
3158(define* (make-parameter init #:optional (conv (lambda (x) x)))
3159 (let ((fluid (make-fluid (conv init))))
3160 (make-struct <parameter> 0
3161 (case-lambda
3162 (() (fluid-ref fluid))
13dd74c8
AW
3163 ((x) (let ((prev (fluid-ref fluid)))
3164 (fluid-set! fluid (conv x))
3165 prev)))
90de5c4c
AW
3166 fluid conv)))
3167
3168(define (parameter? x)
3169 (and (struct? x) (eq? (struct-vtable x) <parameter>)))
3170
3171(define (parameter-fluid p)
3172 (if (parameter? p)
3173 (struct-ref p 1)
3174 (scm-error 'wrong-type-arg "parameter-fluid"
3175 "Not a parameter: ~S" (list p) #f)))
3176
3177(define (parameter-converter p)
3178 (if (parameter? p)
3179 (struct-ref p 2)
3180 (scm-error 'wrong-type-arg "parameter-fluid"
3181 "Not a parameter: ~S" (list p) #f)))
3182
3183(define-syntax parameterize
3184 (lambda (x)
3185 (syntax-case x ()
3186 ((_ ((param value) ...) body body* ...)
3187 (with-syntax (((p ...) (generate-temporaries #'(param ...))))
3188 #'(let ((p param) ...)
3189 (if (not (parameter? p))
3190 (scm-error 'wrong-type-arg "parameterize"
3191 "Not a parameter: ~S" (list p) #f))
3192 ...
3193 (with-fluids (((struct-ref p 1) ((struct-ref p 2) value))
3194 ...)
3195 body body* ...)))))))
3196
3197\f
9670f238
AW
3198;;;
3199;;; Current ports as parameters.
3200;;;
3201
3202(let ((fluid->parameter
3203 (lambda (fluid conv)
3204 (make-struct <parameter> 0
3205 (case-lambda
3206 (() (fluid-ref fluid))
3207 ((x) (let ((prev (fluid-ref fluid)))
3208 (fluid-set! fluid (conv x))
3209 prev)))
3210 fluid conv))))
3211 (define-syntax-rule (port-parameterize! binding fluid predicate msg)
3212 (begin
3213 (set! binding (fluid->parameter (module-ref (current-module) 'fluid)
3214 (lambda (x)
3215 (if (predicate x) x
3216 (error msg x)))))
3217 (module-remove! (current-module) 'fluid)))
3218
3219 (port-parameterize! current-input-port %current-input-port-fluid
3220 input-port? "expected an input port")
3221 (port-parameterize! current-output-port %current-output-port-fluid
3222 output-port? "expected an output port")
3223 (port-parameterize! current-error-port %current-error-port-fluid
3224 output-port? "expected an output port"))
3225
3226
3227\f
3972de76
AW
3228;;;
3229;;; Warnings.
3230;;;
3231
3232(define current-warning-port
3233 (make-parameter (current-error-port)
3234 (lambda (x)
3235 (if (output-port? x)
3236 x
3237 (error "expected an output port" x)))))
3238
3239
3240\f
90de5c4c 3241
0f2d19dd
JB
3242;;; {Running Repls}
3243;;;
3244
9447207f 3245(define *repl-stack* (make-fluid '()))
1fdd5bec 3246
9346b857
AW
3247;; Programs can call `batch-mode?' to see if they are running as part of a
3248;; script or if they are running interactively. REPL implementations ensure that
3249;; `batch-mode?' returns #f during their extent.
3250;;
1fdd5bec 3251(define (batch-mode?)
9447207f 3252 (null? (fluid-ref *repl-stack*)))
1fdd5bec 3253
9346b857 3254;; Programs can re-enter batch mode, for example after a fork, by calling
0feb833d
AW
3255;; `ensure-batch-mode!'. It's not a great interface, though; it would be better
3256;; to abort to the outermost prompt, and call a thunk there.
1fdd5bec 3257;;
9346b857 3258(define (ensure-batch-mode!)
9d2136ba 3259 (set! batch-mode? (lambda () #t)))
4bbbcd5c 3260
0f2d19dd
JB
3261(define (quit . args)
3262 (apply throw 'quit args))
3263
7950df7c
GH
3264(define exit quit)
3265
0f2d19dd
JB
3266(define (gc-run-time)
3267 (cdr (assq 'gc-time-taken (gc-stats))))
3268
8942e7a1
AW
3269(define abort-hook (make-hook))
3270(define before-error-hook (make-hook))
3271(define after-error-hook (make-hook))
3272(define before-backtrace-hook (make-hook))
3273(define after-backtrace-hook (make-hook))
3274
3e3cec45
MD
3275(define before-read-hook (make-hook))
3276(define after-read-hook (make-hook))
870777d7
KN
3277(define before-eval-hook (make-hook 1))
3278(define after-eval-hook (make-hook 1))
3279(define before-print-hook (make-hook 1))
3280(define after-print-hook (make-hook 1))
1c6cd8e8 3281
c592de96
AW
3282;;; This hook is run at the very end of an interactive session.
3283;;;
3284(define exit-hook (make-hook))
3285
dc5c2038
MD
3286;;; The default repl-reader function. We may override this if we've
3287;;; the readline library.
3288(define repl-reader
17ee350c 3289 (lambda* (prompt #:optional (reader (fluid-ref current-reader)))
0becb8f3 3290 (if (not (char-ready?))
dceb7829
AW
3291 (begin
3292 (display (if (string? prompt) prompt (prompt)))
3293 ;; An interesting situation. The printer resets the column to
3294 ;; 0 by printing a newline, but we then advance it by printing
3295 ;; the prompt. However the port-column of the output port
3296 ;; does not typically correspond with the actual column on the
b3da54d1 3297 ;; screen, because the input is echoed back! Since the
dceb7829
AW
3298 ;; input is line-buffered and thus ends with a newline, the
3299 ;; output will really start on column zero. So, here we zero
3300 ;; it out. See bug 9664.
3301 ;;
3302 ;; Note that for similar reasons, the output-line will not
3303 ;; reflect the actual line on the screen. But given the
3304 ;; possibility of multiline input, the fix is not as
3305 ;; straightforward, so we don't bother.
3306 ;;
3307 ;; Also note that the readline implementation papers over
3308 ;; these concerns, because it's readline itself printing the
3309 ;; prompt, and not Guile.
3310 (set-port-column! (current-output-port) 0)))
dc5c2038 3311 (force-output)
04efd24d 3312 (run-hook before-read-hook)
17ee350c 3313 ((or reader read) (current-input-port))))
dc5c2038 3314
0f2d19dd 3315
0f2d19dd 3316\f
3d2ada2f 3317
44cf1f0f 3318;;; {IOTA functions: generating lists of numbers}
3d2ada2f 3319;;;
0f2d19dd 3320
e69cd299
MD
3321(define (iota n)
3322 (let loop ((count (1- n)) (result '()))
3323 (if (< count 0) result
3324 (loop (1- count) (cons count result)))))
0f2d19dd
JB
3325
3326\f
3d2ada2f 3327
773abfbb
KR
3328;;; {While}
3329;;;
3330;;; with `continue' and `break'.
3331;;;
3332
10e69149
AW
3333;; The inliner will remove the prompts at compile-time if it finds that
3334;; `continue' or `break' are not used.
3335;;
3336(define-syntax while
3337 (lambda (x)
3338 (syntax-case x ()
3339 ((while cond body ...)
3340 #`(let ((break-tag (make-prompt-tag "break"))
3341 (continue-tag (make-prompt-tag "continue")))
3342 (call-with-prompt
3343 break-tag
3344 (lambda ()
3345 (define-syntax #,(datum->syntax #'while 'break)
3346 (lambda (x)
3347 (syntax-case x ()
91956a94
AW
3348 ((_ arg (... ...))
3349 #'(abort-to-prompt break-tag arg (... ...)))
10e69149 3350 (_
91956a94
AW
3351 #'(lambda args
3352 (apply abort-to-prompt break-tag args))))))
10e69149
AW
3353 (let lp ()
3354 (call-with-prompt
3355 continue-tag
3356 (lambda ()
3357 (define-syntax #,(datum->syntax #'while 'continue)
3358 (lambda (x)
3359 (syntax-case x ()
3360 ((_)
3361 #'(abort-to-prompt continue-tag))
3362 ((_ . args)
3363 (syntax-violation 'continue "too many arguments" x))
3364 (_
ddf134cf
MW
3365 #'(lambda ()
3366 (abort-to-prompt continue-tag))))))
91956a94 3367 (do () ((not cond) #f) body ...))
10e69149 3368 (lambda (k) (lp)))))
91956a94
AW
3369 (lambda (k . args)
3370 (if (null? args)
3371 #t
3372 (apply values args)))))))))
5578a53f 3373
773abfbb 3374
0f2d19dd 3375\f
3d2ada2f 3376
0f2d19dd
JB
3377;;; {Module System Macros}
3378;;;
3379
532cf805
MV
3380;; Return a list of expressions that evaluate to the appropriate
3381;; arguments for resolve-interface according to SPEC.
3382
1fdd5bec
AW
3383(eval-when (compile)
3384 (if (memq 'prefix (read-options))
3385 (error "boot-9 must be compiled with #:kw, not :kw")))
1a1a10d3 3386
532cf805
MV
3387(define (keyword-like-symbol->keyword sym)
3388 (symbol->keyword (string->symbol (substring (symbol->string sym) 1))))
3389
074e036e
AW
3390(define-syntax define-module
3391 (lambda (x)
3392 (define (keyword-like? stx)
3393 (let ((dat (syntax->datum stx)))
3394 (and (symbol? dat)
3395 (eqv? (string-ref (symbol->string dat) 0) #\:))))
3396 (define (->keyword sym)
3397 (symbol->keyword (string->symbol (substring (symbol->string sym) 1))))
3398
cd8c3519 3399 (define (parse-iface args)
074e036e
AW
3400 (let loop ((in args) (out '()))
3401 (syntax-case in ()
3402 (() (reverse! out))
3403 ;; The user wanted #:foo, but wrote :foo. Fix it.
3404 ((sym . in) (keyword-like? #'sym)
3405 (loop #`(#,(->keyword (syntax->datum #'sym)) . in) out))
3406 ((kw . in) (not (keyword? (syntax->datum #'kw)))
3407 (syntax-violation 'define-module "expected keyword arg" x #'kw))
3408 ((#:renamer renamer . in)
cd8c3519 3409 (loop #'in (cons* #',renamer #:renamer out)))
074e036e 3410 ((kw val . in)
cd8c3519 3411 (loop #'in (cons* #'val #'kw out))))))
074e036e 3412
cd8c3519 3413 (define (parse args imp exp rex rep aut)
074e036e
AW
3414 ;; Just quote everything except #:use-module and #:use-syntax. We
3415 ;; need to know about all arguments regardless since we want to turn
3416 ;; symbols that look like keywords into real keywords, and the
3417 ;; keyword args in a define-module form are not regular
3418 ;; (i.e. no-backtrace doesn't take a value).
cd8c3519
AW
3419 (syntax-case args ()
3420 (()
3421 (let ((imp (if (null? imp) '() #`(#:imports `#,imp)))
3422 (exp (if (null? exp) '() #`(#:exports '#,exp)))
3423 (rex (if (null? rex) '() #`(#:re-exports '#,rex)))
3424 (rep (if (null? rep) '() #`(#:replacements '#,rep)))
3425 (aut (if (null? aut) '() #`(#:autoloads '#,aut))))
3426 #`(#,@imp #,@exp #,@rex #,@rep #,@aut)))
3427 ;; The user wanted #:foo, but wrote :foo. Fix it.
3428 ((sym . args) (keyword-like? #'sym)
3429 (parse #`(#,(->keyword (syntax->datum #'sym)) . args)
3430 imp exp rex rep aut))
3431 ((kw . args) (not (keyword? (syntax->datum #'kw)))
3432 (syntax-violation 'define-module "expected keyword arg" x #'kw))
3433 ((#:no-backtrace . args)
3434 ;; Ignore this one.
3435 (parse #'args imp exp rex rep aut))
3436 ((#:pure . args)
3437 #`(#:pure #t . #,(parse #'args imp exp rex rep aut)))
3438 ((kw)
3439 (syntax-violation 'define-module "keyword arg without value" x #'kw))
3440 ((#:version (v ...) . args)
3441 #`(#:version '(v ...) . #,(parse #'args imp exp rex rep aut)))
3442 ((#:duplicates (d ...) . args)
3443 #`(#:duplicates '(d ...) . #,(parse #'args imp exp rex rep aut)))
3444 ((#:filename f . args)
3445 #`(#:filename 'f . #,(parse #'args imp exp rex rep aut)))
3446 ((#:use-module (name name* ...) . args)
3447 (and (and-map symbol? (syntax->datum #'(name name* ...))))
ad4bd7c2 3448 (parse #'args #`(#,@imp ((name name* ...))) exp rex rep aut))
cd8c3519
AW
3449 ((#:use-syntax (name name* ...) . args)
3450 (and (and-map symbol? (syntax->datum #'(name name* ...))))
3451 #`(#:transformer '(name name* ...)
ad4bd7c2 3452 . #,(parse #'args #`(#,@imp ((name name* ...))) exp rex rep aut)))
cd8c3519
AW
3453 ((#:use-module ((name name* ...) arg ...) . args)
3454 (and (and-map symbol? (syntax->datum #'(name name* ...))))
3455 (parse #'args
ad4bd7c2 3456 #`(#,@imp ((name name* ...) #,@(parse-iface #'(arg ...))))
cd8c3519
AW
3457 exp rex rep aut))
3458 ((#:export (ex ...) . args)
3459 (parse #'args imp #`(#,@exp ex ...) rex rep aut))
3460 ((#:export-syntax (ex ...) . args)
3461 (parse #'args imp #`(#,@exp ex ...) rex rep aut))
3462 ((#:re-export (re ...) . args)
3463 (parse #'args imp exp #`(#,@rex re ...) rep aut))
3464 ((#:re-export-syntax (re ...) . args)
3465 (parse #'args imp exp #`(#,@rex re ...) rep aut))
3466 ((#:replace (r ...) . args)
3467 (parse #'args imp exp rex #`(#,@rep r ...) aut))
3468 ((#:replace-syntax (r ...) . args)
3469 (parse #'args imp exp rex #`(#,@rep r ...) aut))
3470 ((#:autoload name bindings . args)
3471 (parse #'args imp exp rex rep #`(#,@aut name bindings)))
3472 ((kw val . args)
3473 (syntax-violation 'define-module "unknown keyword or bad argument"
3474 #'kw #'val))))
074e036e
AW
3475
3476 (syntax-case x ()
3477 ((_ (name name* ...) arg ...)
cd8c3519
AW
3478 (and-map symbol? (syntax->datum #'(name name* ...)))
3479 (with-syntax (((quoted-arg ...)
3480 (parse #'(arg ...) '() '() '() '() '()))
c415fe08
AW
3481 ;; Ideally the filename is either a string or #f;
3482 ;; this hack is to work around a case in which
3483 ;; port-filename returns a symbol (`socket') for
3484 ;; sockets.
3485 (filename (let ((f (assq-ref (or (syntax-source x) '())
3486 'filename)))
3487 (and (string? f) f))))
d9b1c71a 3488 #'(eval-when (eval load compile expand)
cd8c3519
AW
3489 (let ((m (define-module* '(name name* ...)
3490 #:filename filename quoted-arg ...)))
074e036e
AW
3491 (set-current-module m)
3492 m)))))))
0f2d19dd 3493
532cf805
MV
3494;; The guts of the use-modules macro. Add the interfaces of the named
3495;; modules to the use-list of the current module, in order.
3496
482a28f9
MV
3497;; This function is called by "modules.c". If you change it, be sure
3498;; to change scm_c_use_module as well.
3499
532cf805 3500(define (process-use-modules module-interface-args)
d57da08b 3501 (let ((interfaces (map (lambda (mif-args)
9b5a0d84
AW
3502 (or (apply resolve-interface mif-args)
3503 (error "no such module" mif-args)))
3504 module-interface-args)))
d57da08b
MD
3505 (call-with-deferred-observers
3506 (lambda ()
3507 (module-use-interfaces! (current-module) interfaces)))))
89da9036 3508
4e3328ce
AW
3509(define-syntax use-modules
3510 (lambda (x)
3511 (define (keyword-like? stx)
3512 (let ((dat (syntax->datum stx)))
3513 (and (symbol? dat)
3514 (eqv? (string-ref (symbol->string dat) 0) #\:))))
3515 (define (->keyword sym)
3516 (symbol->keyword (string->symbol (substring (symbol->string sym) 1))))
3517
3518 (define (quotify-iface args)
3519 (let loop ((in args) (out '()))
3520 (syntax-case in ()
3521 (() (reverse! out))
3522 ;; The user wanted #:foo, but wrote :foo. Fix it.
3523 ((sym . in) (keyword-like? #'sym)
3524 (loop #`(#,(->keyword (syntax->datum #'sym)) . in) out))
3525 ((kw . in) (not (keyword? (syntax->datum #'kw)))
3526 (syntax-violation 'define-module "expected keyword arg" x #'kw))
3527 ((#:renamer renamer . in)
3528 (loop #'in (cons* #'renamer #:renamer out)))
3529 ((kw val . in)
3530 (loop #'in (cons* #''val #'kw out))))))
3531
3532 (define (quotify specs)
3533 (let lp ((in specs) (out '()))
3534 (syntax-case in ()
3535 (() (reverse out))
3536 (((name name* ...) . in)
3537 (and-map symbol? (syntax->datum #'(name name* ...)))
3538 (lp #'in (cons #''((name name* ...)) out)))
3539 ((((name name* ...) arg ...) . in)
3540 (and-map symbol? (syntax->datum #'(name name* ...)))
3541 (with-syntax (((quoted-arg ...) (quotify-iface #'(arg ...))))
3542 (lp #'in (cons #`(list '(name name* ...) quoted-arg ...)
3543 out)))))))
3544
3545 (syntax-case x ()
3546 ((_ spec ...)
3547 (with-syntax (((quoted-args ...) (quotify #'(spec ...))))
520caaeb 3548 #'(eval-when (eval load compile expand)
4e3328ce
AW
3549 (process-use-modules (list quoted-args ...))
3550 *unspecified*))))))
3551
b1e4c7cc
JG
3552(include-from-path "ice-9/r6rs-libraries")
3553
0c65f52c
AW
3554(define-syntax-rule (define-private foo bar)
3555 (define foo bar))
13182603
AW
3556
3557(define-syntax define-public
3558 (syntax-rules ()
3559 ((_ (name . args) . body)
3560 (define-public name (lambda args . body)))
3561 ((_ name val)
3562 (begin
3563 (define name val)
3564 (export name)))))
3565
0c65f52c
AW
3566(define-syntax-rule (defmacro-public name args body ...)
3567 (begin
3568 (defmacro name args body ...)
3569 (export-syntax name)))
0f2d19dd 3570
87e00370 3571;; And now for the most important macro.
0c65f52c
AW
3572(define-syntax-rule (λ formals body ...)
3573 (lambda formals body ...))
87e00370
LC
3574
3575\f
89d06712 3576;; Export a local variable
482a28f9
MV
3577
3578;; This function is called from "modules.c". If you change it, be
3579;; sure to update "modules.c" as well.
3580
90847923
MD
3581(define (module-export! m names)
3582 (let ((public-i (module-public-interface m)))
3583 (for-each (lambda (name)
78c22f5e
JG
3584 (let* ((internal-name (if (pair? name) (car name) name))
3585 (external-name (if (pair? name) (cdr name) name))
3586 (var (module-ensure-local-variable! m internal-name)))
3587 (module-add! public-i external-name var)))
9b5a0d84 3588 names)))
89d06712 3589
f595ccfe
MD
3590(define (module-replace! m names)
3591 (let ((public-i (module-public-interface m)))
3592 (for-each (lambda (name)
78c22f5e
JG
3593 (let* ((internal-name (if (pair? name) (car name) name))
3594 (external-name (if (pair? name) (cdr name) name))
3595 (var (module-ensure-local-variable! m internal-name)))
eceee4ef
AW
3596 ;; FIXME: use a bit on variables instead of object
3597 ;; properties.
9b5a0d84 3598 (set-object-property! var 'replace #t)
78c22f5e 3599 (module-add! public-i external-name var)))
9b5a0d84 3600 names)))
f595ccfe 3601
d2b7b761
AW
3602;; Export all local variables from a module
3603;;
3604(define (module-export-all! mod)
3605 (define (fresh-interface!)
3606 (let ((iface (make-module)))
3607 (set-module-name! iface (module-name mod))
e5602ce7 3608 (set-module-version! iface (module-version mod))
d2b7b761
AW
3609 (set-module-kind! iface 'interface)
3610 (set-module-public-interface! mod iface)
3611 iface))
3612 (let ((iface (or (module-public-interface mod)
3613 (fresh-interface!))))
3614 (set-module-obarray! iface (module-obarray mod))))
3615
89d06712
MV
3616;; Re-export a imported variable
3617;;
3618(define (module-re-export! m names)
3619 (let ((public-i (module-public-interface m)))
3620 (for-each (lambda (name)
78c22f5e
JG
3621 (let* ((internal-name (if (pair? name) (car name) name))
3622 (external-name (if (pair? name) (cdr name) name))
3623 (var (module-variable m internal-name)))
9b5a0d84 3624 (cond ((not var)
78c22f5e
JG
3625 (error "Undefined variable:" internal-name))
3626 ((eq? var (module-local-variable m internal-name))
3627 (error "re-exporting local variable:" internal-name))
9b5a0d84 3628 (else
78c22f5e 3629 (module-add! public-i external-name var)))))
9b5a0d84 3630 names)))
90847923 3631
0c65f52c
AW
3632(define-syntax-rule (export name ...)
3633 (eval-when (eval load compile expand)
3634 (call-with-deferred-observers
3635 (lambda ()
3636 (module-export! (current-module) '(name ...))))))
a0cc0a01 3637
0c65f52c
AW
3638(define-syntax-rule (re-export name ...)
3639 (eval-when (eval load compile expand)
3640 (call-with-deferred-observers
3641 (lambda ()
3642 (module-re-export! (current-module) '(name ...))))))
89d06712 3643
0c65f52c
AW
3644(define-syntax-rule (export! name ...)
3645 (eval-when (eval load compile expand)
3646 (call-with-deferred-observers
3647 (lambda ()
3648 (module-replace! (current-module) '(name ...))))))
1052739b 3649
0c65f52c
AW
3650(define-syntax-rule (export-syntax name ...)
3651 (export name ...))
a0cc0a01 3652
0c65f52c
AW
3653(define-syntax-rule (re-export-syntax name ...)
3654 (re-export name ...))
a0cc0a01 3655
3de80ed5
AW
3656\f
3657
f595ccfe
MD
3658;;; {Parameters}
3659;;;
3660
e9729cbb 3661(define* (make-mutable-parameter init #:optional (converter identity))
9447207f 3662 (let ((fluid (make-fluid (converter init))))
e9729cbb
AW
3663 (case-lambda
3664 (() (fluid-ref fluid))
3665 ((val) (fluid-set! fluid (converter val))))))
3666
f595ccfe
MD
3667
3668\f
3d2ada2f 3669
7b07e5ef
MD
3670;;; {Handling of duplicate imported bindings}
3671;;;
3672
3673;; Duplicate handlers take the following arguments:
3674;;
3675;; module importing module
9b5a0d84
AW
3676;; name conflicting name
3677;; int1 old interface where name occurs
3678;; val1 value of binding in old interface
3679;; int2 new interface where name occurs
3680;; val2 value of binding in new interface
3681;; var previous resolution or #f
3682;; val value of previous resolution
7b07e5ef
MD
3683;;
3684;; A duplicate handler can take three alternative actions:
3685;;
3686;; 1. return #f => leave responsibility to next handler
3687;; 2. exit with an error
3688;; 3. return a variable resolving the conflict
3689;;
3690
3691(define duplicate-handlers
3692 (let ((m (make-module 7)))
f595ccfe
MD
3693
3694 (define (check module name int1 val1 int2 val2 var val)
3695 (scm-error 'misc-error
9b5a0d84
AW
3696 #f
3697 "~A: `~A' imported from both ~A and ~A"
3698 (list (module-name module)
3699 name
3700 (module-name int1)
3701 (module-name int2))
3702 #f))
f595ccfe 3703
65bed4aa 3704 (define (warn module name int1 val1 int2 val2 var val)
2c27dd57 3705 (format (current-warning-port)
9b5a0d84
AW
3706 "WARNING: ~A: `~A' imported from both ~A and ~A\n"
3707 (module-name module)
3708 name
3709 (module-name int1)
3710 (module-name int2))
65bed4aa 3711 #f)
f595ccfe
MD
3712
3713 (define (replace module name int1 val1 int2 val2 var val)
3714 (let ((old (or (and var (object-property var 'replace) var)
9b5a0d84
AW
3715 (module-variable int1 name)))
3716 (new (module-variable int2 name)))
3717 (if (object-property old 'replace)
3718 (and (or (eq? old new)
3719 (not (object-property new 'replace)))
3720 old)
3721 (and (object-property new 'replace)
3722 new))))
f595ccfe 3723
65bed4aa
MD
3724 (define (warn-override-core module name int1 val1 int2 val2 var val)
3725 (and (eq? int1 the-scm-module)
9b5a0d84 3726 (begin
2c27dd57 3727 (format (current-warning-port)
9b5a0d84
AW
3728 "WARNING: ~A: imported module ~A overrides core binding `~A'\n"
3729 (module-name module)
3730 (module-name int2)
3731 name)
3732 (module-local-variable int2 name))))
f595ccfe 3733
65bed4aa
MD
3734 (define (first module name int1 val1 int2 val2 var val)
3735 (or var (module-local-variable int1 name)))
f595ccfe 3736
65bed4aa
MD
3737 (define (last module name int1 val1 int2 val2 var val)
3738 (module-local-variable int2 name))
f595ccfe 3739
65bed4aa
MD
3740 (define (noop module name int1 val1 int2 val2 var val)
3741 #f)
3742
7b07e5ef
MD
3743 (set-module-name! m 'duplicate-handlers)
3744 (set-module-kind! m 'interface)
f595ccfe
MD
3745 (module-define! m 'check check)
3746 (module-define! m 'warn warn)
3747 (module-define! m 'replace replace)
3748 (module-define! m 'warn-override-core warn-override-core)
3749 (module-define! m 'first first)
3750 (module-define! m 'last last)
65bed4aa
MD
3751 (module-define! m 'merge-generics noop)
3752 (module-define! m 'merge-accessors noop)
7b07e5ef
MD
3753 m))
3754
f595ccfe 3755(define (lookup-duplicates-handlers handler-names)
109c2c9f
MD
3756 (and handler-names
3757 (map (lambda (handler-name)
9b5a0d84
AW
3758 (or (module-symbol-local-binding
3759 duplicate-handlers handler-name #f)
3760 (error "invalid duplicate handler name:"
3761 handler-name)))
3762 (if (list? handler-names)
3763 handler-names
3764 (list handler-names)))))
f595ccfe 3765
70a459e3
MD
3766(define default-duplicate-binding-procedures
3767 (make-mutable-parameter #f))
3768
3769(define default-duplicate-binding-handler
6496a663 3770 (make-mutable-parameter '(replace warn-override-core warn last)
9b5a0d84
AW
3771 (lambda (handler-names)
3772 (default-duplicate-binding-procedures
3773 (lookup-duplicates-handlers handler-names))
3774 handler-names)))
f595ccfe 3775
7b07e5ef 3776\f
7f24bc58 3777
c50775e2
AW
3778;;; {`load'.}
3779;;;
3780;;; Load is tricky when combined with relative paths, compilation, and
b3da54d1 3781;;; the file system. If a path is relative, what is it relative to? The
c50775e2
AW
3782;;; path of the source file at the time it was compiled? The path of
3783;;; the compiled file? What if both or either were installed? And how
3784;;; do you get that information? Tricky, I say.
3785;;;
3786;;; To get around all of this, we're going to do something nasty, and
3787;;; turn `load' into a macro. That way it can know the path of the
3788;;; source file with respect to which it was invoked, so it can resolve
3789;;; relative paths with respect to the original source path.
3790;;;
3791;;; There is an exception, and that is that if the source file was in
3792;;; the load path when it was compiled, instead of looking up against
3793;;; the absolute source location, we load-from-path against the relative
3794;;; source location.
3795;;;
3796
5a79300f
LC
3797(define %auto-compilation-options
3798 ;; Default `compile-file' option when auto-compiling.
f86f748d 3799 '(#:warnings (unbound-variable arity-mismatch format)))
5a79300f 3800
c50775e2 3801(define* (load-in-vicinity dir path #:optional reader)
6934d9e7
AW
3802 (define (canonical->suffix canon)
3803 (cond
3804 ((string-prefix? "/" canon) canon)
3805 ((and (> (string-length canon) 2)
3806 (eqv? (string-ref canon 1) #\:))
3807 ;; Paths like C:... transform to /C...
3808 (string-append "/" (substring canon 0 1) (substring canon 2)))
3809 (else canon)))
3810
c50775e2
AW
3811 ;; Returns the .go file corresponding to `name'. Does not search load
3812 ;; paths, only the fallback path. If the .go file is missing or out of
6f06e8d3 3813 ;; date, and auto-compilation is enabled, will try auto-compilation, just
c50775e2 3814 ;; as primitive-load-path does internally. primitive-load is
6f06e8d3 3815 ;; unaffected. Returns #f if auto-compilation failed or was disabled.
c50775e2
AW
3816 ;;
3817 ;; NB: Unless we need to compile the file, this function should not cause
3818 ;; (system base compile) to be loaded up. For that reason compiled-file-name
3819 ;; partially duplicates functionality from (system base compile).
3820 ;;
3821 (define (compiled-file-name canon-path)
6934d9e7
AW
3822 ;; FIXME: would probably be better just to append SHA1(canon-path)
3823 ;; to the %compile-fallback-path, to avoid deep directory stats.
c50775e2
AW
3824 (and %compile-fallback-path
3825 (string-append
3826 %compile-fallback-path
6934d9e7 3827 (canonical->suffix canon-path)
c50775e2
AW
3828 (cond ((or (null? %load-compiled-extensions)
3829 (string-null? (car %load-compiled-extensions)))
3830 (warn "invalid %load-compiled-extensions"
3831 %load-compiled-extensions)
3832 ".go")
3833 (else (car %load-compiled-extensions))))))
3834
3835 (define (fresh-compiled-file-name name go-path)
3836 (catch #t
3837 (lambda ()
3838 (let* ((scmstat (stat name))
1e56cff2
AW
3839 (gostat (and (not %fresh-auto-compile)
3840 (stat go-path #f))))
c50775e2
AW
3841 (if (and gostat
3842 (or (> (stat:mtime gostat) (stat:mtime scmstat))
3843 (and (= (stat:mtime gostat) (stat:mtime scmstat))
3844 (>= (stat:mtimensec gostat)
3845 (stat:mtimensec scmstat)))))
3846 go-path
3847 (begin
3848 (if gostat
2c27dd57 3849 (format (current-warning-port)
c50775e2
AW
3850 ";;; note: source file ~a\n;;; newer than compiled ~a\n"
3851 name go-path))
3852 (cond
6f06e8d3
AW
3853 (%load-should-auto-compile
3854 (%warn-auto-compilation-enabled)
2c27dd57 3855 (format (current-warning-port) ";;; compiling ~a\n" name)
5a79300f
LC
3856 (let ((cfn
3857 ((module-ref
c50775e2
AW
3858 (resolve-interface '(system base compile))
3859 'compile-file)
3860 name
5a79300f 3861 #:opts %auto-compilation-options
c50775e2 3862 #:env (current-module))))
2c27dd57 3863 (format (current-warning-port) ";;; compiled ~a\n" cfn)
c50775e2
AW
3864 cfn))
3865 (else #f))))))
3866 (lambda (k . args)
2c27dd57 3867 (format (current-warning-port)
669ea4eb
AW
3868 ";;; WARNING: compilation of ~a failed:\n" name)
3869 (for-each (lambda (s)
3870 (if (not (string-null? s))
2c27dd57 3871 (format (current-warning-port) ";;; ~a\n" s)))
669ea4eb
AW
3872 (string-split
3873 (call-with-output-string
3874 (lambda (port) (print-exception port #f k args)))
3875 #\newline))
c50775e2
AW
3876 #f)))
3877
3878 (define (absolute-path? path)
3879 (string-prefix? "/" path))
3880
3881 (define (load-absolute abs-path)
3882 (let ((cfn (let ((canon (false-if-exception (canonicalize-path abs-path))))
3883 (and canon
3884 (let ((go-path (compiled-file-name canon)))
3885 (and go-path
3886 (fresh-compiled-file-name abs-path go-path)))))))
3887 (if cfn
dcada7d8
AW
3888 (begin
3889 (if %load-hook
3890 (%load-hook abs-path))
3891 (load-compiled cfn))
c50775e2
AW
3892 (start-stack 'load-stack
3893 (primitive-load abs-path)))))
3894
3895 (save-module-excursion
3896 (lambda ()
3897 (with-fluids ((current-reader reader)
3898 (%file-port-name-canonicalization 'relative))
3899 (cond
3900 ((or (absolute-path? path))
3901 (load-absolute path))
3902 ((absolute-path? dir)
3903 (load-absolute (in-vicinity dir path)))
3904 (else
3905 (load-from-path (in-vicinity dir path))))))))
3906
3907(define-syntax load
3908 (make-variable-transformer
3909 (lambda (x)
3910 (let* ((src (syntax-source x))
3911 (file (and src (assq-ref src 'filename)))
3912 (dir (and (string? file) (dirname file))))
3913 (syntax-case x ()
3914 ((_ arg ...)
3915 #`(load-in-vicinity #,(or dir #'(getcwd)) arg ...))
3916 (id
3917 (identifier? #'id)
3918 #`(lambda args
3919 (apply load-in-vicinity #,(or dir #'(getcwd)) args))))))))
3920
3921\f
3922
7f24bc58
MG
3923;;; {`cond-expand' for SRFI-0 support.}
3924;;;
3925;;; This syntactic form expands into different commands or
3926;;; definitions, depending on the features provided by the Scheme
3927;;; implementation.
3928;;;
3929;;; Syntax:
3930;;;
3931;;; <cond-expand>
3932;;; --> (cond-expand <cond-expand-clause>+)
3933;;; | (cond-expand <cond-expand-clause>* (else <command-or-definition>))
3934;;; <cond-expand-clause>
3935;;; --> (<feature-requirement> <command-or-definition>*)
3936;;; <feature-requirement>
3937;;; --> <feature-identifier>
3938;;; | (and <feature-requirement>*)
3939;;; | (or <feature-requirement>*)
3940;;; | (not <feature-requirement>)
3941;;; <feature-identifier>
3942;;; --> <a symbol which is the name or alias of a SRFI>
3943;;;
3944;;; Additionally, this implementation provides the
3945;;; <feature-identifier>s `guile' and `r5rs', so that programs can
3946;;; determine the implementation type and the supported standard.
3947;;;
3948;;; Currently, the following feature identifiers are supported:
3949;;;
08b609aa 3950;;; guile r5rs srfi-0 srfi-4 srfi-6 srfi-13 srfi-14 srfi-55 srfi-61
7f24bc58
MG
3951;;;
3952;;; Remember to update the features list when adding more SRFIs.
3d2ada2f 3953;;;
7f24bc58 3954
b9b8f9da 3955(define %cond-expand-features
f41be016 3956 ;; Adjust the above comment when changing this.
018733ff 3957 '(guile
60c8ad9e 3958 guile-2
018733ff
KR
3959 r5rs
3960 srfi-0 ;; cond-expand itself
85acb35f 3961 srfi-4 ;; homogenous numeric vectors
018733ff 3962 srfi-6 ;; open-input-string etc, in the guile core
4a276c08
MV
3963 srfi-13 ;; string library
3964 srfi-14 ;; character sets
9670f238
AW
3965 srfi-23 ;; `error` procedure
3966 srfi-39 ;; parameterize
344d68d5 3967 srfi-55 ;; require-extension
08b609aa 3968 srfi-61 ;; general cond clause
018733ff 3969 ))
1d00af09 3970
b9b8f9da
MG
3971;; This table maps module public interfaces to the list of features.
3972;;
3973(define %cond-expand-table (make-hash-table 31))
3974
3975;; Add one or more features to the `cond-expand' feature list of the
3976;; module `module'.
3977;;
3978(define (cond-expand-provide module features)
3979 (let ((mod (module-public-interface module)))
3980 (and mod
9b5a0d84
AW
3981 (hashq-set! %cond-expand-table mod
3982 (append (hashq-ref %cond-expand-table mod '())
3983 features)))))
b9b8f9da 3984
1fdd5bec
AW
3985(define-syntax cond-expand
3986 (lambda (x)
3987 (define (module-has-feature? mod sym)
3988 (or-map (lambda (mod)
3989 (memq sym (hashq-ref %cond-expand-table mod '())))
3990 (module-uses mod)))
3991
3992 (define (condition-matches? condition)
3993 (syntax-case condition (and or not)
3994 ((and c ...)
3995 (and-map condition-matches? #'(c ...)))
3996 ((or c ...)
3997 (or-map condition-matches? #'(c ...)))
3998 ((not c)
3999 (if (condition-matches? #'c) #f #t))
4000 (c
4001 (identifier? #'c)
4002 (let ((sym (syntax->datum #'c)))
4003 (if (memq sym %cond-expand-features)
4004 #t
4005 (module-has-feature? (current-module) sym))))))
4006
4007 (define (match clauses alternate)
4008 (syntax-case clauses ()
4009 (((condition form ...) . rest)
4010 (if (condition-matches? #'condition)
4011 #'(begin form ...)
4012 (match #'rest alternate)))
4013 (() (alternate))))
4014
4015 (syntax-case x (else)
4016 ((_ clause ... (else form ...))
4017 (match #'(clause ...)
4018 (lambda ()
4019 #'(begin form ...))))
4020 ((_ clause ...)
4021 (match #'(clause ...)
4022 (lambda ()
4023 (syntax-violation 'cond-expand "unfulfilled cond-expand" x)))))))
0f2d19dd 4024
f41be016
MG
4025;; This procedure gets called from the startup code with a list of
4026;; numbers, which are the numbers of the SRFIs to be loaded on startup.
4027;;
4028(define (use-srfis srfis)
9a18d8d4
KR
4029 (process-use-modules
4030 (map (lambda (num)
9b5a0d84
AW
4031 (list (list 'srfi (string->symbol
4032 (string-append "srfi-" (number->string num))))))
4033 srfis)))
f8a502cb 4034
0f2d19dd 4035\f
9d774814 4036
344d68d5
RB
4037;;; srfi-55: require-extension
4038;;;
4039
6669cd81
AW
4040(define-syntax require-extension
4041 (lambda (x)
4042 (syntax-case x (srfi)
4043 ((_ (srfi n ...))
4044 (and-map integer? (syntax->datum #'(n ...)))
4045 (with-syntax
4046 (((srfi-n ...)
4047 (map (lambda (n)
4048 (datum->syntax x (symbol-append 'srfi- n)))
4049 (map string->symbol
4050 (map number->string (syntax->datum #'(n ...)))))))
4051 #'(use-modules (srfi srfi-n) ...)))
4052 ((_ (type arg ...))
4053 (identifier? #'type)
4054 (syntax-violation 'require-extension "Not a recognized extension type"
4055 x)))))
344d68d5
RB
4056
4057\f
165b10dd
AR
4058;;; Defining transparently inlinable procedures
4059;;;
4060
4061(define-syntax define-inlinable
4062 ;; Define a macro and a procedure such that direct calls are inlined, via
4063 ;; the macro expansion, whereas references in non-call contexts refer to
4064 ;; the procedure. Inspired by the `define-integrable' macro by Dybvig et al.
4065 (lambda (x)
4066 ;; Use a space in the prefix to avoid potential -Wunused-toplevel
4067 ;; warning
4068 (define prefix (string->symbol "% "))
4069 (define (make-procedure-name name)
4070 (datum->syntax name
4071 (symbol-append prefix (syntax->datum name)
4072 '-procedure)))
4073
4074 (syntax-case x ()
4075 ((_ (name formals ...) body ...)
4076 (identifier? #'name)
4077 (with-syntax ((proc-name (make-procedure-name #'name))
4078 ((args ...) (generate-temporaries #'(formals ...))))
4079 #`(begin
4080 (define (proc-name formals ...)
ea3ca4e4 4081 (syntax-parameterize ((name (identifier-syntax proc-name)))
2844ab85 4082 body ...))
ea3ca4e4 4083 (define-syntax-parameter name
165b10dd
AR
4084 (lambda (x)
4085 (syntax-case x ()
4086 ((_ args ...)
ea3ca4e4 4087 #'((syntax-parameterize ((name (identifier-syntax proc-name)))
2844ab85
AW
4088 (lambda (formals ...)
4089 body ...))
165b10dd
AR
4090 args ...))
4091 (_
4092 (identifier? x)
4093 #'proc-name))))))))))
4094
4095\f
344d68d5 4096
755457ec
MD
4097(define using-readline?
4098 (let ((using-readline? (make-fluid)))
4099 (make-procedure-with-setter
4100 (lambda () (fluid-ref using-readline?))
4101 (lambda (v) (fluid-set! using-readline? v)))))
4102
4d31f0da 4103\f
3d2ada2f
DH
4104
4105;;; {Deprecated stuff}
4106;;;
4107
3d2ada2f 4108(begin-deprecated
0ea72faa 4109 (module-use! the-scm-module (resolve-interface '(ice-9 deprecated))))
3d2ada2f
DH
4110
4111\f
4112
68fcf711
AW
4113;;; SRFI-4 in the default environment. FIXME: we should figure out how
4114;;; to deprecate this.
3d2ada2f 4115;;;
6eb396fe 4116
a2689737
AW
4117;; FIXME:
4118(module-use! the-scm-module (resolve-interface '(srfi srfi-4)))
4119
68fcf711
AW
4120\f
4121
4122;;; A few identifiers that need to be defined in this file are really
4123;;; internal implementation details. We shove them off into internal
4124;;; modules, removing them from the (guile) module.
4125;;;
4126
4127(define-module (system syntax))
4128
4129(let ()
4130 (define (steal-bindings! from to ids)
4131 (for-each
4132 (lambda (sym)
4133 (let ((v (module-local-variable from sym)))
4134 (module-remove! from sym)
4135 (module-add! to sym v)))
4136 ids)
4137 (module-export! to ids))
4138
4139 (steal-bindings! the-root-module (resolve-module '(system syntax))
4140 '(syntax-local-binding
4141 syntax-module
f9685f43
AW
4142 syntax-locally-bound-identifiers
4143 syntax-session-id)))
68fcf711
AW
4144
4145
4146\f
4147
4148;;; Place the user in the guile-user module.
4149;;;
4150
7cf64a0a 4151;; Set filename to #f to prevent reload.
68623e8e 4152(define-module (guile-user)
7cf64a0a
AW
4153 #:autoload (system base compile) (compile compile-file)
4154 #:filename #f)
6d36532c 4155
7385dc12
LC
4156;; Remain in the `(guile)' module at compilation-time so that the
4157;; `-Wunused-toplevel' warning works as expected.
4158(eval-when (compile) (set-current-module the-root-module))
4159
20edfbbd 4160;;; boot-9.scm ends here