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