0.8.10.13:
[sbcl.git] / src / code / early-extensions.lisp
1 ;;;; various extensions (including SB-INT "internal extensions")
2 ;;;; available both in the cross-compilation host Lisp and in the
3 ;;;; target SBCL
4
5 ;;;; This software is part of the SBCL system. See the README file for
6 ;;;; more information.
7 ;;;;
8 ;;;; This software is derived from the CMU CL system, which was
9 ;;;; written at Carnegie Mellon University and released into the
10 ;;;; public domain. The software is in the public domain and is
11 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
12 ;;;; files for more information.
13
14 (in-package "SB!IMPL")
15
16 ;;; something not EQ to anything we might legitimately READ
17 (defparameter *eof-object* (make-symbol "EOF-OBJECT"))
18
19 ;;; a type used for indexing into arrays, and for related quantities
20 ;;; like lengths of lists
21 ;;;
22 ;;; It's intentionally limited to one less than the
23 ;;; ARRAY-DIMENSION-LIMIT for efficiency reasons, because in SBCL
24 ;;; ARRAY-DIMENSION-LIMIT is MOST-POSITIVE-FIXNUM, and staying below
25 ;;; that lets the system know it can increment a value of this type
26 ;;; without having to worry about using a bignum to represent the
27 ;;; result.
28 ;;;
29 ;;; (It should be safe to use ARRAY-DIMENSION-LIMIT as an exclusive
30 ;;; bound because ANSI specifies it as an exclusive bound.)
31 (def!type index () `(integer 0 (,sb!xc:array-dimension-limit)))
32
33 ;;; like INDEX, but augmented with -1 (useful when using the index
34 ;;; to count downwards to 0, e.g. LOOP FOR I FROM N DOWNTO 0, with
35 ;;; an implementation which terminates the loop by testing for the
36 ;;; index leaving the loop range)
37 (def!type index-or-minus-1 () `(integer -1 (,sb!xc:array-dimension-limit)))
38
39 ;;; A couple of VM-related types that are currently used only on the
40 ;;; alpha platform. -- CSR, 2002-06-24
41 (def!type unsigned-byte-with-a-bite-out (s bite)
42   (cond ((eq s '*) 'integer)
43         ((and (integerp s) (> s 0))
44          (let ((bound (ash 1 s)))
45            `(integer 0 ,(- bound bite 1))))
46         (t
47          (error "Bad size specified for UNSIGNED-BYTE type specifier: ~S." s))))
48
49 ;;; Motivated by the mips port. -- CSR, 2002-08-22
50 (def!type signed-byte-with-a-bite-out (s bite)
51   (cond ((eq s '*) 'integer)
52         ((and (integerp s) (> s 1))
53          (let ((bound (ash 1 (1- s))))
54            `(integer ,(- bound) ,(- bound bite 1))))
55         (t
56          (error "Bad size specified for SIGNED-BYTE type specifier: ~S." s))))
57
58 (def!type load/store-index (scale lowtag min-offset
59                                  &optional (max-offset min-offset))
60   `(integer ,(- (truncate (+ (ash 1 16)
61                              (* min-offset sb!vm:n-word-bytes)
62                              (- lowtag))
63                           scale))
64             ,(truncate (- (+ (1- (ash 1 16)) lowtag)
65                           (* max-offset sb!vm:n-word-bytes))
66                        scale)))
67
68 ;;; Similar to FUNCTION, but the result type is "exactly" specified:
69 ;;; if it is an object type, then the function returns exactly one
70 ;;; value, if it is a short form of VALUES, then this short form
71 ;;; specifies the exact number of values.
72 (def!type sfunction (args &optional result)
73   (let ((result (cond ((eq result '*) '*)
74                       ((or (atom result)
75                            (not (eq (car result) 'values)))
76                        `(values ,result &optional))
77                       ((intersection (cdr result) lambda-list-keywords)
78                        result)
79                       (t `(values ,@(cdr result) &optional)))))
80     `(function ,args ,result)))
81
82 ;;; a type specifier
83 ;;;
84 ;;; FIXME: The SB!KERNEL:INSTANCE here really means CL:CLASS.
85 ;;; However, the CL:CLASS type is only defined once PCL is loaded,
86 ;;; which is before this is evaluated.  Once PCL is moved into cold
87 ;;; init, this might be fixable.
88 (def!type type-specifier () '(or list symbol sb!kernel:instance))
89
90 ;;; the default value used for initializing character data. The ANSI
91 ;;; spec says this is arbitrary, so we use the value that falls
92 ;;; through when we just let the low-level consing code initialize
93 ;;; all newly-allocated memory to zero.
94 ;;;
95 ;;; KLUDGE: It might be nice to use something which is a
96 ;;; STANDARD-CHAR, both to reduce user surprise a little and, probably
97 ;;; more significantly, to help SBCL's cross-compiler (which knows how
98 ;;; to dump STANDARD-CHARs). Unfortunately, the old CMU CL code is
99 ;;; shot through with implicit assumptions that it's #\NULL, and code
100 ;;; in several places (notably both DEFUN MAKE-ARRAY and DEFTRANSFORM
101 ;;; MAKE-ARRAY) would have to be rewritten. -- WHN 2001-10-04
102 (eval-when (:compile-toplevel :load-toplevel :execute)
103   ;; an expression we can use to construct a DEFAULT-INIT-CHAR value
104   ;; at load time (so that we don't need to teach the cross-compiler
105   ;; how to represent and dump non-STANDARD-CHARs like #\NULL)
106   (defparameter *default-init-char-form* '(code-char 0)))
107
108 ;;; CHAR-CODE values for ASCII characters which we care about but
109 ;;; which aren't defined in section "2.1.3 Standard Characters" of the
110 ;;; ANSI specification for Lisp
111 ;;;
112 ;;; KLUDGE: These are typically used in the idiom (CODE-CHAR
113 ;;; FOO-CHAR-CODE). I suspect that the current implementation is
114 ;;; expanding this idiom into a full call to CODE-CHAR, which is an
115 ;;; annoying overhead. I should check whether this is happening, and
116 ;;; if so, perhaps implement a DEFTRANSFORM or something to stop it.
117 ;;; (or just find a nicer way of expressing characters portably?) --
118 ;;; WHN 19990713
119 (def!constant bell-char-code 7)
120 (def!constant backspace-char-code 8)
121 (def!constant tab-char-code 9)
122 (def!constant line-feed-char-code 10)
123 (def!constant form-feed-char-code 12)
124 (def!constant return-char-code 13)
125 (def!constant escape-char-code 27)
126 (def!constant rubout-char-code 127)
127 \f
128 ;;;; type-ish predicates
129
130 ;;; Is X a list containing a cycle?
131 (defun cyclic-list-p (x)
132   (and (listp x)
133        (labels ((safe-cddr (x) (if (listp (cdr x)) (cddr x)))) 
134          (do ((y x (safe-cddr y))
135               (started-p nil t)
136               (z x (cdr z)))
137              ((not (and (consp z) (consp y))) nil)
138            (when (and started-p (eq y z))
139              (return t))))))
140
141 ;;; Is X a (possibly-improper) list of at least N elements?
142 (declaim (ftype (function (t index)) list-of-length-at-least-p))
143 (defun list-of-length-at-least-p (x n)
144   (or (zerop n) ; since anything can be considered an improper list of length 0
145       (and (consp x)
146            (list-of-length-at-least-p (cdr x) (1- n)))))
147
148 (declaim (inline singleton-p))
149 (defun singleton-p (list)
150   (and (consp list)
151        (null (rest list))))
152
153 ;;; Is X is a positive prime integer? 
154 (defun positive-primep (x)
155   ;; This happens to be called only from one place in sbcl-0.7.0, and
156   ;; only for fixnums, we can limit it to fixnums for efficiency. (And
157   ;; if we didn't limit it to fixnums, we should use a cleverer
158   ;; algorithm, since this one scales pretty badly for huge X.)
159   (declare (fixnum x))
160   (if (<= x 5)
161       (and (>= x 2) (/= x 4))
162       (and (not (evenp x))
163            (not (zerop (rem x 3)))
164            (do ((q 6)
165                 (r 1)
166                 (inc 2 (logxor inc 6)) ;; 2,4,2,4...
167                 (d 5 (+ d inc)))
168                ((or (= r 0) (> d q)) (/= r 0))
169              (declare (fixnum inc))
170              (multiple-value-setq (q r) (truncate x d))))))
171
172 ;;; Could this object contain other objects? (This is important to
173 ;;; the implementation of things like *PRINT-CIRCLE* and the dumper.)
174 (defun compound-object-p (x)
175   (or (consp x)
176       (typep x 'instance)
177       (typep x '(array t *))))
178 \f
179 ;;;; the COLLECT macro
180 ;;;;
181 ;;;; comment from CMU CL: "the ultimate collection macro..."
182
183 ;;; helper functions for COLLECT, which become the expanders of the
184 ;;; MACROLET definitions created by COLLECT
185 ;;;
186 ;;; COLLECT-NORMAL-EXPANDER handles normal collection macros.
187 ;;;
188 ;;; COLLECT-LIST-EXPANDER handles the list collection case. N-TAIL
189 ;;; is the pointer to the current tail of the list, or NIL if the list
190 ;;; is empty.
191 (eval-when (#-sb-xc :compile-toplevel :load-toplevel :execute)
192   (defun collect-normal-expander (n-value fun forms)
193     `(progn
194        ,@(mapcar (lambda (form) `(setq ,n-value (,fun ,form ,n-value))) forms)
195        ,n-value))
196   (defun collect-list-expander (n-value n-tail forms)
197     (let ((n-res (gensym)))
198       `(progn
199          ,@(mapcar (lambda (form)
200                      `(let ((,n-res (cons ,form nil)))
201                         (cond (,n-tail
202                                (setf (cdr ,n-tail) ,n-res)
203                                (setq ,n-tail ,n-res))
204                               (t
205                                (setq ,n-tail ,n-res  ,n-value ,n-res)))))
206                    forms)
207          ,n-value))))
208
209 ;;; Collect some values somehow. Each of the collections specifies a
210 ;;; bunch of things which collected during the evaluation of the body
211 ;;; of the form. The name of the collection is used to define a local
212 ;;; macro, a la MACROLET. Within the body, this macro will evaluate
213 ;;; each of its arguments and collect the result, returning the
214 ;;; current value after the collection is done. The body is evaluated
215 ;;; as a PROGN; to get the final values when you are done, just call
216 ;;; the collection macro with no arguments.
217 ;;;
218 ;;; INITIAL-VALUE is the value that the collection starts out with,
219 ;;; which defaults to NIL. FUNCTION is the function which does the
220 ;;; collection. It is a function which will accept two arguments: the
221 ;;; value to be collected and the current collection. The result of
222 ;;; the function is made the new value for the collection. As a
223 ;;; totally magical special-case, FUNCTION may be COLLECT, which tells
224 ;;; us to build a list in forward order; this is the default. If an
225 ;;; INITIAL-VALUE is supplied for COLLECT, the stuff will be RPLACD'd
226 ;;; onto the end. Note that FUNCTION may be anything that can appear
227 ;;; in the functional position, including macros and lambdas.
228 (defmacro collect (collections &body body)
229   (let ((macros ())
230         (binds ()))
231     (dolist (spec collections)
232       (unless (proper-list-of-length-p spec 1 3)
233         (error "malformed collection specifier: ~S" spec))
234       (let* ((name (first spec))
235              (default (second spec))
236              (kind (or (third spec) 'collect))
237              (n-value (gensym (concatenate 'string
238                                            (symbol-name name)
239                                            "-N-VALUE-"))))
240         (push `(,n-value ,default) binds)
241         (if (eq kind 'collect)
242           (let ((n-tail (gensym (concatenate 'string
243                                              (symbol-name name)
244                                              "-N-TAIL-"))))
245             (if default
246               (push `(,n-tail (last ,n-value)) binds)
247               (push n-tail binds))
248             (push `(,name (&rest args)
249                      (collect-list-expander ',n-value ',n-tail args))
250                   macros))
251           (push `(,name (&rest args)
252                    (collect-normal-expander ',n-value ',kind args))
253                 macros))))
254     `(macrolet ,macros (let* ,(nreverse binds) ,@body))))
255 \f
256 ;;;; some old-fashioned functions. (They're not just for old-fashioned
257 ;;;; code, they're also used as optimized forms of the corresponding
258 ;;;; general functions when the compiler can prove that they're
259 ;;;; equivalent.)
260
261 ;;; like (MEMBER ITEM LIST :TEST #'EQ)
262 (defun memq (item list)
263   #!+sb-doc
264   "Return tail of LIST beginning with first element EQ to ITEM."
265   ;; KLUDGE: These could be and probably should be defined as
266   ;;   (MEMBER ITEM LIST :TEST #'EQ)),
267   ;; but when I try to cross-compile that, I get an error from
268   ;; LTN-ANALYZE-KNOWN-CALL, "Recursive known function definition". The
269   ;; comments for that error say it "is probably a botched interpreter stub".
270   ;; Rather than try to figure that out, I just rewrote this function from
271   ;; scratch. -- WHN 19990512
272   (do ((i list (cdr i)))
273       ((null i))
274     (when (eq (car i) item)
275       (return i))))
276
277 ;;; like (ASSOC ITEM ALIST :TEST #'EQ):
278 ;;;   Return the first pair of ALIST where ITEM is EQ to the key of
279 ;;;   the pair.
280 (defun assq (item alist)
281   ;; KLUDGE: CMU CL defined this with
282   ;;   (DECLARE (INLINE ASSOC))
283   ;;   (ASSOC ITEM ALIST :TEST #'EQ))
284   ;; which is pretty, but which would have required adding awkward
285   ;; build order constraints on SBCL (or figuring out some way to make
286   ;; inline definitions installable at build-the-cross-compiler time,
287   ;; which was too ambitious for now). Rather than mess with that, we
288   ;; just define ASSQ explicitly in terms of more primitive
289   ;; operations:
290   (dolist (pair alist)
291     ;; though it may look more natural to write this as 
292     ;;   (AND PAIR (EQ (CAR PAIR) ITEM))
293     ;; the temptation to do so should be resisted, as pointed out by PFD
294     ;; sbcl-devel 2003-08-16, as NIL elements are rare in association
295     ;; lists.  -- CSR, 2003-08-16
296     (when (and (eq (car pair) item) (not (null pair)))
297       (return pair))))
298
299 ;;; like (DELETE .. :TEST #'EQ):
300 ;;;   Delete all LIST entries EQ to ITEM (destructively modifying
301 ;;;   LIST), and return the modified LIST.
302 (defun delq (item list)
303   (let ((list list))
304     (do ((x list (cdr x))
305          (splice '()))
306         ((endp x) list)
307       (cond ((eq item (car x))
308              (if (null splice)
309                (setq list (cdr x))
310                (rplacd splice (cdr x))))
311             (t (setq splice x)))))) ; Move splice along to include element.
312
313
314 ;;; like (POSITION .. :TEST #'EQ):
315 ;;;   Return the position of the first element EQ to ITEM.
316 (defun posq (item list)
317   (do ((i list (cdr i))
318        (j 0 (1+ j)))
319       ((null i))
320     (when (eq (car i) item)
321       (return j))))
322
323 (declaim (inline neq))
324 (defun neq (x y)
325   (not (eq x y)))
326
327 ;;; not really an old-fashioned function, but what the calling
328 ;;; convention should've been: like NTH, but with the same argument
329 ;;; order as in all the other dereferencing functions, with the
330 ;;; collection first and the index second
331 (declaim (inline nth-but-with-sane-arg-order))
332 (declaim (ftype (function (list index) t) nth-but-with-sane-arg-order))
333 (defun nth-but-with-sane-arg-order (list index)
334   (nth index list))
335
336 (defun adjust-list (list length initial-element)
337   (let ((old-length (length list)))
338     (cond ((< old-length length)
339            (append list (make-list (- length old-length)
340                                    :initial-element initial-element)))
341           ((> old-length length)
342            (subseq list 0 length))
343           (t list))))
344 \f
345 ;;;; miscellaneous iteration extensions
346
347 ;;; "the ultimate iteration macro"
348 ;;;
349 ;;; note for Schemers: This seems to be identical to Scheme's "named LET".
350 (defmacro named-let (name binds &body body)
351   #!+sb-doc
352   (dolist (x binds)
353     (unless (proper-list-of-length-p x 2)
354       (error "malformed NAMED-LET variable spec: ~S" x)))
355   `(labels ((,name ,(mapcar #'first binds) ,@body))
356      (,name ,@(mapcar #'second binds))))
357
358 ;;; just like DOLIST, but with one-dimensional arrays
359 (defmacro dovector ((elt vector &optional result) &rest forms)
360   (let ((index (gensym))
361         (length (gensym))
362         (vec (gensym)))
363     `(let ((,vec ,vector))
364        (declare (type vector ,vec))
365        (do ((,index 0 (1+ ,index))
366             (,length (length ,vec)))
367            ((>= ,index ,length) ,result)
368          (let ((,elt (aref ,vec ,index)))
369            ,@forms)))))
370
371 ;;; Iterate over the entries in a HASH-TABLE.
372 (defmacro dohash ((key-var value-var table &optional result) &body body)
373   (multiple-value-bind (forms decls) (parse-body body :doc-string-allowed nil)
374     (let ((gen (gensym))
375           (n-more (gensym)))
376       `(with-hash-table-iterator (,gen ,table)
377          (loop
378           (multiple-value-bind (,n-more ,key-var ,value-var) (,gen)
379             ,@decls
380             (unless ,n-more (return ,result))
381             ,@forms))))))
382 \f
383 ;;;; hash cache utility
384
385 (eval-when (:compile-toplevel :load-toplevel :execute)
386   (defvar *profile-hash-cache* nil))
387
388 ;;; a flag for whether it's too early in cold init to use caches so
389 ;;; that we have a better chance of recovering so that we have a
390 ;;; better chance of getting the system running so that we have a
391 ;;; better chance of diagnosing the problem which caused us to use the
392 ;;; caches too early
393 #!+sb-show
394 (defvar *hash-caches-initialized-p*)
395
396 ;;; Define a hash cache that associates some number of argument values
397 ;;; with a result value. The TEST-FUNCTION paired with each ARG-NAME
398 ;;; is used to compare the value for that arg in a cache entry with a
399 ;;; supplied arg. The TEST-FUNCTION must not error when passed NIL as
400 ;;; its first arg, but need not return any particular value.
401 ;;; TEST-FUNCTION may be any thing that can be placed in CAR position.
402 ;;;
403 ;;; NAME is used to define these functions:
404 ;;; <name>-CACHE-LOOKUP Arg*
405 ;;;   See whether there is an entry for the specified ARGs in the
406 ;;;   cache. If not present, the :DEFAULT keyword (default NIL)
407 ;;;   determines the result(s).
408 ;;; <name>-CACHE-ENTER Arg* Value*
409 ;;;   Encache the association of the specified args with VALUE.
410 ;;; <name>-CACHE-CLEAR
411 ;;;   Reinitialize the cache, invalidating all entries and allowing
412 ;;;   the arguments and result values to be GC'd.
413 ;;;
414 ;;; These other keywords are defined:
415 ;;; :HASH-BITS <n>
416 ;;;   The size of the cache as a power of 2.
417 ;;; :HASH-FUNCTION function
418 ;;;   Some thing that can be placed in CAR position which will compute
419 ;;;   a value between 0 and (1- (expt 2 <hash-bits>)).
420 ;;; :VALUES <n>
421 ;;;   the number of return values cached for each function call
422 ;;; :INIT-WRAPPER <name>
423 ;;;   The code for initializing the cache is wrapped in a form with
424 ;;;   the specified name. (:INIT-WRAPPER is set to COLD-INIT-FORMS
425 ;;;   in type system definitions so that caches will be created
426 ;;;   before top level forms run.)
427 (defmacro define-hash-cache (name args &key hash-function hash-bits default
428                                   (init-wrapper 'progn)
429                                   (values 1))
430   (let* ((var-name (symbolicate "*" name "-CACHE-VECTOR*"))
431          (nargs (length args))
432          (entry-size (+ nargs values))
433          (size (ash 1 hash-bits))
434          (total-size (* entry-size size))
435          (default-values (if (and (consp default) (eq (car default) 'values))
436                              (cdr default)
437                              (list default)))
438          (n-index (gensym))
439          (n-cache (gensym)))
440
441     (unless (= (length default-values) values)
442       (error "The number of default values ~S differs from :VALUES ~W."
443              default values))
444
445     (collect ((inlines)
446               (forms)
447               (inits)
448               (tests)
449               (sets)
450               (arg-vars)
451               (values-indices)
452               (values-names))
453       (dotimes (i values)
454         (values-indices `(+ ,n-index ,(+ nargs i)))
455         (values-names (gensym)))
456       (let ((n 0))
457         (dolist (arg args)
458           (unless (= (length arg) 2)
459             (error "bad argument spec: ~S" arg))
460           (let ((arg-name (first arg))
461                 (test (second arg)))
462             (arg-vars arg-name)
463             (tests `(,test (svref ,n-cache (+ ,n-index ,n)) ,arg-name))
464             (sets `(setf (svref ,n-cache (+ ,n-index ,n)) ,arg-name)))
465           (incf n)))
466
467       (when *profile-hash-cache*
468         (let ((n-probe (symbolicate "*" name "-CACHE-PROBES*"))
469               (n-miss (symbolicate "*" name "-CACHE-MISSES*")))
470           (inits `(setq ,n-probe 0))
471           (inits `(setq ,n-miss 0))
472           (forms `(defvar ,n-probe))
473           (forms `(defvar ,n-miss))
474           (forms `(declaim (fixnum ,n-miss ,n-probe)))))
475
476       (let ((fun-name (symbolicate name "-CACHE-LOOKUP")))
477         (inlines fun-name)
478         (forms
479          `(defun ,fun-name ,(arg-vars)
480             ,@(when *profile-hash-cache*
481                 `((incf ,(symbolicate  "*" name "-CACHE-PROBES*"))))
482             (let ((,n-index (* (,hash-function ,@(arg-vars)) ,entry-size))
483                   (,n-cache ,var-name))
484               (declare (type fixnum ,n-index))
485               (cond ((and ,@(tests))
486                      (values ,@(mapcar (lambda (x) `(svref ,n-cache ,x))
487                                        (values-indices))))
488                     (t
489                      ,@(when *profile-hash-cache*
490                          `((incf ,(symbolicate  "*" name "-CACHE-MISSES*"))))
491                      ,default))))))
492
493       (let ((fun-name (symbolicate name "-CACHE-ENTER")))
494         (inlines fun-name)
495         (forms
496          `(defun ,fun-name (,@(arg-vars) ,@(values-names))
497             (let ((,n-index (* (,hash-function ,@(arg-vars)) ,entry-size))
498                   (,n-cache ,var-name))
499               (declare (type fixnum ,n-index))
500               ,@(sets)
501               ,@(mapcar (lambda (i val)
502                           `(setf (svref ,n-cache ,i) ,val))
503                         (values-indices)
504                         (values-names))
505               (values)))))
506
507       (let ((fun-name (symbolicate name "-CACHE-CLEAR")))
508         (forms
509          `(defun ,fun-name ()
510             (do ((,n-index ,(- total-size entry-size) (- ,n-index ,entry-size))
511                  (,n-cache ,var-name))
512                 ((minusp ,n-index))
513               (declare (type fixnum ,n-index))
514               ,@(collect ((arg-sets))
515                   (dotimes (i nargs)
516                     (arg-sets `(setf (svref ,n-cache (+ ,n-index ,i)) nil)))
517                   (arg-sets))
518               ,@(mapcar (lambda (i val)
519                           `(setf (svref ,n-cache ,i) ,val))
520                         (values-indices)
521                         default-values))
522             (values)))
523         (forms `(,fun-name)))
524
525       (inits `(unless (boundp ',var-name)
526                 (setq ,var-name (make-array ,total-size))))
527       #!+sb-show (inits `(setq *hash-caches-initialized-p* t))
528
529       `(progn
530          (defvar ,var-name)
531          (declaim (type (simple-vector ,total-size) ,var-name))
532          #!-sb-fluid (declaim (inline ,@(inlines)))
533          (,init-wrapper ,@(inits))
534          ,@(forms)
535          ',name))))
536
537 ;;; some syntactic sugar for defining a function whose values are
538 ;;; cached by DEFINE-HASH-CACHE
539 (defmacro defun-cached ((name &rest options &key (values 1) default
540                               &allow-other-keys)
541                         args &body body-decls-doc)
542   (let ((default-values (if (and (consp default) (eq (car default) 'values))
543                             (cdr default)
544                             (list default)))
545         (arg-names (mapcar #'car args)))
546     (collect ((values-names))
547       (dotimes (i values)
548         (values-names (gensym)))
549       (multiple-value-bind (body decls doc) (parse-body body-decls-doc)
550         `(progn
551            (define-hash-cache ,name ,args ,@options)
552            (defun ,name ,arg-names
553              ,@decls
554              ,doc
555              (cond #!+sb-show
556                    ((not (boundp '*hash-caches-initialized-p*))
557                     ;; This shouldn't happen, but it did happen to me
558                     ;; when revising the type system, and it's a lot
559                     ;; easier to figure out what what's going on with
560                     ;; that kind of problem if the system can be kept
561                     ;; alive until cold boot is complete. The recovery
562                     ;; mechanism should definitely be conditional on
563                     ;; some debugging feature (e.g. SB-SHOW) because
564                     ;; it's big, duplicating all the BODY code. -- WHN
565                     (/show0 ,name " too early in cold init, uncached")
566                     (/show0 ,(first arg-names) "=..")
567                     (/hexstr ,(first arg-names))
568                     ,@body)
569                    (t
570                     (multiple-value-bind ,(values-names)
571                         (,(symbolicate name "-CACHE-LOOKUP") ,@arg-names)
572                       (if (and ,@(mapcar (lambda (val def)
573                                            `(eq ,val ,def))
574                                          (values-names) default-values))
575                           (multiple-value-bind ,(values-names)
576                               (progn ,@body)
577                             (,(symbolicate name "-CACHE-ENTER") ,@arg-names
578                              ,@(values-names))
579                             (values ,@(values-names)))
580                           (values ,@(values-names))))))))))))
581
582 (defmacro define-cached-synonym
583     (name &optional (original (symbolicate "%" name)))
584   (let ((cached-name (symbolicate "%%" name "-cached")))
585     `(progn
586        (defun-cached (,cached-name :hash-bits 8
587                                    :hash-function (lambda (x)
588                                                     (logand (sxhash x) #xff)))
589            ((args equal))
590          (apply #',original args))
591        (defun ,name (&rest args)
592          (,cached-name args)))))
593
594 ;;; FIXME: maybe not the best place
595 ;;;
596 ;;; FIXME: think of a better name -- not only does this not have the
597 ;;; CAR recursion of EQUAL, it also doesn't have the special treatment
598 ;;; of pathnames, bit-vectors and strings.
599 ;;;
600 ;;; KLUDGE: This means that we will no longer cache specifiers of the
601 ;;; form '(INTEGER (0) 4).  This is probably not a disaster.
602 ;;;
603 ;;; A helper function for the type system, which is the main user of
604 ;;; these caches: we must be more conservative than EQUAL for some of
605 ;;; our equality tests, because MEMBER and friends refer to EQLity.
606 ;;; So:
607 (defun equal-but-no-car-recursion (x y)
608   (cond
609     ((eql x y) t)
610     ((consp x)
611      (and (consp y)
612           (eql (car x) (car y))
613           (equal-but-no-car-recursion (cdr x) (cdr y))))
614     (t nil)))
615 \f
616 ;;;; package idioms
617
618 ;;; Note: Almost always you want to use FIND-UNDELETED-PACKAGE-OR-LOSE
619 ;;; instead of this function. (The distinction only actually matters when
620 ;;; PACKAGE-DESIGNATOR is actually a deleted package, and in that case
621 ;;; you generally do want to signal an error instead of proceeding.)
622 (defun %find-package-or-lose (package-designator)
623   (or (find-package package-designator)
624       (error 'sb!kernel:simple-package-error
625              :package package-designator
626              :format-control "The name ~S does not designate any package."
627              :format-arguments (list package-designator))))
628
629 ;;; ANSI specifies (in the section for FIND-PACKAGE) that the
630 ;;; consequences of most operations on deleted packages are
631 ;;; unspecified. We try to signal errors in such cases.
632 (defun find-undeleted-package-or-lose (package-designator)
633   (let ((maybe-result (%find-package-or-lose package-designator)))
634     (if (package-name maybe-result)     ; if not deleted
635         maybe-result
636         (error 'sb!kernel:simple-package-error
637                :package maybe-result
638                :format-control "The package ~S has been deleted."
639                :format-arguments (list maybe-result)))))
640 \f
641 ;;;; various operations on names
642
643 ;;; Is NAME a legal function name?
644 (defun legal-fun-name-p (name)
645   (values (valid-function-name-p name)))
646
647 ;;; Signal an error unless NAME is a legal function name.
648 (defun legal-fun-name-or-type-error (name)
649   (unless (legal-fun-name-p name)
650     (error 'simple-type-error
651            :datum name
652            :expected-type '(or symbol list)
653            :format-control "invalid function name: ~S"
654            :format-arguments (list name))))
655
656 ;;; Given a function name, return the symbol embedded in it.
657 ;;;
658 ;;; The ordinary use for this operator (and the motivation for the
659 ;;; name of this operator) is to convert from a function name to the
660 ;;; name of the BLOCK which encloses its body.
661 ;;;
662 ;;; Occasionally the operator is useful elsewhere, where the operator
663 ;;; name is less mnemonic. (Maybe it should be changed?)
664 (declaim (ftype (function ((or symbol cons)) symbol) fun-name-block-name))
665 (defun fun-name-block-name (fun-name)
666   (cond ((symbolp fun-name)
667          fun-name)
668         ((consp fun-name)
669          (multiple-value-bind (legalp block-name)
670              (valid-function-name-p fun-name)
671            (if legalp
672                block-name
673                (error "not legal as a function name: ~S" fun-name))))
674         (t
675          (error "not legal as a function name: ~S" fun-name))))
676
677 (defun looks-like-name-of-special-var-p (x)
678   (and (symbolp x)
679        (let ((name (symbol-name x)))
680          (and (> (length name) 2) ; to exclude '* and '**
681               (char= #\* (aref name 0))
682               (char= #\* (aref name (1- (length name))))))))
683
684 ;;; Some symbols are defined by ANSI to be self-evaluating. Return
685 ;;; non-NIL for such symbols (and make the non-NIL value a traditional
686 ;;; message, for use in contexts where the user asks us to change such
687 ;;; a symbol).
688 (defun symbol-self-evaluating-p (symbol)
689   (declare (type symbol symbol))
690   (cond ((eq symbol t)
691          "Veritas aeterna. (can't change T)")
692         ((eq symbol nil)
693          "Nihil ex nihil. (can't change NIL)")
694         ((keywordp symbol)
695          "Keyword values can't be changed.")
696         (t
697          nil)))
698
699 ;;; This function is to be called just before a change which would
700 ;;; affect the symbol value. (We don't absolutely have to call this
701 ;;; function before such changes, since such changes are given as
702 ;;; undefined behavior. In particular, we don't if the runtime cost
703 ;;; would be annoying. But otherwise it's nice to do so.)
704 (defun about-to-modify-symbol-value (symbol)
705   (declare (type symbol symbol))
706   (let ((reason (symbol-self-evaluating-p symbol)))
707     (when reason
708       (error reason)))
709   ;; (Note: Just because a value is CONSTANTP is not a good enough
710   ;; reason to complain here, because we want DEFCONSTANT to be able
711   ;; to use this function, and it's legal to DEFCONSTANT a constant as
712   ;; long as the new value is EQL to the old value.)
713   (values))
714
715
716 ;;; If COLD-FSET occurs not at top level, just treat it as an ordinary
717 ;;; assignment instead of doing cold static linking. That way things like
718 ;;;   (FLET ((FROB (X) ..))
719 ;;;     (DEFUN FOO (X Y) (FROB X) ..)
720 ;;;     (DEFUN BAR (Z) (AND (FROB X) ..)))
721 ;;; can still "work" for cold init: they don't do magical static
722 ;;; linking the way that true toplevel DEFUNs do, but at least they do
723 ;;; the linking eventually, so as long as #'FOO and #'BAR aren't
724 ;;; needed until "cold toplevel forms" have executed, it's OK.
725 (defmacro cold-fset (name lambda)
726   (style-warn 
727    "~@<COLD-FSET ~S not cross-compiled at top level: demoting to ~
728 (SETF FDEFINITION)~:@>"
729    name)
730   ;; We convert the LAMBDA expression to the corresponding NAMED-LAMBDA
731   ;; expression so that the compiler can use NAME in debug names etc. 
732   (destructuring-bind (lambda-symbol &rest lambda-rest) lambda
733     (assert (eql lambda-symbol 'lambda)) ; else dunno how to do conversion
734     `(setf (fdefinition ',name)
735            (named-lambda ,name ,@lambda-rest))))
736 \f
737 ;;;; ONCE-ONLY
738 ;;;;
739 ;;;; "The macro ONCE-ONLY has been around for a long time on various
740 ;;;; systems [..] if you can understand how to write and when to use
741 ;;;; ONCE-ONLY, then you truly understand macro." -- Peter Norvig,
742 ;;;; _Paradigms of Artificial Intelligence Programming: Case Studies
743 ;;;; in Common Lisp_, p. 853
744
745 ;;; ONCE-ONLY is a utility useful in writing source transforms and
746 ;;; macros. It provides a concise way to wrap a LET around some code
747 ;;; to ensure that some forms are only evaluated once.
748 ;;;
749 ;;; Create a LET* which evaluates each value expression, binding a
750 ;;; temporary variable to the result, and wrapping the LET* around the
751 ;;; result of the evaluation of BODY. Within the body, each VAR is
752 ;;; bound to the corresponding temporary variable.
753 (defmacro once-only (specs &body body)
754   (named-let frob ((specs specs)
755                    (body body))
756     (if (null specs)
757         `(progn ,@body)
758         (let ((spec (first specs)))
759           ;; FIXME: should just be DESTRUCTURING-BIND of SPEC
760           (unless (proper-list-of-length-p spec 2)
761             (error "malformed ONCE-ONLY binding spec: ~S" spec))
762           (let* ((name (first spec))
763                  (exp-temp (gensym (symbol-name name))))
764             `(let ((,exp-temp ,(second spec))
765                    (,name (gensym "ONCE-ONLY-")))
766                `(let ((,,name ,,exp-temp))
767                   ,,(frob (rest specs) body))))))))
768 \f
769 ;;;; various error-checking utilities
770
771 ;;; This function can be used as the default value for keyword
772 ;;; arguments that must be always be supplied. Since it is known by
773 ;;; the compiler to never return, it will avoid any compile-time type
774 ;;; warnings that would result from a default value inconsistent with
775 ;;; the declared type. When this function is called, it signals an
776 ;;; error indicating that a required &KEY argument was not supplied.
777 ;;; This function is also useful for DEFSTRUCT slot defaults
778 ;;; corresponding to required arguments.
779 (declaim (ftype (function () nil) missing-arg))
780 (defun missing-arg ()
781   #!+sb-doc
782   (/show0 "entering MISSING-ARG")
783   (error "A required &KEY or &OPTIONAL argument was not supplied."))
784
785 ;;; like CL:ASSERT and CL:CHECK-TYPE, but lighter-weight
786 ;;;
787 ;;; (As of sbcl-0.6.11.20, we were using some 400 calls to CL:ASSERT.
788 ;;; The CL:ASSERT restarts and whatnot expand into a significant
789 ;;; amount of code when you multiply them by 400, so replacing them
790 ;;; with this should reduce the size of the system by enough to be
791 ;;; worthwhile. ENFORCE-TYPE is much less common, but might still be
792 ;;; worthwhile, and since I don't really like CERROR stuff deep in the
793 ;;; guts of complex systems anyway, I replaced it too.)
794 (defmacro aver (expr)
795   `(unless ,expr
796      (%failed-aver ,(format nil "~A" expr))))
797
798 (defun %failed-aver (expr-as-string)
799   (bug "~@<failed AVER: ~2I~_~S~:>" expr-as-string))
800
801 ;;; We need a definition of BUG here for the host compiler to be able
802 ;;; to deal with BUGs in sbcl. This should never affect an end-user,
803 ;;; who will pick up the definition that signals a CONDITION of
804 ;;; condition-class BUG; however, this is not defined on the host
805 ;;; lisp, but for the target. SBCL developers sometimes trigger BUGs
806 ;;; in their efforts, and it is useful to get the details of the BUG
807 ;;; rather than an undefined function error. - CSR, 2002-04-12
808 #+sb-xc-host
809 (defun bug (format-control &rest format-arguments)
810   (error 'simple-error
811          :format-control "~@<  ~? ~:@_~?~:>"
812          :format-arguments `(,format-control
813                              ,format-arguments
814                              "~@<If you see this and are an SBCL ~
815 developer, then it is probable that you have made a change to the ~
816 system that has broken the ability for SBCL to compile, usually by ~
817 removing an assumed invariant of the system, but sometimes by making ~
818 an averrance that is violated (check your code!). If you are a user, ~
819 please submit a bug report to the developers' mailing list, details of ~
820 which can be found at <http://sbcl.sourceforge.net/>.~:@>"
821                              ())))
822
823 (defmacro enforce-type (value type)
824   (once-only ((value value))
825     `(unless (typep ,value ',type)
826        (%failed-enforce-type ,value ',type))))
827
828 (defun %failed-enforce-type (value type)
829   (error 'simple-type-error ; maybe should be TYPE-BUG, subclass of BUG?
830          :value value
831          :expected-type type
832          :format-control "~@<~S ~_is not a ~_~S~:>"
833          :format-arguments (list value type)))
834 \f
835 ;;; Return a function like FUN, but expecting its (two) arguments in
836 ;;; the opposite order that FUN does.
837 (declaim (inline swapped-args-fun))
838 (defun swapped-args-fun (fun)
839   (declare (type function fun))
840   (lambda (x y)
841     (funcall fun y x)))
842
843 ;;; Return the numeric value of a type bound, i.e. an interval bound
844 ;;; more or less in the format of bounds in ANSI's type specifiers,
845 ;;; where a bare numeric value is a closed bound and a list of a
846 ;;; single numeric value is an open bound.
847 ;;;
848 ;;; The "more or less" bit is that the no-bound-at-all case is
849 ;;; represented by NIL (not by * as in ANSI type specifiers); and in
850 ;;; this case we return NIL.
851 (defun type-bound-number (x)
852   (if (consp x)
853       (destructuring-bind (result) x result)
854       x))
855
856 ;;; some commonly-occuring CONSTANTLY forms
857 (macrolet ((def-constantly-fun (name constant-expr)
858              `(setf (symbol-function ',name)
859                     (constantly ,constant-expr))))
860   (def-constantly-fun constantly-t t)
861   (def-constantly-fun constantly-nil nil)
862   (def-constantly-fun constantly-0 0))
863
864 ;;; If X is an atom, see whether it is present in *FEATURES*. Also
865 ;;; handle arbitrary combinations of atoms using NOT, AND, OR.
866 (defun featurep (x)
867   (if (consp x)
868     (case (car x)
869       ((:not not)
870        (if (cddr x)
871          (error "too many subexpressions in feature expression: ~S" x)
872          (not (featurep (cadr x)))))
873       ((:and and) (every #'featurep (cdr x)))
874       ((:or or) (some #'featurep (cdr x)))
875       (t
876        (error "unknown operator in feature expression: ~S." x)))
877     (not (null (memq x *features*)))))
878
879 ;;; Given a list of keyword substitutions `(,OLD ,NEW), and a
880 ;;; &KEY-argument-list-style list of alternating keywords and
881 ;;; arbitrary values, return a new &KEY-argument-list-style list with
882 ;;; all substitutions applied to it.
883 ;;;
884 ;;; Note: If efficiency mattered, we could do less consing. (But if
885 ;;; efficiency mattered, why would we be using &KEY arguments at
886 ;;; all, much less renaming &KEY arguments?)
887 ;;;
888 ;;; KLUDGE: It would probably be good to get rid of this. -- WHN 19991201
889 (defun rename-key-args (rename-list key-args)
890   (declare (type list rename-list key-args))
891   ;; Walk through RENAME-LIST modifying RESULT as per each element in
892   ;; RENAME-LIST.
893   (do ((result (copy-list key-args))) ; may be modified below
894       ((null rename-list) result)
895     (destructuring-bind (old new) (pop rename-list)
896       ;; ANSI says &KEY arg names aren't necessarily KEYWORDs.
897       (declare (type symbol old new))
898       ;; Walk through RESULT renaming any OLD key argument to NEW.
899       (do ((in-result result (cddr in-result)))
900           ((null in-result))
901         (declare (type list in-result))
902         (when (eq (car in-result) old)
903           (setf (car in-result) new))))))
904
905 ;;; ANSI Common Lisp's READ-SEQUENCE function, unlike most of the
906 ;;; other ANSI input functions, is defined to communicate end of file
907 ;;; status with its return value, not by signalling. That is not the
908 ;;; behavior that we usually want. This function is a wrapper which
909 ;;; restores the behavior that we usually want, causing READ-SEQUENCE
910 ;;; to communicate end-of-file status by signalling.
911 (defun read-sequence-or-die (sequence stream &key start end)
912   ;; implementation using READ-SEQUENCE
913   #-no-ansi-read-sequence
914   (let ((read-end (read-sequence sequence
915                                  stream
916                                  :start start
917                                  :end end)))
918     (unless (= read-end end)
919       (error 'end-of-file :stream stream))
920     (values))
921   ;; workaround for broken READ-SEQUENCE
922   #+no-ansi-read-sequence
923   (progn
924     (aver (<= start end))
925     (let ((etype (stream-element-type stream)))
926     (cond ((equal etype '(unsigned-byte 8))
927            (do ((i start (1+ i)))
928                ((>= i end)
929                 (values))
930              (setf (aref sequence i)
931                    (read-byte stream))))
932           (t (error "unsupported element type ~S" etype))))))
933 \f
934 ;;;; utilities for two-VALUES predicates
935
936 (defmacro not/type (x)
937   (let ((val (gensym "VAL"))
938         (win (gensym "WIN")))
939     `(multiple-value-bind (,val ,win)
940          ,x
941        (if ,win
942            (values (not ,val) t)
943            (values nil nil)))))
944
945 (defmacro and/type (x y)
946   `(multiple-value-bind (val1 win1) ,x
947      (if (and (not val1) win1)
948          (values nil t)
949          (multiple-value-bind (val2 win2) ,y
950            (if (and val1 val2)
951                (values t t)
952                (values nil (and win2 (not val2))))))))
953
954 ;;; sort of like ANY and EVERY, except:
955 ;;;   * We handle two-VALUES predicate functions, as SUBTYPEP does.
956 ;;;     (And if the result is uncertain, then we return (VALUES NIL NIL),
957 ;;;     as SUBTYPEP does.)
958 ;;;   * THING is just an atom, and we apply OP (an arity-2 function)
959 ;;;     successively to THING and each element of LIST.
960 (defun any/type (op thing list)
961   (declare (type function op))
962   (let ((certain? t))
963     (dolist (i list (values nil certain?))
964       (multiple-value-bind (sub-value sub-certain?) (funcall op thing i)
965         (if sub-certain?
966             (when sub-value (return (values t t)))
967             (setf certain? nil))))))
968 (defun every/type (op thing list)
969   (declare (type function op))
970   (let ((certain? t))
971     (dolist (i list (if certain? (values t t) (values nil nil)))
972       (multiple-value-bind (sub-value sub-certain?) (funcall op thing i)
973         (if sub-certain?
974             (unless sub-value (return (values nil t)))
975             (setf certain? nil))))))
976 \f
977 ;;;; DEFPRINTER
978
979 ;;; These functions are called by the expansion of the DEFPRINTER
980 ;;; macro to do the actual printing.
981 (declaim (ftype (function (symbol t stream) (values))
982                 defprinter-prin1 defprinter-princ))
983 (defun defprinter-prin1 (name value stream)
984   (defprinter-prinx #'prin1 name value stream))
985 (defun defprinter-princ (name value stream)
986   (defprinter-prinx #'princ name value stream))
987 (defun defprinter-prinx (prinx name value stream)
988   (declare (type function prinx))
989   (when *print-pretty*
990     (pprint-newline :linear stream))
991   (format stream ":~A " name)
992   (funcall prinx value stream)
993   (values))
994 (defun defprinter-print-space (stream)
995   (write-char #\space stream))
996
997 ;;; Define some kind of reasonable PRINT-OBJECT method for a
998 ;;; STRUCTURE-OBJECT class.
999 ;;;
1000 ;;; NAME is the name of the structure class, and CONC-NAME is the same
1001 ;;; as in DEFSTRUCT.
1002 ;;;
1003 ;;; The SLOT-DESCS describe how each slot should be printed. Each
1004 ;;; SLOT-DESC can be a slot name, indicating that the slot should
1005 ;;; simply be printed. A SLOT-DESC may also be a list of a slot name
1006 ;;; and other stuff. The other stuff is composed of keywords followed
1007 ;;; by expressions. The expressions are evaluated with the variable
1008 ;;; which is the slot name bound to the value of the slot. These
1009 ;;; keywords are defined:
1010 ;;;
1011 ;;; :PRIN1    Print the value of the expression instead of the slot value.
1012 ;;; :PRINC    Like :PRIN1, only PRINC the value
1013 ;;; :TEST     Only print something if the test is true.
1014 ;;;
1015 ;;; If no printing thing is specified then the slot value is printed
1016 ;;; as if by PRIN1.
1017 ;;;
1018 ;;; The structure being printed is bound to STRUCTURE and the stream
1019 ;;; is bound to STREAM.
1020 (defmacro defprinter ((name
1021                        &key
1022                        (conc-name (concatenate 'simple-string
1023                                                (symbol-name name)
1024                                                "-"))
1025                        identity)
1026                       &rest slot-descs)
1027   (let ((first? t)
1028         maybe-print-space
1029         (reversed-prints nil)
1030         (stream (gensym "STREAM")))
1031     (flet ((sref (slot-name)
1032              `(,(symbolicate conc-name slot-name) structure)))
1033       (dolist (slot-desc slot-descs)
1034         (if first?
1035             (setf maybe-print-space nil
1036                   first? nil)
1037             (setf maybe-print-space `(defprinter-print-space ,stream)))
1038         (cond ((atom slot-desc)
1039                (push maybe-print-space reversed-prints)
1040                (push `(defprinter-prin1 ',slot-desc ,(sref slot-desc) ,stream)
1041                      reversed-prints))
1042               (t
1043                (let ((sname (first slot-desc))
1044                      (test t))
1045                  (collect ((stuff))
1046                    (do ((option (rest slot-desc) (cddr option)))
1047                        ((null option)
1048                         (push `(let ((,sname ,(sref sname)))
1049                                  (when ,test
1050                                    ,maybe-print-space
1051                                    ,@(or (stuff)
1052                                          `((defprinter-prin1
1053                                              ',sname ,sname ,stream)))))
1054                               reversed-prints))
1055                      (case (first option)
1056                        (:prin1
1057                         (stuff `(defprinter-prin1
1058                                   ',sname ,(second option) ,stream)))
1059                        (:princ
1060                         (stuff `(defprinter-princ
1061                                   ',sname ,(second option) ,stream)))
1062                        (:test (setq test (second option)))
1063                        (t
1064                         (error "bad option: ~S" (first option)))))))))))
1065     `(def!method print-object ((structure ,name) ,stream)
1066        (pprint-logical-block (,stream nil)
1067          (print-unreadable-object (structure
1068                                    ,stream
1069                                    :type t
1070                                    :identity ,identity)
1071            ,@(nreverse reversed-prints))))))
1072 \f
1073 ;;;; etc.
1074
1075 ;;; Given a pathname, return a corresponding physical pathname.
1076 (defun physicalize-pathname (possibly-logical-pathname)
1077   (if (typep possibly-logical-pathname 'logical-pathname)
1078       (translate-logical-pathname possibly-logical-pathname)
1079       possibly-logical-pathname))
1080
1081 (defun deprecation-warning (bad-name &optional good-name)
1082   (warn "using deprecated ~S~@[, should use ~S instead~]"
1083         bad-name
1084         good-name))
1085
1086 ;;; Anaphoric macros
1087 (defmacro awhen (test &body body)
1088   `(let ((it ,test))
1089      (when it ,@body)))
1090
1091 (defmacro acond (&rest clauses)
1092   (if (null clauses)
1093       `()
1094       (destructuring-bind ((test &body body) &rest rest) clauses
1095         (once-only ((test test))
1096           `(if ,test
1097                (let ((it ,test)) (declare (ignorable it)),@body)
1098                (acond ,@rest))))))
1099
1100 ;;; (binding* ({(names initial-value [flag])}*) body)
1101 ;;; FLAG may be NIL or :EXIT-IF-NULL
1102 ;;;
1103 ;;; This form unites LET*, MULTIPLE-VALUE-BIND and AWHEN.
1104 (defmacro binding* ((&rest bindings) &body body)
1105   (let ((bindings (reverse bindings)))
1106     (loop with form = `(progn ,@body)
1107           for binding in bindings
1108           do (destructuring-bind (names initial-value &optional flag)
1109                  binding
1110                (multiple-value-bind (names declarations)
1111                    (etypecase names
1112                      (null
1113                       (let ((name (gensym)))
1114                         (values (list name) `((declare (ignorable ,name))))))
1115                      (symbol
1116                       (values (list names) nil))
1117                      (list
1118                       (collect ((new-names) (ignorable))
1119                         (dolist (name names)
1120                           (when (eq name nil)
1121                             (setq name (gensym))
1122                             (ignorable name))
1123                           (new-names name))
1124                         (values (new-names)
1125                                 (when (ignorable)
1126                                   `((declare (ignorable ,@(ignorable)))))))))
1127                  (setq form `(multiple-value-bind ,names
1128                                  ,initial-value
1129                                ,@declarations
1130                                ,(ecase flag
1131                                        ((nil) form)
1132                                        ((:exit-if-null)
1133                                         `(when ,(first names) ,form)))))))
1134           finally (return form))))
1135 \f
1136 ;;; Delayed evaluation
1137 (defmacro delay (form)
1138   `(cons nil (lambda () ,form)))
1139
1140 (defun force (promise)
1141   (cond ((not (consp promise)) promise)
1142         ((car promise) (cdr promise))
1143         (t (setf (car promise) t
1144                  (cdr promise) (funcall (cdr promise))))))
1145
1146 (defun promise-ready-p (promise)
1147   (or (not (consp promise))
1148       (car promise)))
1149 \f
1150 ;;; toplevel helper
1151 (defmacro with-rebound-io-syntax (&body body)
1152   `(%with-rebound-io-syntax (lambda () ,@body)))
1153
1154 (defun %with-rebound-io-syntax (function)
1155   (declare (type function function))
1156   (let ((*package* *package*)
1157         (*print-array* *print-array*)
1158         (*print-base* *print-base*)
1159         (*print-case* *print-case*)
1160         (*print-circle* *print-circle*)
1161         (*print-escape* *print-escape*)
1162         (*print-gensym* *print-gensym*)
1163         (*print-length* *print-length*)
1164         (*print-level* *print-level*)
1165         (*print-lines* *print-lines*)
1166         (*print-miser-width* *print-miser-width*)
1167         (*print-pretty* *print-pretty*)
1168         (*print-radix* *print-radix*)
1169         (*print-readably* *print-readably*)
1170         (*print-right-margin* *print-right-margin*)
1171         (*read-base* *read-base*)
1172         (*read-default-float-format* *read-default-float-format*)
1173         (*read-eval* *read-eval*)
1174         (*read-suppress* *read-suppress*)
1175         (*readtable* *readtable*))
1176     (funcall function)))