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