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