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