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