(SETF %FUN-NAME) on closures, now with fewer restrictions.
[sbcl.git] / src / code / early-extensions.lisp
blobea9e8be2b47ba97ed596264df2c47ac9af0280d5
1 ;;;; various extensions (including SB-INT "internal extensions")
2 ;;;; available both in the cross-compilation host Lisp and in the
3 ;;;; target SBCL
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.
14 (in-package "SB!IMPL")
16 (defvar *core-pathname* nil
17 "The absolute pathname of the running SBCL core.")
19 (defvar *runtime-pathname* nil
20 "The absolute pathname of the running SBCL runtime.")
22 ;;; something not EQ to anything we might legitimately READ
23 (defglobal *eof-object* (make-symbol "EOF-OBJECT"))
25 (eval-when (:compile-toplevel :load-toplevel :execute)
26 (defconstant max-hash sb!xc:most-positive-fixnum))
28 (def!type hash ()
29 `(integer 0 ,max-hash))
31 ;;; a type used for indexing into sequences, and for related
32 ;;; quantities like lengths of lists and other sequences.
33 ;;;
34 ;;; A more correct value for the exclusive upper bound for indexing
35 ;;; would be (1- ARRAY-DIMENSION-LIMIT) since ARRAY-DIMENSION-LIMIT is
36 ;;; the exclusive maximum *size* of one array dimension (As specified
37 ;;; in CLHS entries for MAKE-ARRAY and "valid array dimensions"). The
38 ;;; current value is maintained to avoid breaking existing code that
39 ;;; also uses that type for upper bounds on indices (e.g. sequence
40 ;;; length).
41 ;;;
42 ;;; In SBCL, ARRAY-DIMENSION-LIMIT is arranged to be a little smaller
43 ;;; than MOST-POSITIVE-FIXNUM, for implementation (see comment above
44 ;;; ARRAY-DIMENSION-LIMIT) and efficiency reasons: staying below
45 ;;; MOST-POSITIVE-FIXNUM lets the system know it can increment a value
46 ;;; of type INDEX without having to worry about using a bignum to
47 ;;; represent the result.
48 (def!type index () `(integer 0 (,sb!xc:array-dimension-limit)))
50 ;;; like INDEX, but only up to half the maximum. Used by hash-table
51 ;;; code that does plenty to (aref v (* 2 i)) and (aref v (1+ (* 2 i))).
52 (def!type index/2 () `(integer 0 (,(floor sb!xc:array-dimension-limit 2))))
54 ;;; like INDEX, but augmented with -1 (useful when using the index
55 ;;; to count downwards to 0, e.g. LOOP FOR I FROM N DOWNTO 0, with
56 ;;; an implementation which terminates the loop by testing for the
57 ;;; index leaving the loop range)
58 (def!type index-or-minus-1 () `(integer -1 (,sb!xc:array-dimension-limit)))
60 ;;; A couple of VM-related types that are currently used only on the
61 ;;; alpha and mips platforms. -- CSR, 2002-06-24
62 (def!type unsigned-byte-with-a-bite-out (size bite)
63 (unless (typep size '(integer 1))
64 (error "Bad size for the ~S type specifier: ~S."
65 'unsigned-byte-with-a-bite-out size))
66 (let ((bound (ash 1 size)))
67 `(integer 0 ,(- bound bite 1))))
69 (def!type signed-byte-with-a-bite-out (size bite)
70 (unless (typep size '(integer 2))
71 (error "Bad size for ~S type specifier: ~S."
72 'signed-byte-with-a-bite-out size))
73 (let ((bound (ash 1 (1- size))))
74 `(integer ,(- bound) ,(- bound bite 1))))
76 ;;; The smallest power of two that is equal to or greater than X.
77 (declaim (inline power-of-two-ceiling))
78 (defun power-of-two-ceiling (x)
79 (declare (index x))
80 (ash 1 (integer-length (1- x))))
82 (def!type load/store-index (scale lowtag min-offset
83 &optional (max-offset min-offset))
84 `(integer ,(- (truncate (+ (ash 1 16)
85 (* min-offset sb!vm:n-word-bytes)
86 (- lowtag))
87 scale))
88 ,(truncate (- (+ (1- (ash 1 16)) lowtag)
89 (* max-offset sb!vm:n-word-bytes))
90 scale)))
92 #!+(or x86 x86-64)
93 (defun displacement-bounds (lowtag element-size data-offset)
94 (let* ((adjustment (- (* data-offset sb!vm:n-word-bytes) lowtag))
95 (bytes-per-element (ceiling element-size sb!vm:n-byte-bits))
96 (min (truncate (+ sb!vm::minimum-immediate-offset adjustment)
97 bytes-per-element))
98 (max (truncate (+ sb!vm::maximum-immediate-offset adjustment)
99 bytes-per-element)))
100 (values min max)))
102 #!+(or x86 x86-64)
103 (def!type constant-displacement (lowtag element-size data-offset)
104 (flet ((integerify (x)
105 (etypecase x
106 (integer x)
107 (symbol (symbol-value x)))))
108 (let ((lowtag (integerify lowtag))
109 (element-size (integerify element-size))
110 (data-offset (integerify data-offset)))
111 (multiple-value-bind (min max) (displacement-bounds lowtag
112 element-size
113 data-offset)
114 `(integer ,min ,max)))))
116 ;;; the default value used for initializing character data. The ANSI
117 ;;; spec says this is arbitrary, so we use the value that falls
118 ;;; through when we just let the low-level consing code initialize
119 ;;; all newly-allocated memory to zero.
121 ;;; KLUDGE: It might be nice to use something which is a
122 ;;; STANDARD-CHAR, both to reduce user surprise a little and, probably
123 ;;; more significantly, to help SBCL's cross-compiler (which knows how
124 ;;; to dump STANDARD-CHARs). Unfortunately, the old CMU CL code is
125 ;;; shot through with implicit assumptions that it's #\NULL, and code
126 ;;; in several places (notably both DEFUN MAKE-ARRAY and DEFTRANSFORM
127 ;;; MAKE-ARRAY) would have to be rewritten. -- WHN 2001-10-04
128 (eval-when (:compile-toplevel :load-toplevel :execute)
129 ;; an expression we can use to construct a DEFAULT-INIT-CHAR value
130 ;; at load time (so that we don't need to teach the cross-compiler
131 ;; how to represent and dump non-STANDARD-CHARs like #\NULL)
132 (defparameter *default-init-char-form* '(code-char 0)))
134 ;;; CHAR-CODE values for ASCII characters which we care about but
135 ;;; which aren't defined in section "2.1.3 Standard Characters" of the
136 ;;; ANSI specification for Lisp
138 ;;; KLUDGE: These are typically used in the idiom (CODE-CHAR
139 ;;; FOO-CHAR-CODE). I suspect that the current implementation is
140 ;;; expanding this idiom into a full call to CODE-CHAR, which is an
141 ;;; annoying overhead. I should check whether this is happening, and
142 ;;; if so, perhaps implement a DEFTRANSFORM or something to stop it.
143 ;;; (or just find a nicer way of expressing characters portably?) --
144 ;;; WHN 19990713
145 (defconstant bell-char-code 7)
146 (defconstant backspace-char-code 8)
147 (defconstant tab-char-code 9)
148 (defconstant line-feed-char-code 10)
149 (defconstant form-feed-char-code 12)
150 (defconstant return-char-code 13)
151 (defconstant escape-char-code 27)
152 (defconstant rubout-char-code 127)
154 ;;;; type-ish predicates
156 ;;; This is used for coalescing constants, check that the tree doesn't
157 ;;; have cycles and isn't too large.
158 (defun coalesce-tree-p (x)
159 (let ((depth-limit 12)
160 (size-limit (expt 2 25)))
161 (declare (fixnum size-limit))
162 (and (consp x)
163 (labels ((safe-cddr (cons)
164 (let ((cdr (cdr cons)))
165 (when (consp cdr)
166 (cdr cdr))))
167 (check-cycle (cdr seen depth)
168 (let ((object (car cdr)))
169 (when (and (consp object)
170 (or (= depth depth-limit)
171 (memq object seen)
172 (let ((seen (cons cdr seen)))
173 (declare (dynamic-extent seen))
174 (recurse object seen
175 (truly-the fixnum (1+ depth))))))
176 (return-from coalesce-tree-p))))
177 (recurse (list seen depth)
178 ;; Almost regular circular list detection, with a twist:
179 ;; we also check each element of the list for upward
180 ;; references using CHECK-CYCLE.
181 (do ((fast (cdr list) (safe-cddr fast))
182 (slow list (cdr slow)))
183 ((not (consp fast))
184 ;; Not CDR-circular, need to check remaining CARs yet
185 (do ((tail slow (cdr tail)))
186 ((not (consp tail)))
187 (check-cycle tail seen depth)))
188 (check-cycle slow seen depth)
189 (when (or (eq fast slow)
190 (zerop (setf size-limit
191 (truly-the fixnum
192 (1- size-limit)))))
193 (return-from coalesce-tree-p)))))
194 (declare (inline check-cycle))
195 (recurse x (list x) 0)
196 t))))
198 ;;; Is X a (possibly-improper) list of at least N elements?
199 (declaim (ftype (function (t index)) list-of-length-at-least-p))
200 (defun list-of-length-at-least-p (x n)
201 (or (zerop n) ; since anything can be considered an improper list of length 0
202 (and (consp x)
203 (list-of-length-at-least-p (cdr x) (1- n)))))
205 ;;; Is X is a positive prime integer?
206 (defun positive-primep (x)
207 ;; This happens to be called only from one place in sbcl-0.7.0, and
208 ;; only for fixnums, we can limit it to fixnums for efficiency. (And
209 ;; if we didn't limit it to fixnums, we should use a cleverer
210 ;; algorithm, since this one scales pretty badly for huge X.)
211 (declare (fixnum x))
212 (if (<= x 5)
213 (and (>= x 2) (/= x 4))
214 (and (not (evenp x))
215 (not (zerop (rem x 3)))
216 (do ((q 6)
217 (r 1)
218 (inc 2 (logxor inc 6)) ;; 2,4,2,4...
219 (d 5 (+ d inc)))
220 ((or (= r 0) (> d q)) (/= r 0))
221 (declare (fixnum inc))
222 (multiple-value-setq (q r) (truncate x d))))))
224 ;;; Could this object contain other objects? (This is important to
225 ;;; the implementation of things like *PRINT-CIRCLE* and the dumper.)
226 (defun compound-object-p (x)
227 (or (consp x)
228 (%instancep x)
229 (typep x '(array t *))))
231 ;;;; the COLLECT macro
232 ;;;;
233 ;;;; comment from CMU CL: "the ultimate collection macro..."
235 ;;; helper function for COLLECT, which becomes the expander of the
236 ;;; MACROLET definitions created by COLLECT if collecting a list.
237 ;;; N-TAIL is the pointer to the current tail of the list, or NIL
238 ;;; if the list is empty.
239 (eval-when (#-sb-xc :compile-toplevel :load-toplevel :execute)
240 (defun collect-list-expander (n-value n-tail forms)
241 (let ((n-res (gensym)))
242 `(progn
243 ,@(mapcar (lambda (form)
244 `(let ((,n-res (cons ,form nil)))
245 (cond (,n-tail
246 (setf (cdr ,n-tail) ,n-res)
247 (setq ,n-tail ,n-res))
249 (setq ,n-tail ,n-res ,n-value ,n-res)))))
250 forms)
251 ,n-value))))
253 ;;; Collect some values somehow. Each of the collections specifies a
254 ;;; bunch of things which collected during the evaluation of the body
255 ;;; of the form. The name of the collection is used to define a local
256 ;;; macro, a la MACROLET. Within the body, this macro will evaluate
257 ;;; each of its arguments and collect the result, returning the
258 ;;; current value after the collection is done. The body is evaluated
259 ;;; as a PROGN; to get the final values when you are done, just call
260 ;;; the collection macro with no arguments.
262 ;;; INITIAL-VALUE is the value that the collection starts out with,
263 ;;; which defaults to NIL. FUNCTION is the function which does the
264 ;;; collection. It is a function which will accept two arguments: the
265 ;;; value to be collected and the current collection. The result of
266 ;;; the function is made the new value for the collection. As a
267 ;;; totally magical special-case, FUNCTION may be COLLECT, which tells
268 ;;; us to build a list in forward order; this is the default. If an
269 ;;; INITIAL-VALUE is supplied for COLLECT, the stuff will be RPLACD'd
270 ;;; onto the end. Note that FUNCTION may be anything that can appear
271 ;;; in the functional position, including macros and lambdas.
272 (defmacro collect (collections &body body)
273 (let ((macros ())
274 (binds ())
275 (ignores ()))
276 (dolist (spec collections)
277 (destructuring-bind (name &optional default collector
278 &aux (n-value (copy-symbol name))) spec
279 (push `(,n-value ,default) binds)
280 (let ((macro-body
281 (if (or (null collector) (eq collector 'collect))
282 (let ((n-tail (gensymify* name "-TAIL")))
283 (push n-tail ignores)
284 (push `(,n-tail ,(if default `(last ,n-value))) binds)
285 `(collect-list-expander ',n-value ',n-tail args))
286 ``(progn
287 ,@(mapcar (lambda (x)
288 `(setq ,',n-value (,',collector ,x ,',n-value)))
289 args)
290 ,',n-value))))
291 (push `(,name (&rest args) ,macro-body) macros))))
292 `(macrolet ,macros
293 (let* ,(nreverse binds)
294 ;; Even if the user reads each collection result,
295 ;; reader conditionals might statically eliminate all writes.
296 ;; Since we don't know, all the -n-tail variable are ignorable.
297 ,@(if ignores `((declare (ignorable ,@ignores))))
298 ,@body))))
300 ;;;; some old-fashioned functions. (They're not just for old-fashioned
301 ;;;; code, they're also used as optimized forms of the corresponding
302 ;;;; general functions when the compiler can prove that they're
303 ;;;; equivalent.)
305 ;;; like (MEMBER ITEM LIST :TEST #'EQ)
306 (defun memq (item list)
307 "Return tail of LIST beginning with first element EQ to ITEM."
308 (declare (explicit-check))
309 ;; KLUDGE: These could be and probably should be defined as
310 ;; (MEMBER ITEM LIST :TEST #'EQ)),
311 ;; but when I try to cross-compile that, I get an error from
312 ;; LTN-ANALYZE-KNOWN-CALL, "Recursive known function definition". The
313 ;; comments for that error say it "is probably a botched interpreter stub".
314 ;; Rather than try to figure that out, I just rewrote this function from
315 ;; scratch. -- WHN 19990512
316 (do ((i list (cdr i)))
317 ((null i))
318 (when (eq (car i) item)
319 (return i))))
321 ;;; like (ASSOC ITEM ALIST :TEST #'EQ):
322 ;;; Return the first pair of ALIST where ITEM is EQ to the key of
323 ;;; the pair.
324 (defun assq (item alist)
325 (declare (explicit-check))
326 ;; KLUDGE: CMU CL defined this with
327 ;; (DECLARE (INLINE ASSOC))
328 ;; (ASSOC ITEM ALIST :TEST #'EQ))
329 ;; which is pretty, but which would have required adding awkward
330 ;; build order constraints on SBCL (or figuring out some way to make
331 ;; inline definitions installable at build-the-cross-compiler time,
332 ;; which was too ambitious for now). Rather than mess with that, we
333 ;; just define ASSQ explicitly in terms of more primitive
334 ;; operations:
335 (dolist (pair alist)
336 ;; though it may look more natural to write this as
337 ;; (AND PAIR (EQ (CAR PAIR) ITEM))
338 ;; the temptation to do so should be resisted, as pointed out by PFD
339 ;; sbcl-devel 2003-08-16, as NIL elements are rare in association
340 ;; lists. -- CSR, 2003-08-16
341 (when (and (eq (car pair) item) (not (null pair)))
342 (return pair))))
344 ;;; like (DELETE .. :TEST #'EQ):
345 ;;; Delete all LIST entries EQ to ITEM (destructively modifying
346 ;;; LIST), and return the modified LIST.
347 (defun delq (item list)
348 (declare (explicit-check))
349 (let ((list list))
350 (do ((x list (cdr x))
351 (splice '()))
352 ((endp x) list)
353 (cond ((eq item (car x))
354 (if (null splice)
355 (setq list (cdr x))
356 (rplacd splice (cdr x))))
357 (t (setq splice x)))))) ; Move splice along to include element.
360 ;;; like (POSITION .. :TEST #'EQ):
361 ;;; Return the position of the first element EQ to ITEM.
362 (defun posq (item list)
363 (do ((i list (cdr i))
364 (j 0 (1+ j)))
365 ((null i))
366 (when (eq (car i) item)
367 (return j))))
369 (declaim (inline neq))
370 (defun neq (x y)
371 (not (eq x y)))
373 (defun adjust-list (list length initial-element)
374 (let ((old-length (length list)))
375 (cond ((< old-length length)
376 (append list (make-list (- length old-length)
377 :initial-element initial-element)))
378 ((> old-length length)
379 (subseq list 0 length))
380 (t list))))
382 ;;;; miscellaneous iteration extensions
384 ;;; like Scheme's named LET
386 ;;; (CMU CL called this ITERATE, and commented it as "the ultimate
387 ;;; iteration macro...". I (WHN) found the old name insufficiently
388 ;;; specific to remind me what the macro means, so I renamed it.)
389 (defmacro named-let (name binds &body body)
390 (dolist (x binds)
391 (unless (proper-list-of-length-p x 2)
392 (error "malformed NAMED-LET variable spec: ~S" x)))
393 `(labels ((,name ,(mapcar #'first binds) ,@body))
394 (,name ,@(mapcar #'second binds))))
396 (defun filter-dolist-declarations (decls)
397 (mapcar (lambda (decl)
398 `(declare ,@(remove-if
399 (lambda (clause)
400 (and (consp clause)
401 (or (eq (car clause) 'type)
402 (eq (car clause) 'ignore))))
403 (cdr decl))))
404 decls))
405 ;;; just like DOLIST, but with one-dimensional arrays
406 (defmacro dovector ((elt vector &optional result) &body body)
407 (multiple-value-bind (forms decls) (parse-body body nil)
408 (with-unique-names (index length vec)
409 `(let ((,vec ,vector))
410 (declare (type vector ,vec))
411 (do ((,index 0 (1+ ,index))
412 (,length (length ,vec)))
413 ((>= ,index ,length) (let ((,elt nil))
414 ,@(filter-dolist-declarations decls)
415 ,elt
416 ,result))
417 (let ((,elt (aref ,vec ,index)))
418 ,@decls
419 (tagbody
420 ,@forms)))))))
422 ;;; Iterate over the entries in a HASH-TABLE, first obtaining the lock
423 ;;; if the table is a synchronized table.
424 ;;; An implicit block named NIL exists around the iteration, as is the custom.
425 (defmacro dohash (((key-var value-var) table &key result locked) &body body)
426 (let* ((n-table (make-symbol "HT"))
427 (iter-form `(block nil
428 (maphash (lambda (,key-var ,value-var) ,@body) ,n-table)
429 ,result)))
430 `(let ((,n-table ,table))
431 ,(if locked
432 `(with-locked-system-table (,n-table) ,iter-form)
433 iter-form))))
435 ;;; Executes BODY for all entries of PLIST with KEY and VALUE bound to
436 ;;; the respective keys and values.
437 (defmacro doplist ((key val) plist &body body)
438 (with-unique-names (tail)
439 `(let ((,tail ,plist) ,key ,val)
440 (loop (when (null ,tail) (return nil))
441 (setq ,key (pop ,tail))
442 (when (null ,tail)
443 (error "malformed plist, odd number of elements"))
444 (setq ,val (pop ,tail))
445 (progn ,@body)))))
447 ;;; Like GETHASH if HASH-TABLE contains an entry for KEY.
448 ;;; Otherwise, evaluate DEFAULT, store the resulting value in
449 ;;; HASH-TABLE and return two values: 1) the result of evaluating
450 ;;; DEFAULT 2) NIL.
451 (defmacro ensure-gethash (key hash-table &optional default)
452 (with-unique-names (n-key n-hash-table value foundp)
453 `(let ((,n-key ,key)
454 (,n-hash-table ,hash-table))
455 (multiple-value-bind (,value ,foundp) (gethash ,n-key ,n-hash-table)
456 (if ,foundp
457 (values ,value t)
458 (values (setf (gethash ,n-key ,n-hash-table) ,default) nil))))))
460 ;;; (binding* ({(names initial-value [flag])}*) body)
461 ;;; FLAG may be NIL or :EXIT-IF-NULL
463 ;;; This form unites LET*, MULTIPLE-VALUE-BIND and AWHEN.
464 ;;; Any name in a list of names may be NIL to ignore the respective value.
465 ;;; If NAMES itself is nil, the initial-value form is evaluated only for effect.
467 ;;; Clauses with no flag and one binding are equivalent to LET.
469 ;;; Caution: don't use declarations of the form (<non-builtin-type-id> <var>)
470 ;;; before the INFO database is set up in building the cross-compiler,
471 ;;; or you will probably lose.
472 ;;; Of course, since some other host Lisps don't seem to think that's
473 ;;; acceptable syntax anyway, you're pretty much prevented from writing it.
475 (defmacro binding* ((&rest clauses) &body body)
476 (unless clauses ; wrap in LET to preserve non-toplevelness
477 (return-from binding* `(let () ,@body)))
478 (multiple-value-bind (body decls) (parse-body body nil)
479 ;; Generate an abstract representation that combines LET* clauses.
480 (let (repr)
481 (dolist (clause clauses)
482 (destructuring-bind (symbols value-form &optional flag) clause
483 (declare (type (member :exit-if-null nil) flag))
484 (let* ((ignore nil)
485 (symbols
486 (cond ((not (listp symbols)) (list symbols))
487 ((not symbols) (setq ignore (list (gensym))))
488 (t (mapcar
489 (lambda (x) (or x (car (push (gensym) ignore))))
490 symbols))))
491 (flags (logior (if (cdr symbols) 1 0) (if flag 2 0)))
492 (last (car repr)))
493 ;; EVENP => this clause does not entail multiple-value-bind
494 (cond ((and (evenp flags) (eql (car last) 0))
495 (setf (first last) flags)
496 (push (car symbols) (second last))
497 (push value-form (third last))
498 (setf (fourth last) (nconc ignore (fourth last))))
500 (push (list flags symbols (list value-form) ignore)
501 repr))))))
502 ;; Starting with the innermost binding clause, snarf out the
503 ;; applicable declarations. (Clauses are currently reversed)
504 (dolist (abstract-clause repr)
505 (when decls
506 (multiple-value-bind (binding-decls remaining-decls)
507 (extract-var-decls decls (second abstract-clause))
508 (setf (cddddr abstract-clause) binding-decls)
509 (setf decls remaining-decls))))
510 ;; Generate sexprs from inside out.
511 (loop with listp = t ; BODY is already a list
512 for (flags symbols values ignore . binding-decls) in repr
513 ;; Maybe test the last bound symbol in the clause for LET*
514 ;; or 1st symbol for mv-bind. Either way, the first of SYMBOLS.
515 for inner = (if (logtest flags 2) ; :EXIT-IF-NULL was specified.
516 (prog1 `(when ,(car symbols)
517 ,@(if listp body (list body)))
518 (setq listp nil))
519 body)
520 do (setq body
521 `(,.(if (evenp flags)
522 `(let* ,(nreverse (mapcar #'list symbols values)))
523 `(multiple-value-bind ,symbols ,(car values)))
524 ,@(when binding-decls (list binding-decls))
525 ,@(when ignore `((declare (ignorable ,@ignore))))
526 ,@decls ; anything leftover
527 ,@(if listp inner (list inner)))
528 listp nil
529 decls nil))
530 body)))
532 ;;;; macro writing utilities
534 (defmacro with-current-source-form ((&rest forms) &body body)
535 "In a macroexpander, indicate that FORMS are being processed by BODY.
537 FORMS are usually sub-forms of the whole form passed to the expander.
539 If more than one form is supplied, FORMS should be ordered by
540 specificity, with the most specific form first. This allows the
541 compiler to try and obtain a source path using subsequent elements of
542 FORMS if it fails for the first one.
544 Indicating the processing of sub-forms lets the compiler report
545 precise source locations in case conditions are signaled during the
546 execution of BODY.
548 NOTE: This interface is experimental and subject to change."
549 #-sb-xc-host `(sb!c::call-with-current-source-form
550 (lambda () ,@body) ,@forms)
551 #+sb-xc-host `(progn (list ,@forms) ,@body))
553 ;;;; hash cache utility
555 (eval-when (:compile-toplevel :load-toplevel :execute)
556 (defvar *profile-hash-cache* nil))
558 ;;; Define a hash cache that associates some number of argument values
559 ;;; with a result value. The TEST-FUNCTION paired with each ARG-NAME
560 ;;; is used to compare the value for that arg in a cache entry with a
561 ;;; supplied arg. The TEST-FUNCTION must not error when passed NIL as
562 ;;; its first arg, but need not return any particular value.
563 ;;; TEST-FUNCTION may be any thing that can be placed in CAR position.
565 ;;; This code used to store all the arguments / return values directly
566 ;;; in the cache vector. This was both interrupt- and thread-unsafe, since
567 ;;; it was possible that *-CACHE-ENTER would scribble over a region of the
568 ;;; cache vector which *-CACHE-LOOKUP had only partially processed. Instead
569 ;;; we now store the contents of each cache bucket as a separate array, which
570 ;;; is stored in the appropriate cell in the cache vector. A new bucket array
571 ;;; is created every time *-CACHE-ENTER is called, and the old ones are never
572 ;;; modified. This means that *-CACHE-LOOKUP will always work with a set
573 ;;; of consistent data. The overhead caused by consing new buckets seems to
574 ;;; be insignificant on the grand scale of things. -- JES, 2006-11-02
576 ;;; NAME is used to define these functions:
577 ;;; <name>-CACHE-LOOKUP Arg*
578 ;;; See whether there is an entry for the specified ARGs in the
579 ;;; cache. If not present, the :DEFAULT keyword (default NIL)
580 ;;; determines the result(s).
581 ;;; <name>-CACHE-ENTER Arg* Value*
582 ;;; Encache the association of the specified args with VALUE.
583 ;;; <name>-CACHE-CLEAR
584 ;;; Reinitialize the cache, invalidating all entries and allowing
585 ;;; the arguments and result values to be GC'd.
587 ;;; These other keywords are defined:
588 ;;; :HASH-BITS <n>
589 ;;; The size of the cache as a power of 2.
590 ;;; :HASH-FUNCTION function
591 ;;; Some thing that can be placed in CAR position which will compute
592 ;;; a fixnum with at least (* 2 <hash-bits>) of information in it.
593 ;;; :VALUES <n>
594 ;;; the number of return values cached for each function call
595 (defvar *cache-vector-symbols* nil)
597 (defun drop-all-hash-caches ()
598 (dolist (name *cache-vector-symbols*)
599 (set name nil)))
601 ;; Make a new hash-cache and optionally create the statistics vector.
602 (defun alloc-hash-cache (size symbol)
603 (let (cache)
604 ;; It took me a while to figure out why infinite recursion could occur
605 ;; in VALUES-SPECIFIER-TYPE. It's because SET calls VALUES-SPECIFIER-TYPE.
606 (macrolet ((set! (symbol value)
607 `(#+sb-xc-host set
608 #-sb-xc-host sb!kernel:%set-symbol-global-value
609 ,symbol ,value))
610 (reset-stats ()
611 ;; If statistics gathering is not not compiled-in,
612 ;; no sense in setting a symbol that is never used.
613 ;; While this uses SYMBOLICATE at runtime,
614 ;; it is inconsequential to performance.
615 (if *profile-hash-cache*
616 `(let ((statistics
617 (let ((*package* (symbol-package symbol)))
618 (symbolicate symbol "STATISTICS"))))
619 (unless (boundp statistics)
620 (set! statistics
621 (make-array 3 :element-type 'fixnum
622 :initial-contents '(1 0 0))))))))
623 ;; It would be bad if another thread sees MAKE-ARRAY's result in the
624 ;; global variable before the vector's header+length have been set.
625 ;; Without a barrier, this would be theoretically possible if the
626 ;; architecture allows out-of-order memory writes.
627 (sb!thread:barrier (:write)
628 (reset-stats)
629 (setq cache (make-array size :initial-element 0)))
630 (set! symbol cache))))
632 ;; At present we make a new vector every time a line is re-written,
633 ;; to make it thread-safe and interrupt-safe. A multi-word compare-and-swap
634 ;; is tricky to code and stronger than we need. It is possible instead
635 ;; to provide multi-word reads that can detect failure of atomicity,
636 ;; and on x86 it's possible to have atomic double-wide read/write,
637 ;; so a 1-arg/1-result cache line needn't cons at all except once
638 ;; (and maybe not even that if we make the cache into pairs of cells).
639 ;; But this way is easier to understand, for now anyway.
640 (eval-when (#-sb-xc :compile-toplevel :load-toplevel :execute)
641 (defun hash-cache-line-allocator (n)
642 (aref #.(coerce (loop for i from 2 to 6
643 collect (symbolicate "ALLOC-HASH-CACHE-LINE/"
644 (char "23456" (- i 2))))
645 'vector)
646 (- n 2))))
647 (macrolet ((def (n)
648 (let* ((ftype `(sfunction ,(make-list n :initial-element t) t))
649 (fn (hash-cache-line-allocator n))
650 (args (make-gensym-list n)))
651 `(progn
652 (declaim (ftype ,ftype ,fn))
653 (defun ,fn ,args
654 (declare (optimize (safety 0)))
655 ,(if (<= n 3)
656 `(list* ,@args)
657 `(vector ,@args)))))))
658 (def 2)
659 (def 3)
660 (def 4)
661 (def 5)
662 (def 6))
664 (defmacro !define-hash-cache (name args aux-vars
665 &key hash-function hash-bits memoizer
666 flush-function (values 1))
667 (declare (ignore memoizer))
668 (dolist (arg args)
669 (unless (<= 2 (length arg) 3)
670 (error "bad argument spec: ~S" arg)))
671 (assert (typep hash-bits '(integer 5 14))) ; reasonable bounds
672 (let* ((fun-name (symbolicate "!" name "-MEMO-WRAPPER"))
673 (var-name (symbolicate "**" name "-CACHE-VECTOR**"))
674 (statistics-name
675 (when *profile-hash-cache*
676 (symbolicate var-name "STATISTICS")))
677 (nargs (length args))
678 (size (ash 1 hash-bits))
679 (hashval (make-symbol "HASH"))
680 (cache (make-symbol "CACHE"))
681 (entry (make-symbol "LINE"))
682 (thunk (make-symbol "THUNK"))
683 (arg-vars (mapcar #'first args))
684 (nvalues (if (listp values) (length values) values))
685 (result-temps
686 (if (listp values)
687 values ; use the names provided by the user
688 (loop for i from 1 to nvalues ; else invent some names
689 collect (make-symbol (format nil "R~D" i)))))
690 (temps (append (mapcar (lambda (x) (make-symbol (string x)))
691 arg-vars)
692 result-temps))
693 ;; Mnemonic: (FIND x SEQ :test #'f) calls f with x as the LHS
694 (tests (mapcar (lambda (spec temp) ; -> (EQx ARG #:ARG)
695 `(,(cadr spec) ,(car spec) ,temp))
696 args temps))
697 (cache-type `(simple-vector ,size))
698 (line-type (let ((n (+ nargs nvalues)))
699 (if (<= n 3) 'cons `(simple-vector ,n))))
700 (bind-hashval
701 `((,hashval (the (signed-byte #.sb!vm:n-fixnum-bits)
702 (funcall ,hash-function ,@arg-vars)))
703 (,cache ,var-name)))
704 (probe-it
705 (lambda (ignore action)
706 `(when ,cache
707 (let ((,hashval ,hashval) ; gets clobbered in probe loop
708 (,cache (truly-the ,cache-type ,cache)))
709 ;; FIXME: redundant?
710 (declare (type (signed-byte #.sb!vm:n-fixnum-bits) ,hashval))
711 (loop repeat 2
712 do (let ((,entry
713 (svref ,cache
714 (ldb (byte ,hash-bits 0) ,hashval))))
715 (unless (eql ,entry 0)
716 ;; This barrier is a no-op on all multi-threaded SBCL
717 ;; architectures. No CPU except Alpha will move a
718 ;; load prior to a load on which it depends.
719 (sb!thread:barrier (:data-dependency))
720 (locally (declare (type ,line-type ,entry))
721 (let* ,(case (length temps)
722 (2 `((,(first temps) (car ,entry))
723 (,(second temps) (cdr ,entry))))
724 (3 (let ((arg-temp (sb!xc:gensym "ARGS")))
725 `((,arg-temp (cdr ,entry))
726 (,(first temps) (car ,entry))
727 (,(second temps)
728 (car (truly-the cons ,arg-temp)))
729 (,(third temps) (cdr ,arg-temp)))))
730 (t (loop for i from 0 for x in temps
731 collect `(,x (svref ,entry ,i)))))
732 ,@ignore
733 (when (and ,@tests) ,action))))
734 (setq ,hashval (ash ,hashval ,(- hash-bits)))))))))
735 (fun
736 `(defun ,fun-name (,thunk ,@arg-vars ,@aux-vars)
737 ,@(when *profile-hash-cache* ; count seeks
738 `((when (boundp ',statistics-name)
739 (incf (aref ,statistics-name 0)))))
740 (let ,bind-hashval
741 ,(funcall probe-it nil
742 `(return-from ,fun-name (values ,@result-temps)))
743 (multiple-value-bind ,result-temps (funcall ,thunk)
744 (let ((,entry
745 (,(hash-cache-line-allocator (+ nargs nvalues))
746 ,@(mapcar (lambda (spec) (or (caddr spec) (car spec)))
747 args)
748 ,@result-temps))
749 (,cache
750 (truly-the ,cache-type
751 (or ,cache (alloc-hash-cache ,size ',var-name))))
752 (idx1 (ldb (byte ,hash-bits 0) ,hashval))
753 (idx2 (ldb (byte ,hash-bits ,hash-bits) ,hashval)))
754 ,@(when *profile-hash-cache*
755 `((incf (aref ,statistics-name 1)))) ; count misses
756 ;; Why a barrier: the pointer to 'entry' (a cons or vector)
757 ;; MUST NOT be observed by another thread before its cells
758 ;; are filled. Equally bad, the 'output' cells in the line
759 ;; could be 0 while the 'input' cells matched something.
760 (sb!thread:barrier (:write))
761 (cond ((eql (svref ,cache idx1) 0)
762 (setf (svref ,cache idx1) ,entry))
763 ((eql (svref ,cache idx2) 0)
764 (setf (svref ,cache idx2) ,entry))
766 ,@(when *profile-hash-cache* ; count evictions
767 `((incf (aref ,statistics-name 2))))
768 (setf (svref ,cache idx1) ,entry))))
769 (values ,@result-temps))))))
770 `(progn
771 (pushnew ',var-name *cache-vector-symbols*)
772 (defglobal ,var-name nil)
773 ,@(when *profile-hash-cache*
774 `((declaim (type (simple-array fixnum (3)) ,statistics-name))
775 (defvar ,statistics-name)))
776 (declaim (type (or null ,cache-type) ,var-name))
777 (defun ,(symbolicate name "-CACHE-CLEAR") () (setq ,var-name nil))
778 ,@(when flush-function
779 `((defun ,flush-function ,arg-vars
780 (let ,bind-hashval
781 ,(funcall probe-it
782 `((declare (ignore ,@result-temps)))
783 `(return (setf (svref ,cache
784 (ldb (byte ,hash-bits 0) ,hashval))
785 0)))))))
786 (declaim (inline ,fun-name))
787 ,fun)))
789 ;;; some syntactic sugar for defining a function whose values are
790 ;;; cached by !DEFINE-HASH-CACHE
791 ;;; These keywords are mostly defined at !DEFINE-HASH-CACHE.
792 ;;; Additional options:
793 ;;; :MEMOIZER <name>
794 ;;; If provided, it is the name of a local macro that must be called
795 ;;; within the body forms to perform cache lookup/insertion.
796 ;;; If not provided, then the function's behavior is to automatically
797 ;;; attempt cache lookup, and on miss, execute the body code and
798 ;;; insert into the cache.
799 ;;; Manual control over memoization is useful if there are cases for
800 ;;; which it is undesirable to pollute the cache.
802 ;;; Possible FIXME: if the function has a type proclamation, it forces
803 ;;; a type-check every time the cache finds something. Instead, values should
804 ;;; be checked once only when inserted into the cache, and not when read out.
806 ;;; N.B.: it is not obvious that the intended use of an explicit MEMOIZE macro
807 ;;; is to call it exactly once or not at all. If you call it more than once,
808 ;;; then you inline all of its logic every time. Probably the code generated
809 ;;; by DEFINE-HASH-CACHE should be an FLET inside the body of DEFUN-CACHED,
810 ;;; but the division of labor is somewhat inverted at present.
811 ;;; Since we don't have caches that aren't in direct support of DEFUN-CACHED
812 ;;; - did we ever? - this should be possible to change.
814 (defmacro defun-cached ((name &rest options &key
815 (memoizer (make-symbol "MEMOIZE")
816 memoizer-supplied-p)
817 &allow-other-keys)
818 args &body body-decls-doc)
819 (binding* (((forms decls doc) (parse-body body-decls-doc t))
820 ((inputs aux-vars)
821 (let ((aux (member '&aux args)))
822 (if aux
823 (values (ldiff args aux) aux)
824 (values args nil))))
825 (arg-names (mapcar #'car inputs)))
826 `(progn
827 (!define-hash-cache ,name ,inputs ,aux-vars ,@options)
828 (defun ,name ,arg-names
829 ,@decls
830 ,@(if doc (list doc))
831 (macrolet ((,memoizer (&body body)
832 ;; We don't need (DX-FLET ((,thunk () ,@body)) ...)
833 ;; This lambda is a single-use local call within
834 ;; the inline memoizing wrapper.
835 `(,',(symbolicate "!" name "-MEMO-WRAPPER")
836 (lambda () ,@body) ,@',arg-names)))
837 ,@(if memoizer-supplied-p
838 forms
839 `((,memoizer ,@forms))))))))
841 ;;; FIXME: maybe not the best place
843 ;;; FIXME: think of a better name -- not only does this not have the
844 ;;; CAR recursion of EQUAL, it also doesn't have the special treatment
845 ;;; of pathnames, bit-vectors and strings.
847 ;;; KLUDGE: This means that we will no longer cache specifiers of the
848 ;;; form '(INTEGER (0) 4). This is probably not a disaster.
850 ;;; A helper function for the type system, which is the main user of
851 ;;; these caches: we must be more conservative than EQUAL for some of
852 ;;; our equality tests, because MEMBER and friends refer to EQLity.
853 ;;; So:
854 (defun equal-but-no-car-recursion (x y)
855 (do () (())
856 (cond ((eql x y) (return t))
857 ((and (consp x)
858 (consp y)
859 (eql (pop x) (pop y))))
861 (return)))))
863 ;;;; package idioms
865 ;;; Note: Almost always you want to use FIND-UNDELETED-PACKAGE-OR-LOSE
866 ;;; instead of this function. (The distinction only actually matters when
867 ;;; PACKAGE-DESIGNATOR is actually a deleted package, and in that case
868 ;;; you generally do want to signal an error instead of proceeding.)
869 (defun %find-package-or-lose (package-designator)
870 #-sb-xc-host(declare (optimize allow-non-returning-tail-call))
871 (or (find-package package-designator)
872 (error 'simple-package-error
873 :package package-designator
874 :format-control "The name ~S does not designate any package."
875 :format-arguments (list package-designator))))
877 ;;; ANSI specifies (in the section for FIND-PACKAGE) that the
878 ;;; consequences of most operations on deleted packages are
879 ;;; unspecified. We try to signal errors in such cases.
880 (defun find-undeleted-package-or-lose (package-designator)
881 #-sb-xc-host(declare (optimize allow-non-returning-tail-call))
882 (let ((maybe-result (%find-package-or-lose package-designator)))
883 (if (package-%name maybe-result) ; if not deleted
884 maybe-result
885 (error 'simple-package-error
886 :package maybe-result
887 :format-control "The package ~S has been deleted."
888 :format-arguments (list maybe-result)))))
890 ;;;; various operations on names
892 ;;; Is NAME a legal variable/function name?
893 (declaim (inline legal-variable-name-p))
894 (defun legal-variable-name-p (name)
895 (typep name '(and symbol (not keyword) (not null))))
897 (declaim (inline legal-fun-name-p))
898 (defun legal-fun-name-p (name)
899 (values (valid-function-name-p name)))
901 (deftype function-name () '(satisfies legal-fun-name-p))
903 ;;; Signal an error unless NAME is a legal function name.
904 (defun legal-fun-name-or-type-error (name)
905 #-sb-xc-host(declare (optimize allow-non-returning-tail-call))
906 (unless (legal-fun-name-p name)
907 (error 'simple-type-error
908 :datum name
909 :expected-type 'function-name
910 :format-control "Invalid function name: ~S"
911 :format-arguments (list name))))
913 ;;; Given a function name, return the symbol embedded in it.
915 ;;; The ordinary use for this operator (and the motivation for the
916 ;;; name of this operator) is to convert from a function name to the
917 ;;; name of the BLOCK which encloses its body.
919 ;;; Occasionally the operator is useful elsewhere, where the operator
920 ;;; name is less mnemonic. (Maybe it should be changed?)
921 (declaim (ftype (function ((or symbol cons)) symbol) fun-name-block-name))
922 (defun fun-name-block-name (fun-name)
923 (if (symbolp fun-name)
924 fun-name
925 (multiple-value-bind (legalp block-name)
926 (valid-function-name-p fun-name)
927 (if legalp
928 block-name
929 (error "not legal as a function name: ~S" fun-name)))))
931 (defun looks-like-name-of-special-var-p (x)
932 (and (symbolp x)
933 (symbol-package x)
934 (let ((name (symbol-name x)))
935 (and (> (length name) 2) ; to exclude '* and '**
936 (char= #\* (aref name 0))
937 (char= #\* (aref name (1- (length name))))))))
939 ;;;; ONCE-ONLY
940 ;;;;
941 ;;;; "The macro ONCE-ONLY has been around for a long time on various
942 ;;;; systems [..] if you can understand how to write and when to use
943 ;;;; ONCE-ONLY, then you truly understand macro." -- Peter Norvig,
944 ;;;; _Paradigms of Artificial Intelligence Programming: Case Studies
945 ;;;; in Common Lisp_, p. 853
947 ;;; ONCE-ONLY is a utility useful in writing source transforms and
948 ;;; macros. It provides a concise way to wrap a LET around some code
949 ;;; to ensure that some forms are only evaluated once.
951 ;;; Create a LET* which evaluates each value expression, binding a
952 ;;; temporary variable to the result, and wrapping the LET* around the
953 ;;; result of the evaluation of BODY. Within the body, each VAR is
954 ;;; bound to the corresponding temporary variable.
955 (defmacro once-only (specs &body body)
956 (named-let frob ((specs specs)
957 (body body))
958 (if (null specs)
959 `(progn ,@body)
960 (let ((spec (first specs)))
961 ;; FIXME: should just be DESTRUCTURING-BIND of SPEC
962 (unless (proper-list-of-length-p spec 2)
963 (error "malformed ONCE-ONLY binding spec: ~S" spec))
964 (let* ((name (first spec))
965 (exp-temp (gensym "ONCE-ONLY")))
966 `(let ((,exp-temp ,(second spec))
967 (,name (sb!xc:gensym ,(symbol-name name))))
968 `(let ((,,name ,,exp-temp))
969 ,,(frob (rest specs) body))))))))
971 ;;;; various error-checking utilities
973 ;;; This function can be used as the default value for keyword
974 ;;; arguments that must be always be supplied. Since it is known by
975 ;;; the compiler to never return, it will avoid any compile-time type
976 ;;; warnings that would result from a default value inconsistent with
977 ;;; the declared type. When this function is called, it signals an
978 ;;; error indicating that a required &KEY argument was not supplied.
979 ;;; This function is also useful for DEFSTRUCT slot defaults
980 ;;; corresponding to required arguments.
981 (declaim (ftype (function () #+(and sb-xc-host ccl) *
982 #-(and sb-xc-host ccl) nil) missing-arg))
983 (defun missing-arg ()
984 (/show0 "entering MISSING-ARG")
985 (error "A required &KEY or &OPTIONAL argument was not supplied."))
987 ;;; like CL:ASSERT and CL:CHECK-TYPE, but lighter-weight
989 ;;; (As of sbcl-0.6.11.20, we were using some 400 calls to CL:ASSERT.
990 ;;; The CL:ASSERT restarts and whatnot expand into a significant
991 ;;; amount of code when you multiply them by 400, so replacing them
992 ;;; with this should reduce the size of the system by enough to be
993 ;;; worthwhile.)
994 (defmacro aver (expr)
995 `(unless ,expr
996 (%failed-aver ',expr)))
998 (defun %failed-aver (expr)
999 (bug "~@<failed AVER: ~2I~_~S~:>" expr))
1001 (defun bug (format-control &rest format-arguments)
1002 (error 'bug
1003 :format-control format-control
1004 :format-arguments format-arguments))
1006 ;;; Return a function like FUN, but expecting its (two) arguments in
1007 ;;; the opposite order that FUN does.
1008 (declaim (inline swapped-args-fun))
1009 (defun swapped-args-fun (fun)
1010 (declare (type function fun))
1011 (lambda (x y)
1012 (funcall fun y x)))
1014 ;;; Return the numeric value of a type bound, i.e. an interval bound
1015 ;;; more or less in the format of bounds in ANSI's type specifiers,
1016 ;;; where a bare numeric value is a closed bound and a list of a
1017 ;;; single numeric value is an open bound.
1019 ;;; The "more or less" bit is that the no-bound-at-all case is
1020 ;;; represented by NIL (not by * as in ANSI type specifiers); and in
1021 ;;; this case we return NIL.
1022 (defun type-bound-number (x)
1023 (if (consp x)
1024 (destructuring-bind (result) x result)
1027 ;;; some commonly-occurring CONSTANTLY forms
1028 (macrolet ((def-constantly-fun (name constant-expr)
1029 `(progn
1030 (declaim (ftype (sfunction * (eql ,constant-expr)) ,name))
1031 (setf (symbol-function ',name)
1032 (constantly ,constant-expr)))))
1033 (def-constantly-fun constantly-t t)
1034 (def-constantly-fun constantly-nil nil)
1035 (def-constantly-fun constantly-0 0))
1037 ;;; If X is a symbol, see whether it is present in *FEATURES*. Also
1038 ;;; handle arbitrary combinations of atoms using NOT, AND, OR.
1039 (defun featurep (x)
1040 (typecase x
1041 (cons
1042 (case (car x)
1043 ((:not not)
1044 (cond
1045 ((cddr x)
1046 (error "too many subexpressions in feature expression: ~S" x))
1047 ((null (cdr x))
1048 (error "too few subexpressions in feature expression: ~S" x))
1049 (t (not (featurep (cadr x))))))
1050 ((:and and) (every #'featurep (cdr x)))
1051 ((:or or) (some #'featurep (cdr x)))
1053 (error "unknown operator in feature expression: ~S." x))))
1054 (symbol (not (null (memq x *features*))))
1056 (error "invalid feature expression: ~S" x))))
1059 ;;;; utilities for two-VALUES predicates
1061 (defmacro not/type (x)
1062 (let ((val (gensym "VAL"))
1063 (win (gensym "WIN")))
1064 `(multiple-value-bind (,val ,win)
1066 (if ,win
1067 (values (not ,val) t)
1068 (values nil nil)))))
1070 (defmacro and/type (x y)
1071 `(multiple-value-bind (val1 win1) ,x
1072 (if (and (not val1) win1)
1073 (values nil t)
1074 (multiple-value-bind (val2 win2) ,y
1075 (if (and val1 val2)
1076 (values t t)
1077 (values nil (and win2 (not val2))))))))
1079 ;;; sort of like ANY and EVERY, except:
1080 ;;; * We handle two-VALUES predicate functions, as SUBTYPEP does.
1081 ;;; (And if the result is uncertain, then we return (VALUES NIL NIL),
1082 ;;; as SUBTYPEP does.)
1083 ;;; * THING is just an atom, and we apply OP (an arity-2 function)
1084 ;;; successively to THING and each element of LIST.
1085 (defun any/type (op thing list)
1086 (declare (type function op))
1087 (let ((certain? t))
1088 (dolist (i list (values nil certain?))
1089 (multiple-value-bind (sub-value sub-certain?) (funcall op thing i)
1090 (if sub-certain?
1091 (when sub-value (return (values t t)))
1092 (setf certain? nil))))))
1093 (defun every/type (op thing list)
1094 (declare (type function op))
1095 (let ((certain? t))
1096 (dolist (i list (if certain? (values t t) (values nil nil)))
1097 (multiple-value-bind (sub-value sub-certain?) (funcall op thing i)
1098 (if sub-certain?
1099 (unless sub-value (return (values nil t)))
1100 (setf certain? nil))))))
1102 ;;;; DEFPRINTER
1104 ;;; These functions are called by the expansion of the DEFPRINTER
1105 ;;; macro to do the actual printing.
1106 (declaim (ftype (function (symbol t stream) (values))
1107 defprinter-prin1 defprinter-princ))
1108 (defun defprinter-prin1 (name value stream)
1109 (defprinter-prinx #'prin1 name value stream))
1110 (defun defprinter-princ (name value stream)
1111 (defprinter-prinx #'princ name value stream))
1112 (defun defprinter-prinx (prinx name value stream)
1113 (declare (type function prinx))
1114 (when *print-pretty*
1115 (pprint-newline :linear stream))
1116 (format stream ":~A " name)
1117 (funcall prinx value stream)
1118 (values))
1119 (defun defprinter-print-space (stream)
1120 (write-char #\space stream))
1122 ;;; Define some kind of reasonable PRINT-OBJECT method for a
1123 ;;; STRUCTURE-OBJECT class.
1125 ;;; NAME is the name of the structure class, and CONC-NAME is the same
1126 ;;; as in DEFSTRUCT.
1128 ;;; The SLOT-DESCS describe how each slot should be printed. Each
1129 ;;; SLOT-DESC can be a slot name, indicating that the slot should
1130 ;;; simply be printed. A SLOT-DESC may also be a list of a slot name
1131 ;;; and other stuff. The other stuff is composed of keywords followed
1132 ;;; by expressions. The expressions are evaluated with the variable
1133 ;;; which is the slot name bound to the value of the slot. These
1134 ;;; keywords are defined:
1136 ;;; :PRIN1 Print the value of the expression instead of the slot value.
1137 ;;; :PRINC Like :PRIN1, only PRINC the value
1138 ;;; :TEST Only print something if the test is true.
1140 ;;; If no printing thing is specified then the slot value is printed
1141 ;;; as if by PRIN1.
1143 ;;; The structure being printed is bound to STRUCTURE and the stream
1144 ;;; is bound to STREAM.
1145 (defmacro defprinter ((name
1146 &key
1147 (conc-name (concatenate 'simple-string
1148 (symbol-name name)
1149 "-"))
1150 identity)
1151 &rest slot-descs)
1152 (let ((first? t)
1153 maybe-print-space
1154 (reversed-prints nil)
1155 (stream (sb!xc:gensym "STREAM")))
1156 (flet ((sref (slot-name)
1157 `(,(symbolicate conc-name slot-name) structure)))
1158 (dolist (slot-desc slot-descs)
1159 (if first?
1160 (setf maybe-print-space nil
1161 first? nil)
1162 (setf maybe-print-space `(defprinter-print-space ,stream)))
1163 (cond ((atom slot-desc)
1164 (push maybe-print-space reversed-prints)
1165 (push `(defprinter-prin1 ',slot-desc ,(sref slot-desc) ,stream)
1166 reversed-prints))
1168 (let ((sname (first slot-desc))
1169 (test t))
1170 (collect ((stuff))
1171 (do ((option (rest slot-desc) (cddr option)))
1172 ((null option)
1173 (push `(let ((,sname ,(sref sname)))
1174 (when ,test
1175 ,maybe-print-space
1176 ,@(or (stuff)
1177 `((defprinter-prin1
1178 ',sname ,sname ,stream)))))
1179 reversed-prints))
1180 (case (first option)
1181 (:prin1
1182 (stuff `(defprinter-prin1
1183 ',sname ,(second option) ,stream)))
1184 (:princ
1185 (stuff `(defprinter-princ
1186 ',sname ,(second option) ,stream)))
1187 (:test (setq test (second option)))
1189 (error "bad option: ~S" (first option)))))))))))
1190 `(defmethod print-object ((structure ,name) ,stream)
1191 (pprint-logical-block (,stream nil)
1192 (print-unreadable-object (structure
1193 ,stream
1194 :type t
1195 :identity ,identity)
1196 ,@(nreverse reversed-prints))))))
1198 (defun print-symbol-with-prefix (stream symbol &optional colon at)
1199 "For use with ~/: Write SYMBOL to STREAM as if it is not accessible from
1200 the current package."
1201 (declare (ignore colon at))
1202 ;; Only keywords should be accessible from the keyword package, and
1203 ;; keywords are always printed with colons, so this guarantees that the
1204 ;; symbol will not be printed without a prefix.
1205 (let ((*package* *keyword-package*))
1206 (write symbol :stream stream :escape t)))
1208 (declaim (special sb!pretty:*pprint-quote-with-syntactic-sugar*))
1209 (defun print-type-specifier (stream type-specifier &optional colon at)
1210 (declare (ignore colon at))
1211 ;; Binding *PPRINT-QUOTE-WITH-SYNTACTIC-SUGAR* prevents certain
1212 ;; [f]types from being printed unhelpfully:
1214 ;; (function ()) => #'NIL
1215 ;; (function *) => #'*
1216 ;; (function (function a)) => #'#'A
1218 ;; Binding *PACKAGE* to the COMMON-LISP package causes specifiers
1219 ;; like CL:FUNCTION, CL:INTEGER, etc. to be printed without package
1220 ;; prefix but forces printing with package prefix for other
1221 ;; specifiers.
1222 (let ((sb!pretty:*pprint-quote-with-syntactic-sugar* nil)
1223 (*package* *cl-package*))
1224 (prin1 type-specifier stream)))
1226 (defun print-type (stream type &optional colon at)
1227 (print-type-specifier stream (type-specifier type) colon at))
1229 (declaim (ftype (sfunction (index &key (:comma-interval (and (integer 1) index))) index)
1230 decimal-with-grouped-digits-width))
1231 (defun decimal-with-grouped-digits-width (value &key (comma-interval 3))
1232 (let ((digits (length (write-to-string value :base 10))))
1233 (+ digits (floor (1- digits) comma-interval))))
1236 ;;;; etc.
1238 ;;; Given a pathname, return a corresponding physical pathname.
1239 (defun physicalize-pathname (possibly-logical-pathname)
1240 (if (typep possibly-logical-pathname 'logical-pathname)
1241 (translate-logical-pathname possibly-logical-pathname)
1242 possibly-logical-pathname))
1244 ;;;; Deprecating stuff
1246 (deftype deprecation-state ()
1247 '(member :early :late :final))
1249 (deftype deprecation-software-and-version ()
1250 '(or string (cons string (cons string null))))
1252 (defun normalize-deprecation-since (since)
1253 (unless (typep since 'deprecation-software-and-version)
1254 (error 'simple-type-error
1255 :datum since
1256 :expected-type 'deprecation-software-and-version
1257 :format-control "~@<The value ~S does not designate a ~
1258 version or a software name and a version.~@:>"
1259 :format-arguments (list since)))
1260 (if (typep since 'string)
1261 (values nil since)
1262 (values-list since)))
1264 (defun normalize-deprecation-replacements (replacements)
1265 (if (or (not (listp replacements))
1266 (eq 'setf (car replacements)))
1267 (list replacements)
1268 replacements))
1270 (defstruct (deprecation-info
1271 (:constructor make-deprecation-info
1272 (state software version &optional replacement-spec
1273 &aux
1274 (replacements (normalize-deprecation-replacements
1275 replacement-spec))))
1276 (:copier nil))
1277 (state (missing-arg) :type deprecation-state :read-only t)
1278 (software (missing-arg) :type (or null string) :read-only t)
1279 (version (missing-arg) :type string :read-only t)
1280 (replacements '() :type list :read-only t))
1282 ;; Return the state of deprecation of the thing identified by
1283 ;; NAMESPACE and NAME, or NIL.
1284 (defun deprecated-thing-p (namespace name)
1285 (multiple-value-bind (info infop)
1286 (ecase namespace
1287 (variable (info :variable :deprecated name))
1288 (function (info :function :deprecated name))
1289 (type (info :type :deprecated name)))
1290 (when infop
1291 (values (deprecation-info-state info)
1292 (list (deprecation-info-software info)
1293 (deprecation-info-version info))
1294 (deprecation-info-replacements info)))))
1296 ;;; Without a proclaimed type, the call is "untrusted" and so the compiler
1297 ;;; would generate a post-call check that the function did not return.
1298 (declaim (ftype (function (t t t t t) nil) deprecation-error))
1299 (defun deprecation-error (software version namespace name replacements)
1300 #-sb-xc-host(declare (optimize allow-non-returning-tail-call))
1301 (error 'deprecation-error
1302 :namespace namespace
1303 :name name
1304 :software software
1305 :version version
1306 :replacements (normalize-deprecation-replacements replacements)))
1308 (defun deprecation-warn (state software version namespace name replacements
1309 &key (runtime-error (neq :early state)))
1310 (warn (ecase state
1311 (:early 'early-deprecation-warning)
1312 (:late 'late-deprecation-warning)
1313 (:final 'final-deprecation-warning))
1314 :namespace namespace
1315 :name name
1316 :software software
1317 :version version
1318 :replacements (normalize-deprecation-replacements replacements)
1319 :runtime-error runtime-error))
1321 (defun check-deprecated-thing (namespace name)
1322 (multiple-value-bind (state since replacements)
1323 (deprecated-thing-p namespace name)
1324 (when state
1325 (deprecation-warn
1326 state (first since) (second since) namespace name replacements)
1327 (values state since replacements))))
1329 ;;; For-effect-only variant of CHECK-DEPRECATED-THING for
1330 ;;; type-specifiers that descends into compound type-specifiers.
1331 (defun %check-deprecated-type (type-specifier)
1332 (let ((seen '()))
1333 ;; KLUDGE: we have to use SPECIFIER-TYPE to sanely traverse
1334 ;; TYPE-SPECIFIER and detect references to deprecated types. But
1335 ;; then we may have to drop its cache to get the
1336 ;; PARSE-DEPRECATED-TYPE condition when TYPE-SPECIFIER is parsed
1337 ;; again later.
1339 ;; Proper fix would be a
1341 ;; walk-type function type-specifier
1343 ;; mechanism that could drive VALUES-SPECIFIER-TYPE but also
1344 ;; things like this function.
1345 (block nil
1346 (handler-bind
1347 ((sb!kernel::parse-deprecated-type
1348 (lambda (condition)
1349 (let ((type-specifier (sb!kernel::parse-deprecated-type-specifier
1350 condition)))
1351 (aver (symbolp type-specifier))
1352 (unless (memq type-specifier seen)
1353 (push type-specifier seen)
1354 (check-deprecated-thing 'type type-specifier)))))
1355 ((or error sb!kernel:parse-unknown-type)
1356 (lambda (condition)
1357 (declare (ignore condition))
1358 (return))))
1359 (specifier-type type-specifier)))))
1361 (defun check-deprecated-type (type-specifier)
1362 (typecase type-specifier
1363 ((or symbol cons)
1364 (%check-deprecated-type type-specifier))
1365 (class
1366 (let ((name (class-name type-specifier)))
1367 (when (and name (symbolp name)
1368 (eq type-specifier (find-class name nil)))
1369 (%check-deprecated-type name))))))
1371 ;; This is the moral equivalent of a warning from /usr/bin/ld that
1372 ;; "gets() is dangerous." You're informed by both the compiler and linker.
1373 (defun loader-deprecation-warn (stuff whence)
1374 ;; Stuff is a list: ((<state> name . category) ...)
1375 ;; For now we only deal with category = :FUNCTION so we ignore it.
1376 (let ((warning-class
1377 ;; We're only going to warn once (per toplevel form),
1378 ;; so pick the most stern warning applicable.
1379 (if (every (lambda (x) (eq (car x) :early)) stuff)
1380 'simple-style-warning 'simple-warning)))
1381 (warn warning-class
1382 :format-control "Reference to deprecated function~P ~S~@[ from ~S~]"
1383 :format-arguments
1384 (list (length stuff) (mapcar #'second stuff) whence))))
1386 ;;; STATE is one of
1388 ;;; :EARLY, for a compile-time style-warning.
1389 ;;; :LATE, for a compile-time full warning.
1390 ;;; :FINAL, for a compile-time full warning and runtime error.
1392 ;;; Suggested duration of each stage is one year, but some things can move faster,
1393 ;;; and some widely used legacy APIs might need to move slower. Internals we don't
1394 ;;; usually add deprecation notes for, but sometimes an internal API actually has
1395 ;;; several external users, in which case we try to be nice about it.
1397 ;;; When you deprecate something, note it here till it is fully gone: makes it
1398 ;;; easier to keep things progressing orderly. Also add the relevant section
1399 ;;; (or update it when deprecation proceeds) in the manual, in
1400 ;;; deprecated.texinfo.
1402 ;;; EARLY:
1403 ;;; - SOCKINT::WIN32-BIND since 1.2.10 (03/2015) -> Late: 08/2015
1404 ;;; - SOCKINT::WIN32-GETSOCKNAME since 1.2.10 (03/2015) -> Late: 08/2015
1405 ;;; - SOCKINT::WIN32-LISTEN since 1.2.10 (03/2015) -> Late: 08/2015
1406 ;;; - SOCKINT::WIN32-RECV since 1.2.10 (03/2015) -> Late: 08/2015
1407 ;;; - SOCKINT::WIN32-RECVFROM since 1.2.10 (03/2015) -> Late: 08/2015
1408 ;;; - SOCKINT::WIN32-SEND since 1.2.10 (03/2015) -> Late: 08/2015
1409 ;;; - SOCKINT::WIN32-SENDTO since 1.2.10 (03/2015) -> Late: 08/2015
1410 ;;; - SOCKINT::WIN32-CLOSE since 1.2.10 (03/2015) -> Late: 08/2015
1411 ;;; - SOCKINT::WIN32-CONNECT since 1.2.10 (03/2015) -> Late: 08/2015
1412 ;;; - SOCKINT::WIN32-GETPEERNAME since 1.2.10 (03/2015) -> Late: 08/2015
1413 ;;; - SOCKINT::WIN32-IOCTL since 1.2.10 (03/2015) -> Late: 08/2015
1414 ;;; - SOCKINT::WIN32-SETSOCKOPT since 1.2.10 (03/2015) -> Late: 08/2015
1415 ;;; - SOCKINT::WIN32-GETSOCKOPT since 1.2.10 (03/2015) -> Late: 08/2015
1417 ;;; - SB-C::MERGE-TAIL-CALLS (policy) since 1.0.53.74 (11/2011) -> Late: 11/2012
1419 ;;; LATE:
1420 ;;; - SB-C::STACK-ALLOCATE-DYNAMIC-EXTENT (policy) since 1.0.19.7 -> Final: anytime
1421 ;;; - SB-C::STACK-ALLOCATE-VECTOR (policy) since 1.0.19.7 -> Final: anytime
1422 ;;; - SB-C::STACK-ALLOCATE-VALUE-CELLS (policy) since 1.0.19.7 -> Final: anytime
1424 (defun print-deprecation-replacements (stream replacements &optional colonp atp)
1425 (declare (ignore colonp atp))
1426 ;; I don't think this is callable during cross-compilation, is it?
1427 (apply #'format stream
1428 "~#[~;~
1429 Use ~/sb-ext:print-symbol-with-prefix/ instead.~;~
1430 Use ~/sb-ext:print-symbol-with-prefix/ or ~
1431 ~/sb-ext:print-symbol-with-prefix/ instead.~:;~
1432 Use~@{~#[~; or~] ~
1433 ~/sb-ext:print-symbol-with-prefix/~^,~} instead.~
1435 replacements))
1437 (defun print-deprecation-message (namespace name software version
1438 &optional replacements stream)
1439 (format stream
1440 "The ~(~A~) ~/sb!impl:print-symbol-with-prefix/ has been ~
1441 deprecated as of ~@[~A ~]version ~A.~
1442 ~@[~2%~/sb!impl::print-deprecation-replacements/~]"
1443 namespace name software version replacements))
1445 (defun setup-function-in-final-deprecation
1446 (software version name replacement-spec)
1447 #+sb-xc-host (declare (ignore software version name replacement-spec))
1448 #-sb-xc-host
1449 (setf (fdefinition name)
1450 (sb!impl::set-closure-name
1451 (lambda (&rest args)
1452 (declare (ignore args))
1453 (deprecation-error software version 'function name replacement-spec))
1455 name)))
1457 (defun setup-variable-in-final-deprecation
1458 (software version name replacement-spec)
1459 (sb!c::%define-symbol-macro
1460 name
1461 `(deprecation-error
1462 ,software ,version 'variable ',name
1463 (list ,@(mapcar
1464 (lambda (replacement)
1465 `',replacement)
1466 (normalize-deprecation-replacements replacement-spec))))
1467 nil))
1469 (defun setup-type-in-final-deprecation
1470 (software version name replacement-spec)
1471 (declare (ignore software version replacement-spec))
1472 (%compiler-deftype name (constant-type-expander name t) nil))
1474 (defmacro define-deprecated-function (state version name replacements lambda-list
1475 &body body)
1476 (declare (type deprecation-state state)
1477 (type string version)
1478 (type function-name name)
1479 (type (or function-name list) replacements)
1480 (type list lambda-list)
1481 #+sb-xc-host (ignore version replacements))
1482 `(progn
1483 #-sb-xc-host
1484 (declaim (deprecated
1485 ,state ("SBCL" ,version)
1486 (function ,name ,@(when replacements
1487 `(:replacement ,replacements)))))
1488 ,(ecase state
1489 ((:early :late)
1490 `(defun ,name ,lambda-list
1491 ,@body))
1492 ((:final)
1493 `',name))))
1495 (defmacro define-deprecated-variable (state version name
1496 &key (value nil valuep) replacement)
1497 (declare (type deprecation-state state)
1498 (type string version)
1499 (type symbol name)
1500 #+sb-xc-host (ignore version replacement))
1501 `(progn
1502 #-sb-xc-host
1503 (declaim (deprecated
1504 ,state ("SBCL" ,version)
1505 (variable ,name ,@(when replacement
1506 `(:replacement ,replacement)))))
1507 ,(ecase state
1508 ((:early :late)
1509 `(defvar ,name ,@(when valuep (list value))))
1510 ((:final)
1511 `',name))))
1513 ;; Given DECLS as returned by from parse-body, and SYMBOLS to be bound
1514 ;; (with LET, MULTIPLE-VALUE-BIND, etc) return two sets of declarations:
1515 ;; those which pertain to the variables and those which don't.
1516 ;; The first returned value is NIL or a single expression headed by DECLARE.
1517 ;; The second is a list of expressions resembling the input DECLS.
1518 (defun extract-var-decls (decls symbols)
1519 (unless symbols ; Don't bother filtering DECLS, just return them.
1520 (return-from extract-var-decls (values nil decls)))
1521 (labels ((applies-to-variables (decl)
1522 ;; If DECL is a variable-affecting declaration, then return
1523 ;; the subset of SYMBOLS to which DECL applies.
1524 (let ((id (car decl)))
1525 (remove-if (lambda (x) (not (memq x symbols)))
1526 (cond ((eq id 'type)
1527 (cddr decl))
1528 ((or (listp id) ; must be a type-specifier
1529 (memq id '(special ignorable ignore
1530 dynamic-extent
1531 truly-dynamic-extent))
1532 (info :type :kind id))
1533 (cdr decl))))))
1534 (partition (spec)
1535 ;; If SPEC is a declaration affecting some variables in SYMBOLS
1536 ;; and some not, split it into two mutually exclusive declarations.
1537 (acond ((applies-to-variables spec)
1538 (multiple-value-bind (decl-head all-symbols)
1539 (if (eq (car spec) 'type)
1540 (values `(type ,(cadr spec)) (cddr spec))
1541 (values `(,(car spec)) (cdr spec)))
1542 (let ((more (set-difference all-symbols it)))
1543 (values `(,@decl-head ,@it)
1544 (and more `(,@decl-head ,@more))))))
1546 (values nil spec)))))
1547 ;; This loop is less inefficient than theoretically possible,
1548 ;; reconstructing the tree even if no need,
1549 ;; but it's just a macroexpander, so... fine.
1550 (collect ((binding-decls))
1551 (let ((filtered
1552 (mapcar (lambda (decl-expr) ; a list headed by DECLARE
1553 (mapcan (lambda (spec)
1554 (multiple-value-bind (binding other)
1555 (partition spec)
1556 (when binding
1557 (binding-decls binding))
1558 (if other (list other))))
1559 (cdr decl-expr)))
1560 decls)))
1561 (values (awhen (binding-decls) `(declare ,@it))
1562 (mapcan (lambda (x) (if x (list `(declare ,@x)))) filtered))))))
1564 ;;; Delayed evaluation
1565 (defmacro delay (form)
1566 `(cons nil (lambda () ,form)))
1568 (defun force (promise)
1569 (cond ((not (consp promise)) promise)
1570 ((car promise) (cdr promise))
1571 (t (setf (car promise) t
1572 (cdr promise) (funcall (cdr promise))))))
1574 (defun promise-ready-p (promise)
1575 (or (not (consp promise))
1576 (car promise)))
1578 ;;; toplevel helper
1579 (defmacro with-rebound-io-syntax (&body body)
1580 `(%with-rebound-io-syntax (lambda () ,@body)))
1582 (defun %with-rebound-io-syntax (function)
1583 (declare (type function function))
1584 (let ((*package* *package*)
1585 (*print-array* *print-array*)
1586 (*print-base* *print-base*)
1587 (*print-case* *print-case*)
1588 (*print-circle* *print-circle*)
1589 (*print-escape* *print-escape*)
1590 (*print-gensym* *print-gensym*)
1591 (*print-length* *print-length*)
1592 (*print-level* *print-level*)
1593 (*print-lines* *print-lines*)
1594 (*print-miser-width* *print-miser-width*)
1595 (*print-pretty* *print-pretty*)
1596 (*print-radix* *print-radix*)
1597 (*print-readably* *print-readably*)
1598 (*print-right-margin* *print-right-margin*)
1599 (*read-base* *read-base*)
1600 (*read-default-float-format* *read-default-float-format*)
1601 (*read-eval* *read-eval*)
1602 (*read-suppress* *read-suppress*)
1603 (*readtable* *readtable*))
1604 (funcall function)))
1606 ;;; Bind a few "potentially dangerous" printer control variables to
1607 ;;; safe values, respecting current values if possible.
1608 (defmacro with-sane-io-syntax (&body forms)
1609 `(call-with-sane-io-syntax (lambda () ,@forms)))
1611 (defun call-with-sane-io-syntax (function)
1612 (declare (type function function))
1613 (macrolet ((true (sym)
1614 `(and (boundp ',sym) ,sym)))
1615 (let ((*print-readably* nil)
1616 (*print-level* (or (true *print-level*) 6))
1617 (*print-length* (or (true *print-length*) 12)))
1618 (funcall function))))
1620 ;;; Returns a list of members of LIST. Useful for dealing with circular lists.
1621 ;;; For a dotted list returns a secondary value of T -- in which case the
1622 ;;; primary return value does not include the dotted tail.
1623 ;;; If the maximum length is reached, return a secondary value of :MAYBE.
1624 (defun list-members (list &key max-length)
1625 (when list
1626 (do ((tail (cdr list) (cdr tail))
1627 (members (list (car list)) (cons (car tail) members))
1628 (count 0 (1+ count)))
1629 ((or (not (consp tail)) (eq tail list)
1630 (and max-length (>= count max-length)))
1631 (values members (or (not (listp tail))
1632 (and (>= count max-length) :maybe)))))))
1634 ;;; Default evaluator mode (interpeter / compiler)
1636 (declaim (type (member :compile #!+(or sb-eval sb-fasteval) :interpret)
1637 *evaluator-mode*))
1638 (!defparameter *evaluator-mode* :compile
1639 "Toggle between different evaluator implementations. If set to :COMPILE,
1640 an implementation of EVAL that calls the compiler will be used. If set
1641 to :INTERPRET, an interpreter will be used.")
1643 ;; This is not my preferred name for this function, but chosen for harmony
1644 ;; with everything else that refers to these as 'hash-caches'.
1645 ;; Hashing is just one particular way of memoizing, and it would have been
1646 ;; slightly more abstract and yet at the same time more concrete to say
1647 ;; "memoized-function-caches". "hash-caches" is pretty nonspecific.
1648 #.(if *profile-hash-cache*
1649 '(defun show-hash-cache-statistics ()
1650 (flet ((cache-stats (symbol)
1651 (let* ((name (string symbol))
1652 (statistics (let ((*package* (symbol-package symbol)))
1653 (symbolicate symbol "STATISTICS")))
1654 (prefix
1655 (subseq name 0 (- (length name) (length "VECTOR**")))))
1656 (values (if (boundp statistics)
1657 (symbol-value statistics)
1658 (make-array 3 :element-type 'fixnum))
1659 (subseq prefix 2 (1- (length prefix)))))))
1660 (format t "~%Type function memoization:~% Seek Hit (%)~:
1661 Evict (%) Size full~%")
1662 ;; Sort by descending seek count to rank by likely relative importance
1663 (dolist (symbol (sort (copy-list *cache-vector-symbols*) #'>
1664 :key (lambda (x) (aref (cache-stats x) 0))))
1665 (binding* (((stats short-name) (cache-stats symbol))
1666 (seek (aref stats 0))
1667 (miss (aref stats 1))
1668 (hit (- seek miss))
1669 (evict (aref stats 2))
1670 (cache (symbol-value symbol)))
1671 (format t "~9d ~9d (~5,1f%) ~8d (~5,1f%) ~4d ~6,1f% ~A~%"
1672 seek hit
1673 (if (plusp seek) (* 100 (/ hit seek)))
1674 evict
1675 (if (plusp seek) (* 100 (/ evict seek)))
1676 (length cache)
1677 (if (plusp (length cache))
1678 (* 100 (/ (count-if-not #'fixnump cache)
1679 (length cache))))
1680 short-name))))))
1682 (in-package "SB!KERNEL")
1684 (defun fp-zero-p (x)
1685 (typecase x
1686 (single-float (zerop x))
1687 (double-float (zerop x))
1688 #!+long-float
1689 (long-float (zerop x))
1690 (t nil)))
1692 (defun neg-fp-zero (x)
1693 (etypecase x
1694 (single-float
1695 (if (eql x 0.0f0)
1696 (make-unportable-float :single-float-negative-zero)
1697 0.0f0))
1698 (double-float
1699 (if (eql x 0.0d0)
1700 (make-unportable-float :double-float-negative-zero)
1701 0.0d0))
1702 #!+long-float
1703 (long-float
1704 (if (eql x 0.0l0)
1705 (make-unportable-float :long-float-negative-zero)
1706 0.0l0))))
1708 (declaim (inline schwartzian-stable-sort-list))
1709 (defun schwartzian-stable-sort-list (list comparator &key key)
1710 (if (null key)
1711 (stable-sort (copy-list list) comparator)
1712 (let* ((key (if (functionp key)
1714 (symbol-function key)))
1715 (wrapped (mapcar (lambda (x)
1716 (cons x (funcall key x)))
1717 list))
1718 (sorted (stable-sort wrapped comparator :key #'cdr)))
1719 (map-into sorted #'car sorted))))
1721 ;;; Just like WITH-OUTPUT-TO-STRING but doesn't close the stream,
1722 ;;; producing more compact code.
1723 (defmacro with-simple-output-to-string
1724 ((var &optional string)
1725 &body body)
1726 (multiple-value-bind (forms decls) (parse-body body nil)
1727 (if string
1728 `(let ((,var (sb!impl::make-fill-pointer-output-stream ,string)))
1729 ,@decls
1730 ,@forms)
1731 `(let ((,var #+sb-xc-host (make-string-output-stream)
1732 #-sb-xc-host (sb!impl::%make-string-output-stream
1733 (or #!-sb-unicode 'character :default)
1734 #'sb!impl::string-ouch)))
1736 ,@decls
1737 ,@forms
1738 (get-output-stream-string ,var)))))
1740 ;;; Ensure basicness if possible, and simplicity always
1741 (defun possibly-base-stringize (s)
1742 (declare (string s))
1743 (cond #!+(and sb-unicode (host-feature sb-xc))
1744 ((and (typep s '(array character (*))) (every #'base-char-p s))
1745 (coerce s 'base-string))
1747 (coerce s 'simple-string))))
1749 (defun self-evaluating-p (x)
1750 (typecase x
1751 (null t)
1752 (symbol (or (eq x t) (eq (symbol-package x) *keyword-package*)))
1753 (cons nil)
1754 (t t)))