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