1 ;;;; various extensions (including SB-INT "internal extensions")
2 ;;;; available both in the cross-compilation host Lisp and in the
5 ;;;; This software is part of the SBCL system. See the README file for
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
18 "The absolute pathname of the running SBCL core.")
20 (defvar *runtime-pathname
* nil
22 "The absolute pathname of the running SBCL runtime.")
24 ;;; something not EQ to anything we might legitimately READ
25 (defglobal *eof-object
* (make-symbol "EOF-OBJECT"))
27 (eval-when (:compile-toplevel
:load-toplevel
:execute
)
28 (defconstant max-hash sb
!xc
:most-positive-fixnum
))
31 `(integer 0 ,max-hash
))
33 ;;; a type used for indexing into sequences, and for related
34 ;;; quantities like lengths of lists and other sequences.
36 ;;; A more correct value for the exclusive upper bound for indexing
37 ;;; would be (1- ARRAY-DIMENSION-LIMIT) since ARRAY-DIMENSION-LIMIT is
38 ;;; the exclusive maximum *size* of one array dimension (As specified
39 ;;; in CLHS entries for MAKE-ARRAY and "valid array dimensions"). The
40 ;;; current value is maintained to avoid breaking existing code that
41 ;;; also uses that type for upper bounds on indices (e.g. sequence
44 ;;; In SBCL, ARRAY-DIMENSION-LIMIT is arranged to be a little smaller
45 ;;; than MOST-POSITIVE-FIXNUM, for implementation (see comment above
46 ;;; ARRAY-DIMENSION-LIMIT) and efficiency reasons: staying below
47 ;;; MOST-POSITIVE-FIXNUM lets the system know it can increment a value
48 ;;; of type INDEX without having to worry about using a bignum to
49 ;;; represent the result.
50 (def!type index
() `(integer 0 (,sb
!xc
:array-dimension-limit
)))
52 ;;; like INDEX, but only up to half the maximum. Used by hash-table
53 ;;; code that does plenty to (aref v (* 2 i)) and (aref v (1+ (* 2 i))).
54 (def!type index
/2 () `(integer 0 (,(floor sb
!xc
:array-dimension-limit
2))))
56 ;;; like INDEX, but augmented with -1 (useful when using the index
57 ;;; to count downwards to 0, e.g. LOOP FOR I FROM N DOWNTO 0, with
58 ;;; an implementation which terminates the loop by testing for the
59 ;;; index leaving the loop range)
60 (def!type index-or-minus-1
() `(integer -
1 (,sb
!xc
:array-dimension-limit
)))
62 ;;; A couple of VM-related types that are currently used only on the
63 ;;; alpha platform. -- CSR, 2002-06-24
64 (def!type unsigned-byte-with-a-bite-out
(s bite
)
65 (cond ((eq s
'*) 'integer
)
66 ((and (integerp s
) (> s
0))
67 (let ((bound (ash 1 s
)))
68 `(integer 0 ,(- bound bite
1))))
70 (error "Bad size specified for UNSIGNED-BYTE type specifier: ~S." s
))))
72 ;;; Motivated by the mips port. -- CSR, 2002-08-22
73 (def!type signed-byte-with-a-bite-out
(s bite
)
74 (cond ((eq s
'*) 'integer
)
75 ((and (integerp s
) (> s
1))
76 (let ((bound (ash 1 (1- s
))))
77 `(integer ,(- bound
) ,(- bound bite
1))))
79 (error "Bad size specified for SIGNED-BYTE type specifier: ~S." s
))))
81 (def!type load
/store-index
(scale lowtag min-offset
82 &optional
(max-offset min-offset
))
83 `(integer ,(- (truncate (+ (ash 1 16)
84 (* min-offset sb
!vm
:n-word-bytes
)
87 ,(truncate (- (+ (1- (ash 1 16)) lowtag
)
88 (* max-offset sb
!vm
:n-word-bytes
))
92 (defun displacement-bounds (lowtag element-size data-offset
)
93 (let* ((adjustment (- (* data-offset sb
!vm
:n-word-bytes
) lowtag
))
94 (bytes-per-element (ceiling element-size sb
!vm
:n-byte-bits
))
95 (min (truncate (+ sb
!vm
::minimum-immediate-offset adjustment
)
97 (max (truncate (+ sb
!vm
::maximum-immediate-offset adjustment
)
102 (def!type constant-displacement
(lowtag element-size data-offset
)
103 (flet ((integerify (x)
106 (symbol (symbol-value x
)))))
107 (let ((lowtag (integerify lowtag
))
108 (element-size (integerify element-size
))
109 (data-offset (integerify data-offset
)))
110 (multiple-value-bind (min max
) (displacement-bounds lowtag
113 `(integer ,min
,max
)))))
115 ;;; Similar to FUNCTION, but the result type is "exactly" specified:
116 ;;; if it is an object type, then the function returns exactly one
117 ;;; value, if it is a short form of VALUES, then this short form
118 ;;; specifies the exact number of values.
119 (def!type sfunction
(args &optional result
)
120 (let ((result (cond ((eq result
'*) '*)
122 (not (eq (car result
) 'values
)))
123 `(values ,result
&optional
))
124 ((intersection (cdr result
) sb
!xc
:lambda-list-keywords
)
126 (t `(values ,@(cdr result
) &optional
)))))
127 `(function ,args
,result
)))
131 ;;; FIXME: The SB!KERNEL:INSTANCE here really means CL:CLASS.
132 ;;; However, the CL:CLASS type is only defined once PCL is loaded,
133 ;;; which is before this is evaluated. Once PCL is moved into cold
134 ;;; init, this might be fixable.
135 (def!type type-specifier
() '(or list symbol instance
))
137 ;;; the default value used for initializing character data. The ANSI
138 ;;; spec says this is arbitrary, so we use the value that falls
139 ;;; through when we just let the low-level consing code initialize
140 ;;; all newly-allocated memory to zero.
142 ;;; KLUDGE: It might be nice to use something which is a
143 ;;; STANDARD-CHAR, both to reduce user surprise a little and, probably
144 ;;; more significantly, to help SBCL's cross-compiler (which knows how
145 ;;; to dump STANDARD-CHARs). Unfortunately, the old CMU CL code is
146 ;;; shot through with implicit assumptions that it's #\NULL, and code
147 ;;; in several places (notably both DEFUN MAKE-ARRAY and DEFTRANSFORM
148 ;;; MAKE-ARRAY) would have to be rewritten. -- WHN 2001-10-04
149 (eval-when (:compile-toplevel
:load-toplevel
:execute
)
150 ;; an expression we can use to construct a DEFAULT-INIT-CHAR value
151 ;; at load time (so that we don't need to teach the cross-compiler
152 ;; how to represent and dump non-STANDARD-CHARs like #\NULL)
153 (defparameter *default-init-char-form
* '(code-char 0)))
155 ;;; CHAR-CODE values for ASCII characters which we care about but
156 ;;; which aren't defined in section "2.1.3 Standard Characters" of the
157 ;;; ANSI specification for Lisp
159 ;;; KLUDGE: These are typically used in the idiom (CODE-CHAR
160 ;;; FOO-CHAR-CODE). I suspect that the current implementation is
161 ;;; expanding this idiom into a full call to CODE-CHAR, which is an
162 ;;; annoying overhead. I should check whether this is happening, and
163 ;;; if so, perhaps implement a DEFTRANSFORM or something to stop it.
164 ;;; (or just find a nicer way of expressing characters portably?) --
166 (def!constant bell-char-code
7)
167 (def!constant backspace-char-code
8)
168 (def!constant tab-char-code
9)
169 (def!constant line-feed-char-code
10)
170 (def!constant form-feed-char-code
12)
171 (def!constant return-char-code
13)
172 (def!constant escape-char-code
27)
173 (def!constant rubout-char-code
127)
175 ;;;; type-ish predicates
177 ;;; X may contain cycles -- a conservative approximation. This
178 ;;; occupies a somewhat uncomfortable niche between being fast for
179 ;;; common cases (we don't want to allocate a hash-table), and not
180 ;;; falling down to exponential behaviour for large trees (so we set
181 ;;; an arbitrady depth limit beyond which we punt).
182 (defun maybe-cyclic-p (x &optional
(depth-limit 12))
184 (labels ((safe-cddr (cons)
185 (let ((cdr (cdr cons
)))
188 (check-cycle (object seen depth
)
189 (when (and (consp object
)
190 (or (> depth depth-limit
)
192 (circularp object seen depth
)))
193 (return-from maybe-cyclic-p t
)))
194 (circularp (list seen depth
)
195 ;; Almost regular circular list detection, with a twist:
196 ;; we also check each element of the list for upward
197 ;; references using CHECK-CYCLE.
198 (do ((fast (cons (car list
) (cdr list
)) (safe-cddr fast
))
199 (slow list
(cdr slow
)))
201 ;; Not CDR-circular, need to check remaining CARs yet
202 (do ((tail slow
(and (cdr tail
))))
205 (check-cycle (car tail
) (cons tail seen
) (1+ depth
))))
206 (check-cycle (car slow
) (cons slow seen
) (1+ depth
))
209 (circularp x
(list x
) 0))))
211 ;;; Is X a (possibly-improper) list of at least N elements?
212 (declaim (ftype (function (t index
)) list-of-length-at-least-p
))
213 (defun list-of-length-at-least-p (x n
)
214 (or (zerop n
) ; since anything can be considered an improper list of length 0
216 (list-of-length-at-least-p (cdr x
) (1- n
)))))
218 ;;; Is X is a positive prime integer?
219 (defun positive-primep (x)
220 ;; This happens to be called only from one place in sbcl-0.7.0, and
221 ;; only for fixnums, we can limit it to fixnums for efficiency. (And
222 ;; if we didn't limit it to fixnums, we should use a cleverer
223 ;; algorithm, since this one scales pretty badly for huge X.)
226 (and (>= x
2) (/= x
4))
228 (not (zerop (rem x
3)))
231 (inc 2 (logxor inc
6)) ;; 2,4,2,4...
233 ((or (= r
0) (> d q
)) (/= r
0))
234 (declare (fixnum inc
))
235 (multiple-value-setq (q r
) (truncate x d
))))))
237 ;;; Could this object contain other objects? (This is important to
238 ;;; the implementation of things like *PRINT-CIRCLE* and the dumper.)
239 (defun compound-object-p (x)
242 (typep x
'(array t
*))))
244 ;;;; the COLLECT macro
246 ;;;; comment from CMU CL: "the ultimate collection macro..."
248 ;;; helper functions for COLLECT, which become the expanders of the
249 ;;; MACROLET definitions created by COLLECT
251 ;;; COLLECT-NORMAL-EXPANDER handles normal collection macros.
253 ;;; COLLECT-LIST-EXPANDER handles the list collection case. N-TAIL
254 ;;; is the pointer to the current tail of the list, or NIL if the list
256 (eval-when (#-sb-xc
:compile-toplevel
:load-toplevel
:execute
)
257 (defun collect-normal-expander (n-value fun forms
)
259 ,@(mapcar (lambda (form) `(setq ,n-value
(,fun
,form
,n-value
))) forms
)
261 (defun collect-list-expander (n-value n-tail forms
)
262 (let ((n-res (gensym)))
264 ,@(mapcar (lambda (form)
265 `(let ((,n-res
(cons ,form nil
)))
267 (setf (cdr ,n-tail
) ,n-res
)
268 (setq ,n-tail
,n-res
))
270 (setq ,n-tail
,n-res
,n-value
,n-res
)))))
274 ;;; Collect some values somehow. Each of the collections specifies a
275 ;;; bunch of things which collected during the evaluation of the body
276 ;;; of the form. The name of the collection is used to define a local
277 ;;; macro, a la MACROLET. Within the body, this macro will evaluate
278 ;;; each of its arguments and collect the result, returning the
279 ;;; current value after the collection is done. The body is evaluated
280 ;;; as a PROGN; to get the final values when you are done, just call
281 ;;; the collection macro with no arguments.
283 ;;; INITIAL-VALUE is the value that the collection starts out with,
284 ;;; which defaults to NIL. FUNCTION is the function which does the
285 ;;; collection. It is a function which will accept two arguments: the
286 ;;; value to be collected and the current collection. The result of
287 ;;; the function is made the new value for the collection. As a
288 ;;; totally magical special-case, FUNCTION may be COLLECT, which tells
289 ;;; us to build a list in forward order; this is the default. If an
290 ;;; INITIAL-VALUE is supplied for COLLECT, the stuff will be RPLACD'd
291 ;;; onto the end. Note that FUNCTION may be anything that can appear
292 ;;; in the functional position, including macros and lambdas.
293 (defmacro collect
(collections &body body
)
297 (dolist (spec collections
)
298 (unless (proper-list-of-length-p spec
1 3)
299 (error "malformed collection specifier: ~S" spec
))
300 (let* ((name (first spec
))
301 (default (second spec
))
302 (kind (or (third spec
) 'collect
))
303 (n-value (gensym (concatenate 'string
306 (push `(,n-value
,default
) binds
)
307 (if (eq kind
'collect
)
308 (let ((n-tail (gensym (concatenate 'string
311 (push n-tail ignores
)
313 (push `(,n-tail
(last ,n-value
)) binds
)
315 (push `(,name
(&rest args
)
316 (collect-list-expander ',n-value
',n-tail args
))
318 (push `(,name
(&rest args
)
319 (collect-normal-expander ',n-value
',kind args
))
322 (let* ,(nreverse binds
)
323 ;; Even if the user reads each collection result,
324 ;; reader conditionals might statically eliminate all writes.
325 ;; Since we don't know, all the -n-tail variable are ignorable.
326 ,@(if ignores
`((declare (ignorable ,@ignores
))))
329 ;;;; some old-fashioned functions. (They're not just for old-fashioned
330 ;;;; code, they're also used as optimized forms of the corresponding
331 ;;;; general functions when the compiler can prove that they're
334 ;;; like (MEMBER ITEM LIST :TEST #'EQ)
335 (defun memq (item list
)
337 "Return tail of LIST beginning with first element EQ to ITEM."
338 ;; KLUDGE: These could be and probably should be defined as
339 ;; (MEMBER ITEM LIST :TEST #'EQ)),
340 ;; but when I try to cross-compile that, I get an error from
341 ;; LTN-ANALYZE-KNOWN-CALL, "Recursive known function definition". The
342 ;; comments for that error say it "is probably a botched interpreter stub".
343 ;; Rather than try to figure that out, I just rewrote this function from
344 ;; scratch. -- WHN 19990512
345 (do ((i list
(cdr i
)))
347 (when (eq (car i
) item
)
350 ;;; like (ASSOC ITEM ALIST :TEST #'EQ):
351 ;;; Return the first pair of ALIST where ITEM is EQ to the key of
353 (defun assq (item alist
)
354 ;; KLUDGE: CMU CL defined this with
355 ;; (DECLARE (INLINE ASSOC))
356 ;; (ASSOC ITEM ALIST :TEST #'EQ))
357 ;; which is pretty, but which would have required adding awkward
358 ;; build order constraints on SBCL (or figuring out some way to make
359 ;; inline definitions installable at build-the-cross-compiler time,
360 ;; which was too ambitious for now). Rather than mess with that, we
361 ;; just define ASSQ explicitly in terms of more primitive
364 ;; though it may look more natural to write this as
365 ;; (AND PAIR (EQ (CAR PAIR) ITEM))
366 ;; the temptation to do so should be resisted, as pointed out by PFD
367 ;; sbcl-devel 2003-08-16, as NIL elements are rare in association
368 ;; lists. -- CSR, 2003-08-16
369 (when (and (eq (car pair
) item
) (not (null pair
)))
372 ;;; like (DELETE .. :TEST #'EQ):
373 ;;; Delete all LIST entries EQ to ITEM (destructively modifying
374 ;;; LIST), and return the modified LIST.
375 (defun delq (item list
)
377 (do ((x list
(cdr x
))
380 (cond ((eq item
(car x
))
383 (rplacd splice
(cdr x
))))
384 (t (setq splice x
)))))) ; Move splice along to include element.
387 ;;; like (POSITION .. :TEST #'EQ):
388 ;;; Return the position of the first element EQ to ITEM.
389 (defun posq (item list
)
390 (do ((i list
(cdr i
))
393 (when (eq (car i
) item
)
396 (declaim (inline neq
))
400 ;;; not really an old-fashioned function, but what the calling
401 ;;; convention should've been: like NTH, but with the same argument
402 ;;; order as in all the other indexed dereferencing functions, with
403 ;;; the collection first and the index second
404 (declaim (inline nth-but-with-sane-arg-order
))
405 (declaim (ftype (function (list index
) t
) nth-but-with-sane-arg-order
))
406 (defun nth-but-with-sane-arg-order (list index
)
409 (defun adjust-list (list length initial-element
)
410 (let ((old-length (length list
)))
411 (cond ((< old-length length
)
412 (append list
(make-list (- length old-length
)
413 :initial-element initial-element
)))
414 ((> old-length length
)
415 (subseq list
0 length
))
418 ;;;; miscellaneous iteration extensions
420 ;;; like Scheme's named LET
422 ;;; (CMU CL called this ITERATE, and commented it as "the ultimate
423 ;;; iteration macro...". I (WHN) found the old name insufficiently
424 ;;; specific to remind me what the macro means, so I renamed it.)
425 (defmacro named-let
(name binds
&body body
)
427 (unless (proper-list-of-length-p x
2)
428 (error "malformed NAMED-LET variable spec: ~S" x
)))
429 `(labels ((,name
,(mapcar #'first binds
) ,@body
))
430 (,name
,@(mapcar #'second binds
))))
432 (defun filter-dolist-declarations (decls)
433 (mapcar (lambda (decl)
434 `(declare ,@(remove-if
437 (or (eq (car clause
) 'type
)
438 (eq (car clause
) 'ignore
))))
441 ;;; just like DOLIST, but with one-dimensional arrays
442 (defmacro dovector
((elt vector
&optional result
) &body body
)
443 (multiple-value-bind (forms decls
) (parse-body body
:doc-string-allowed nil
)
444 (with-unique-names (index length vec
)
445 `(let ((,vec
,vector
))
446 (declare (type vector
,vec
))
447 (do ((,index
0 (1+ ,index
))
448 (,length
(length ,vec
)))
449 ((>= ,index
,length
) (let ((,elt nil
))
450 ,@(filter-dolist-declarations decls
)
453 (let ((,elt
(aref ,vec
,index
)))
458 ;;; Iterate over the entries in a HASH-TABLE, first obtaining the lock
459 ;;; if the table is a synchronized table.
460 (defmacro dohash
(((key-var value-var
) table
&key result locked
) &body body
)
461 (multiple-value-bind (forms decls
) (parse-body body
:doc-string-allowed nil
)
462 (with-unique-names (gen n-more n-table
)
463 (let ((iter-form `(with-hash-table-iterator (,gen
,n-table
)
465 (multiple-value-bind (,n-more
,key-var
,value-var
) (,gen
)
467 (unless ,n-more
(return ,result
))
469 `(let ((,n-table
,table
))
471 `(with-locked-system-table (,n-table
)
475 ;;; Executes BODY for all entries of PLIST with KEY and VALUE bound to
476 ;;; the respective keys and values.
477 (defmacro doplist
((key val
) plist
&body body
)
478 (with-unique-names (tail)
479 `(let ((,tail
,plist
) ,key
,val
)
480 (loop (when (null ,tail
) (return nil
))
481 (setq ,key
(pop ,tail
))
483 (error "malformed plist, odd number of elements"))
484 (setq ,val
(pop ,tail
))
487 ;;; (binding* ({(names initial-value [flag])}*) body)
488 ;;; FLAG may be NIL or :EXIT-IF-NULL
490 ;;; This form unites LET*, MULTIPLE-VALUE-BIND and AWHEN.
491 ;;; Any name in a list of names may be NIL to ignore the respective value.
492 ;;; If NAMES itself is nil, the initial-value form is evaluated only for effect.
494 ;;; Clauses with no flag and one binding are equivalent to LET.
496 ;;; Caution: don't use declarations of the form (<non-builtin-type-id> <var>)
497 ;;; before the INFO database is set up in building the cross-compiler,
498 ;;; or you will probably lose.
499 ;;; Of course, since some other host Lisps don't seem to think that's
500 ;;; acceptable syntax anyway, you're pretty much prevented from writing it.
502 (def!macro binding
* ((&rest clauses
) &body body
)
503 (unless clauses
; wrap in LET to preserve non-toplevelness
504 (return-from binding
* `(let () ,@body
)))
505 (multiple-value-bind (body decls
) (parse-body body
:doc-string-allowed nil
)
506 ;; Generate an abstract representation that combines LET* clauses.
508 (dolist (clause clauses
)
509 (destructuring-bind (symbols value-form
&optional flag
) clause
510 (declare (type (member :exit-if-null nil
) flag
))
513 (cond ((not (listp symbols
)) (list symbols
))
514 ((not symbols
) (setq ignore
(list (gensym))))
516 (lambda (x) (or x
(car (push (gensym) ignore
))))
518 (flags (logior (if (cdr symbols
) 1 0) (if flag
2 0)))
520 ;; EVENP => this clause does not entail multiple-value-bind
521 (cond ((and (evenp flags
) (eql (car last
) 0))
522 (setf (first last
) flags
)
523 (push (car symbols
) (second last
))
524 (push value-form
(third last
))
525 (setf (fourth last
) (nconc ignore
(fourth last
))))
527 (push (list flags symbols
(list value-form
) ignore
)
529 ;; Starting with the innermost binding clause, snarf out the
530 ;; applicable declarations. (Clauses are currently reversed)
531 (dolist (abstract-clause repr
)
533 (multiple-value-bind (binding-decls remaining-decls
)
534 (extract-var-decls decls
(second abstract-clause
))
535 (setf (cddddr abstract-clause
) binding-decls
)
536 (setf decls remaining-decls
))))
537 ;; Generate sexprs from inside out.
538 (loop with listp
= t
; BODY is already a list
539 for
(flags symbols values ignore . binding-decls
) in repr
540 ;; Maybe test the last bound symbol in the clause for LET*
541 ;; or 1st symbol for mv-bind. Either way, the first of SYMBOLS.
542 for inner
= (if (logtest flags
2) ; :EXIT-IF-NULL was specified.
543 (prog1 `(when ,(car symbols
)
544 ,@(if listp body
(list body
)))
548 `(,.
(if (evenp flags
)
549 `(let* ,(nreverse (mapcar #'list symbols values
)))
550 `(multiple-value-bind ,symbols
,(car values
)))
551 ,@(when binding-decls
(list binding-decls
))
552 ,@(when ignore
`((declare (ignorable ,@ignore
))))
553 ,@decls
; anything leftover
554 ,@(if listp inner
(list inner
)))
559 ;;;; hash cache utility
561 (eval-when (:compile-toplevel
:load-toplevel
:execute
)
562 (defvar *profile-hash-cache
* nil
))
564 ;;; Define a hash cache that associates some number of argument values
565 ;;; with a result value. The TEST-FUNCTION paired with each ARG-NAME
566 ;;; is used to compare the value for that arg in a cache entry with a
567 ;;; supplied arg. The TEST-FUNCTION must not error when passed NIL as
568 ;;; its first arg, but need not return any particular value.
569 ;;; TEST-FUNCTION may be any thing that can be placed in CAR position.
571 ;;; This code used to store all the arguments / return values directly
572 ;;; in the cache vector. This was both interrupt- and thread-unsafe, since
573 ;;; it was possible that *-CACHE-ENTER would scribble over a region of the
574 ;;; cache vector which *-CACHE-LOOKUP had only partially processed. Instead
575 ;;; we now store the contents of each cache bucket as a separate array, which
576 ;;; is stored in the appropriate cell in the cache vector. A new bucket array
577 ;;; is created every time *-CACHE-ENTER is called, and the old ones are never
578 ;;; modified. This means that *-CACHE-LOOKUP will always work with a set
579 ;;; of consistent data. The overhead caused by consing new buckets seems to
580 ;;; be insignificant on the grand scale of things. -- JES, 2006-11-02
582 ;;; NAME is used to define these functions:
583 ;;; <name>-CACHE-LOOKUP Arg*
584 ;;; See whether there is an entry for the specified ARGs in the
585 ;;; cache. If not present, the :DEFAULT keyword (default NIL)
586 ;;; determines the result(s).
587 ;;; <name>-CACHE-ENTER Arg* Value*
588 ;;; Encache the association of the specified args with VALUE.
589 ;;; <name>-CACHE-CLEAR
590 ;;; Reinitialize the cache, invalidating all entries and allowing
591 ;;; the arguments and result values to be GC'd.
593 ;;; These other keywords are defined:
595 ;;; The size of the cache as a power of 2.
596 ;;; :HASH-FUNCTION function
597 ;;; Some thing that can be placed in CAR position which will compute
598 ;;; a fixnum with at least (* 2 <hash-bits>) of information in it.
600 ;;; the number of return values cached for each function call
601 (defvar *cache-vector-symbols
* nil
)
603 (defun drop-all-hash-caches ()
604 (dolist (name *cache-vector-symbols
*)
607 ;; Make a new hash-cache and optionally create the statistics vector.
608 (defun alloc-hash-cache (size symbol
)
610 ;; It took me a while to figure out why infinite recursion could occur
611 ;; in VALUES-SPECIFIER-TYPE. It's because SET calls VALUES-SPECIFIER-TYPE.
612 (macrolet ((set! (symbol value
)
614 #-sb-xc-host sb
!kernel
:%set-symbol-global-value
617 ;; If statistics gathering is not not compiled-in,
618 ;; no sense in setting a symbol that is never used.
619 ;; While this uses SYMBOLICATE at runtime,
620 ;; it is inconsequential to performance.
621 (if *profile-hash-cache
*
623 (let ((*package
* (symbol-package symbol
)))
624 (symbolicate symbol
"STATISTICS"))))
625 (unless (boundp statistics
)
627 (make-array 3 :element-type
'fixnum
628 :initial-contents
'(1 0 0))))))))
629 ;; It would be bad if another thread sees MAKE-ARRAY's result in the
630 ;; global variable before the vector's header+length have been set.
631 ;; Without a barrier, this would be theoretically possible if the
632 ;; architecture allows out-of-order memory writes.
633 (sb!thread
:barrier
(:write
)
635 (setq cache
(make-array size
:initial-element
0)))
636 (set! symbol cache
))))
638 ;; At present we make a new vector every time a line is re-written,
639 ;; to make it thread-safe and interrupt-safe. A multi-word compare-and-swap
640 ;; is tricky to code and stronger than we need. It is possible instead
641 ;; to provide multi-word reads that can detect failure of atomicity,
642 ;; and on x86 it's possible to have atomic double-wide read/write,
643 ;; so a 1-arg/1-result cache line needn't cons at all except once
644 ;; (and maybe not even that if we make the cache into pairs of cells).
645 ;; But this way is easier to understand, for now anyway.
646 (eval-when (#-sb-xc
:compile-toplevel
:load-toplevel
:execute
)
647 (defun hash-cache-line-allocator (n)
648 (aref #.
(coerce (loop for i from
2 to
6
649 collect
(symbolicate "ALLOC-HASH-CACHE-LINE/"
650 (char "23456" (- i
2))))
654 (let* ((ftype `(sfunction ,(make-list n
:initial-element t
) t
))
655 (fn (hash-cache-line-allocator n
))
656 (args (make-gensym-list n
)))
658 (declaim (ftype ,ftype
,fn
))
660 (declare (optimize (safety 0)))
663 `(vector ,@args
)))))))
670 (defmacro !define-hash-cache
(name args
671 &key hash-function hash-bits memoizer
673 (declare (ignore memoizer
))
675 (unless (= (length arg
) 2)
676 (error "bad argument spec: ~S" arg
)))
677 (assert (typep hash-bits
'(integer 5 14))) ; reasonable bounds
678 (let* ((fun-name (symbolicate name
"-MEMO-WRAPPER"))
679 (var-name (symbolicate "**" name
"-CACHE-VECTOR**"))
681 (when *profile-hash-cache
*
682 (symbolicate var-name
"STATISTICS")))
683 (nargs (length args
))
684 (size (ash 1 hash-bits
))
685 (hashval (make-symbol "HASH"))
686 (cache (make-symbol "CACHE"))
687 (entry (make-symbol "LINE"))
688 (thunk (make-symbol "THUNK"))
689 (arg-vars (mapcar #'first args
))
690 (result-temps (loop for i from
1 to values
691 collect
(make-symbol (format nil
"RES~D" i
))))
692 (temps (append (mapcar (lambda (x) (make-symbol (string x
)))
695 (tests (mapcar (lambda (arg temp
) ; -> (EQx ARG #:ARG)
696 `(,(cadr arg
) ,(car arg
) ,temp
))
698 (cache-type `(simple-vector ,size
))
699 (line-type (let ((n (+ nargs values
)))
700 (if (<= n
3) 'cons
`(simple-vector ,n
))))
703 (2 `((,(first temps
) (car ,entry
))
704 (,(second temps
) (cdr ,entry
))))
705 (3 (let ((arg-temp (sb!xc
:gensym
"ARGS")))
706 `((,arg-temp
(cdr ,entry
))
707 (,(first temps
) (car ,entry
))
708 (,(second temps
) (car (truly-the cons
,arg-temp
)))
709 (,(third temps
) (cdr ,arg-temp
)))))
710 (t (loop for i from
0 for x in temps
711 collect
`(,x
(svref ,entry
,i
))))))
713 `(defun ,fun-name
(,thunk
,@arg-vars
)
714 ,@(when *profile-hash-cache
* ; count seeks
715 `((when (boundp ',statistics-name
)
716 (incf (aref ,statistics-name
0)))))
717 (let ((,hashval
(the (signed-byte #.sb
!vm
:n-fixnum-bits
)
718 (funcall ,hash-function
,@arg-vars
)))
721 (let ((,hashval
,hashval
))
722 (declare (type (signed-byte #.sb
!vm
:n-fixnum-bits
) ,hashval
))
724 (let ((,entry
(svref (truly-the ,cache-type
,cache
)
725 (ldb (byte ,hash-bits
0) ,hashval
))))
726 (unless (eql ,entry
0)
727 ;; This barrier is a no-op on all multi-threaded SBCL
728 ;; architectures. No CPU except Alpha will move a read
729 ;; prior to a read on which it depends.
730 (sb!thread
:barrier
(:data-dependency
))
731 (locally (declare (type ,line-type
,entry
))
734 (return-from ,fun-name
735 (values ,@result-temps
))))))
736 (setq ,hashval
(ash ,hashval
,(- hash-bits
)))))))
737 (multiple-value-bind ,result-temps
(funcall ,thunk
)
739 (,(hash-cache-line-allocator (+ nargs values
))
740 ,@arg-vars
,@result-temps
))
742 (truly-the ,cache-type
743 (or ,cache
(alloc-hash-cache ,size
',var-name
))))
744 (idx1 (ldb (byte ,hash-bits
0) ,hashval
))
745 (idx2 (ldb (byte ,hash-bits
,hash-bits
) ,hashval
)))
746 ,@(when *profile-hash-cache
*
747 `((incf (aref ,statistics-name
1)))) ; count misses
748 ;; Why a barrier: the pointer to 'entry' (a cons or vector)
749 ;; MUST NOT be observed by another thread before its cells
750 ;; are filled. Equally bad, the 'output' cells in the line
751 ;; could be 0 while the 'input' cells matched something.
752 (sb!thread
:barrier
(:write
))
753 (cond ((eql (svref ,cache idx1
) 0)
754 (setf (svref ,cache idx1
) ,entry
))
755 ((eql (svref ,cache idx2
) 0)
756 (setf (svref ,cache idx2
) ,entry
))
758 ,@(when *profile-hash-cache
* ; count evictions
759 `((incf (aref ,statistics-name
2))))
760 (setf (svref ,cache idx1
) ,entry
))))
761 (values ,@result-temps
))))))
763 (pushnew ',var-name
*cache-vector-symbols
*)
764 (defglobal ,var-name nil
)
765 ,@(when *profile-hash-cache
*
766 `((declaim (type (simple-array fixnum
(3)) ,statistics-name
))
767 (defvar ,statistics-name
)))
768 (declaim (type (or null
,cache-type
) ,var-name
))
769 (defun ,(symbolicate name
"-CACHE-CLEAR") () (setq ,var-name nil
))
770 (declaim (inline ,fun-name
))
773 ;;; some syntactic sugar for defining a function whose values are
774 ;;; cached by !DEFINE-HASH-CACHE
775 ;;; These keywords are mostly defined at !DEFINE-HASH-CACHE.
776 ;;; Additional options:
778 ;;; If provided, it is the name of a local macro that must be called
779 ;;; within the body forms to perform cache lookup/insertion.
780 ;;; If not provided, then the function's behavior is to automatically
781 ;;; attempt cache lookup, and on miss, execute the body code and
782 ;;; insert into the cache.
783 ;;; Manual control over memoization is useful if there are cases for
784 ;;; which computing the result is simpler than cache lookup.
786 (defmacro defun-cached
((name &rest options
&key
787 (memoizer (make-symbol "MEMOIZE")
790 args
&body body-decls-doc
)
791 (binding* (((forms decls doc
) (parse-body body-decls-doc
))
792 (arg-names (mapcar #'car args
)))
794 (!define-hash-cache
,name
,args
,@options
)
795 (defun ,name
,arg-names
797 ,@(if doc
(list doc
))
798 (macrolet ((,memoizer
(&body body
)
799 ;; We don't need (DX-FLET ((,thunk () ,@body)) ...)
800 ;; This lambda is a single-use local call within
801 ;; the inline memoizing wrapper.
802 `(,',(symbolicate name
"-MEMO-WRAPPER")
803 (lambda () ,@body
) ,@',arg-names
)))
804 ,@(if memoizer-supplied-p
806 `((,memoizer
,@forms
))))))))
808 ;;; FIXME: maybe not the best place
810 ;;; FIXME: think of a better name -- not only does this not have the
811 ;;; CAR recursion of EQUAL, it also doesn't have the special treatment
812 ;;; of pathnames, bit-vectors and strings.
814 ;;; KLUDGE: This means that we will no longer cache specifiers of the
815 ;;; form '(INTEGER (0) 4). This is probably not a disaster.
817 ;;; A helper function for the type system, which is the main user of
818 ;;; these caches: we must be more conservative than EQUAL for some of
819 ;;; our equality tests, because MEMBER and friends refer to EQLity.
821 (defun equal-but-no-car-recursion (x y
)
823 (cond ((eql x y
) (return t
))
826 (eql (pop x
) (pop y
))))
832 ;;; Note: Almost always you want to use FIND-UNDELETED-PACKAGE-OR-LOSE
833 ;;; instead of this function. (The distinction only actually matters when
834 ;;; PACKAGE-DESIGNATOR is actually a deleted package, and in that case
835 ;;; you generally do want to signal an error instead of proceeding.)
836 (defun %find-package-or-lose
(package-designator)
837 (or (find-package package-designator
)
838 (error 'simple-package-error
839 :package package-designator
840 :format-control
"The name ~S does not designate any package."
841 :format-arguments
(list package-designator
))))
843 ;;; ANSI specifies (in the section for FIND-PACKAGE) that the
844 ;;; consequences of most operations on deleted packages are
845 ;;; unspecified. We try to signal errors in such cases.
846 (defun find-undeleted-package-or-lose (package-designator)
847 (let ((maybe-result (%find-package-or-lose package-designator
)))
848 (if (package-name maybe-result
) ; if not deleted
850 (error 'simple-package-error
851 :package maybe-result
852 :format-control
"The package ~S has been deleted."
853 :format-arguments
(list maybe-result
)))))
855 ;;;; various operations on names
857 ;;; Is NAME a legal function name?
858 (declaim (inline legal-fun-name-p
))
859 (defun legal-fun-name-p (name)
860 (values (valid-function-name-p name
)))
862 (deftype function-name
() '(satisfies legal-fun-name-p
))
864 ;;; Signal an error unless NAME is a legal function name.
865 (defun legal-fun-name-or-type-error (name)
866 (unless (legal-fun-name-p name
)
867 (error 'simple-type-error
869 :expected-type
'function-name
870 :format-control
"invalid function name: ~S"
871 :format-arguments
(list name
))))
873 ;;; Given a function name, return the symbol embedded in it.
875 ;;; The ordinary use for this operator (and the motivation for the
876 ;;; name of this operator) is to convert from a function name to the
877 ;;; name of the BLOCK which encloses its body.
879 ;;; Occasionally the operator is useful elsewhere, where the operator
880 ;;; name is less mnemonic. (Maybe it should be changed?)
881 (declaim (ftype (function ((or symbol cons
)) symbol
) fun-name-block-name
))
882 (defun fun-name-block-name (fun-name)
883 (if (symbolp fun-name
)
885 (multiple-value-bind (legalp block-name
)
886 (valid-function-name-p fun-name
)
889 (error "not legal as a function name: ~S" fun-name
)))))
891 (defun looks-like-name-of-special-var-p (x)
894 (let ((name (symbol-name x
)))
895 (and (> (length name
) 2) ; to exclude '* and '**
896 (char= #\
* (aref name
0))
897 (char= #\
* (aref name
(1- (length name
))))))))
901 ;;;; "The macro ONCE-ONLY has been around for a long time on various
902 ;;;; systems [..] if you can understand how to write and when to use
903 ;;;; ONCE-ONLY, then you truly understand macro." -- Peter Norvig,
904 ;;;; _Paradigms of Artificial Intelligence Programming: Case Studies
905 ;;;; in Common Lisp_, p. 853
907 ;;; ONCE-ONLY is a utility useful in writing source transforms and
908 ;;; macros. It provides a concise way to wrap a LET around some code
909 ;;; to ensure that some forms are only evaluated once.
911 ;;; Create a LET* which evaluates each value expression, binding a
912 ;;; temporary variable to the result, and wrapping the LET* around the
913 ;;; result of the evaluation of BODY. Within the body, each VAR is
914 ;;; bound to the corresponding temporary variable.
915 (defmacro once-only
(specs &body body
)
916 (named-let frob
((specs specs
)
920 (let ((spec (first specs
)))
921 ;; FIXME: should just be DESTRUCTURING-BIND of SPEC
922 (unless (proper-list-of-length-p spec
2)
923 (error "malformed ONCE-ONLY binding spec: ~S" spec
))
924 (let* ((name (first spec
))
925 (exp-temp (gensym "ONCE-ONLY")))
926 `(let ((,exp-temp
,(second spec
))
927 (,name
(sb!xc
:gensym
,(symbol-name name
))))
928 `(let ((,,name
,,exp-temp
))
929 ,,(frob (rest specs
) body
))))))))
931 ;;;; various error-checking utilities
933 ;;; This function can be used as the default value for keyword
934 ;;; arguments that must be always be supplied. Since it is known by
935 ;;; the compiler to never return, it will avoid any compile-time type
936 ;;; warnings that would result from a default value inconsistent with
937 ;;; the declared type. When this function is called, it signals an
938 ;;; error indicating that a required &KEY argument was not supplied.
939 ;;; This function is also useful for DEFSTRUCT slot defaults
940 ;;; corresponding to required arguments.
941 (declaim (ftype (function () nil
) missing-arg
))
942 (defun missing-arg ()
944 (/show0
"entering MISSING-ARG")
945 (error "A required &KEY or &OPTIONAL argument was not supplied."))
947 ;;; like CL:ASSERT and CL:CHECK-TYPE, but lighter-weight
949 ;;; (As of sbcl-0.6.11.20, we were using some 400 calls to CL:ASSERT.
950 ;;; The CL:ASSERT restarts and whatnot expand into a significant
951 ;;; amount of code when you multiply them by 400, so replacing them
952 ;;; with this should reduce the size of the system by enough to be
953 ;;; worthwhile. ENFORCE-TYPE is much less common, but might still be
954 ;;; worthwhile, and since I don't really like CERROR stuff deep in the
955 ;;; guts of complex systems anyway, I replaced it too.)
956 (defmacro aver
(expr)
958 (%failed-aver
',expr
)))
960 (defun %failed-aver
(expr)
961 ;; hackish way to tell we're in a cold sbcl and output the
962 ;; message before signalling error, as it may be this is too
963 ;; early in the cold init.
964 (when (find-package "SB!C")
966 (write-line "failed AVER:")
969 (bug "~@<failed AVER: ~2I~_~A~:>" expr
))
971 (defun bug (format-control &rest format-arguments
)
973 :format-control format-control
974 :format-arguments format-arguments
))
976 (defmacro enforce-type
(value type
)
977 (once-only ((value value
))
978 `(unless (typep ,value
',type
)
979 (%failed-enforce-type
,value
',type
))))
981 (defun %failed-enforce-type
(value type
)
982 ;; maybe should be TYPE-BUG, subclass of BUG? If it is changed,
983 ;; check uses of it in user-facing code (e.g. WARN)
984 (error 'simple-type-error
987 :format-control
"~@<~S ~_is not a ~_~S~:>"
988 :format-arguments
(list value type
)))
990 ;;; Return a function like FUN, but expecting its (two) arguments in
991 ;;; the opposite order that FUN does.
992 (declaim (inline swapped-args-fun
))
993 (defun swapped-args-fun (fun)
994 (declare (type function fun
))
998 ;;; Return the numeric value of a type bound, i.e. an interval bound
999 ;;; more or less in the format of bounds in ANSI's type specifiers,
1000 ;;; where a bare numeric value is a closed bound and a list of a
1001 ;;; single numeric value is an open bound.
1003 ;;; The "more or less" bit is that the no-bound-at-all case is
1004 ;;; represented by NIL (not by * as in ANSI type specifiers); and in
1005 ;;; this case we return NIL.
1006 (defun type-bound-number (x)
1008 (destructuring-bind (result) x result
)
1011 ;;; some commonly-occuring CONSTANTLY forms
1012 (macrolet ((def-constantly-fun (name constant-expr
)
1013 `(setf (symbol-function ',name
)
1014 (constantly ,constant-expr
))))
1015 (def-constantly-fun constantly-t t
)
1016 (def-constantly-fun constantly-nil nil
)
1017 (def-constantly-fun constantly-0
0))
1019 ;;; If X is a symbol, see whether it is present in *FEATURES*. Also
1020 ;;; handle arbitrary combinations of atoms using NOT, AND, OR.
1028 (error "too many subexpressions in feature expression: ~S" x
))
1030 (error "too few subexpressions in feature expression: ~S" x
))
1031 (t (not (featurep (cadr x
))))))
1032 ((:and and
) (every #'featurep
(cdr x
)))
1033 ((:or or
) (some #'featurep
(cdr x
)))
1035 (error "unknown operator in feature expression: ~S." x
))))
1036 (symbol (not (null (memq x
*features
*))))
1038 (error "invalid feature expression: ~S" x
))))
1041 ;;;; utilities for two-VALUES predicates
1043 (defmacro not
/type
(x)
1044 (let ((val (gensym "VAL"))
1045 (win (gensym "WIN")))
1046 `(multiple-value-bind (,val
,win
)
1049 (values (not ,val
) t
)
1050 (values nil nil
)))))
1052 (defmacro and
/type
(x y
)
1053 `(multiple-value-bind (val1 win1
) ,x
1054 (if (and (not val1
) win1
)
1056 (multiple-value-bind (val2 win2
) ,y
1059 (values nil
(and win2
(not val2
))))))))
1061 ;;; sort of like ANY and EVERY, except:
1062 ;;; * We handle two-VALUES predicate functions, as SUBTYPEP does.
1063 ;;; (And if the result is uncertain, then we return (VALUES NIL NIL),
1064 ;;; as SUBTYPEP does.)
1065 ;;; * THING is just an atom, and we apply OP (an arity-2 function)
1066 ;;; successively to THING and each element of LIST.
1067 (defun any/type
(op thing list
)
1068 (declare (type function op
))
1070 (dolist (i list
(values nil certain?
))
1071 (multiple-value-bind (sub-value sub-certain?
) (funcall op thing i
)
1073 (when sub-value
(return (values t t
)))
1074 (setf certain? nil
))))))
1075 (defun every/type
(op thing list
)
1076 (declare (type function op
))
1078 (dolist (i list
(if certain?
(values t t
) (values nil nil
)))
1079 (multiple-value-bind (sub-value sub-certain?
) (funcall op thing i
)
1081 (unless sub-value
(return (values nil t
)))
1082 (setf certain? nil
))))))
1086 ;;; These functions are called by the expansion of the DEFPRINTER
1087 ;;; macro to do the actual printing.
1088 (declaim (ftype (function (symbol t stream
) (values))
1089 defprinter-prin1 defprinter-princ
))
1090 (defun defprinter-prin1 (name value stream
)
1091 (defprinter-prinx #'prin1 name value stream
))
1092 (defun defprinter-princ (name value stream
)
1093 (defprinter-prinx #'princ name value stream
))
1094 (defun defprinter-prinx (prinx name value stream
)
1095 (declare (type function prinx
))
1096 (when *print-pretty
*
1097 (pprint-newline :linear stream
))
1098 (format stream
":~A " name
)
1099 (funcall prinx value stream
)
1101 (defun defprinter-print-space (stream)
1102 (write-char #\space stream
))
1104 ;;; Define some kind of reasonable PRINT-OBJECT method for a
1105 ;;; STRUCTURE-OBJECT class.
1107 ;;; NAME is the name of the structure class, and CONC-NAME is the same
1108 ;;; as in DEFSTRUCT.
1110 ;;; The SLOT-DESCS describe how each slot should be printed. Each
1111 ;;; SLOT-DESC can be a slot name, indicating that the slot should
1112 ;;; simply be printed. A SLOT-DESC may also be a list of a slot name
1113 ;;; and other stuff. The other stuff is composed of keywords followed
1114 ;;; by expressions. The expressions are evaluated with the variable
1115 ;;; which is the slot name bound to the value of the slot. These
1116 ;;; keywords are defined:
1118 ;;; :PRIN1 Print the value of the expression instead of the slot value.
1119 ;;; :PRINC Like :PRIN1, only PRINC the value
1120 ;;; :TEST Only print something if the test is true.
1122 ;;; If no printing thing is specified then the slot value is printed
1125 ;;; The structure being printed is bound to STRUCTURE and the stream
1126 ;;; is bound to STREAM.
1127 (defmacro defprinter
((name
1129 (conc-name (concatenate 'simple-string
1136 (reversed-prints nil
)
1137 (stream (sb!xc
:gensym
"STREAM")))
1138 (flet ((sref (slot-name)
1139 `(,(symbolicate conc-name slot-name
) structure
)))
1140 (dolist (slot-desc slot-descs
)
1142 (setf maybe-print-space nil
1144 (setf maybe-print-space
`(defprinter-print-space ,stream
)))
1145 (cond ((atom slot-desc
)
1146 (push maybe-print-space reversed-prints
)
1147 (push `(defprinter-prin1 ',slot-desc
,(sref slot-desc
) ,stream
)
1150 (let ((sname (first slot-desc
))
1153 (do ((option (rest slot-desc
) (cddr option
)))
1155 (push `(let ((,sname
,(sref sname
)))
1160 ',sname
,sname
,stream
)))))
1162 (case (first option
)
1164 (stuff `(defprinter-prin1
1165 ',sname
,(second option
) ,stream
)))
1167 (stuff `(defprinter-princ
1168 ',sname
,(second option
) ,stream
)))
1169 (:test
(setq test
(second option
)))
1171 (error "bad option: ~S" (first option
)))))))))))
1172 `(sb!xc
:defmethod
print-object ((structure ,name
) ,stream
)
1173 (pprint-logical-block (,stream nil
)
1174 (print-unreadable-object (structure
1177 :identity
,identity
)
1178 ,@(nreverse reversed-prints
))))))
1180 (defun print-symbol-with-prefix (stream symbol
&optional colon at
)
1182 "For use with ~/: Write SYMBOL to STREAM as if it is not accessible from
1183 the current package."
1184 (declare (ignore colon at
))
1185 ;; Only keywords should be accessible from the keyword package, and
1186 ;; keywords are always printed with colons, so this guarantees that the
1187 ;; symbol will not be printed without a prefix.
1188 (let ((*package
* *keyword-package
*))
1189 (write symbol
:stream stream
:escape t
)))
1193 ;;; Given a pathname, return a corresponding physical pathname.
1194 (defun physicalize-pathname (possibly-logical-pathname)
1195 (if (typep possibly-logical-pathname
'logical-pathname
)
1196 (translate-logical-pathname possibly-logical-pathname
)
1197 possibly-logical-pathname
))
1199 ;;;; Deprecating stuff
1201 (defun normalize-deprecation-replacements (replacements)
1202 (if (or (not (listp replacements
))
1203 (eq 'setf
(car replacements
)))
1207 (defun deprecation-error (since name replacements
)
1208 (error 'deprecation-error
1210 :replacements
(normalize-deprecation-replacements replacements
)
1213 (defun deprecation-warning (state since name replacements
1214 &key
(runtime-error (neq :early state
)))
1216 (:early
'early-deprecation-warning
)
1217 (:late
'late-deprecation-warning
)
1218 (:final
'final-deprecation-warning
))
1220 :replacements
(normalize-deprecation-replacements replacements
)
1222 :runtime-error runtime-error
))
1224 (defun deprecated-function (since name replacements
&optional doc
)
1226 ;; setting the name is mildly redundant since the closure captures
1227 ;; its name. However %FUN-DOC can't make use of that fact.
1229 (lambda (&rest deprecated-function-args
)
1230 (declare (ignore deprecated-function-args
))
1231 (deprecation-error since name replacements
))
1234 (setf (%fun-doc closure
) doc
))
1237 (defun deprecation-compiler-macro (state since name replacements
)
1238 ;; this lambda's name is significant - see DEPRECATED-THING-P
1239 (named-lambda .deprecation-warning.
(form env
)
1240 (declare (ignore env
))
1241 (deprecation-warning state since name replacements
)
1244 ;; Return the stage of deprecation of thing identified by KIND and NAME, or NIL.
1245 (defun deprecated-thing-p (kind name
)
1248 (let ((macro-fun (info :function
:compiler-macro-function name
)))
1249 (and (closurep macro-fun
)
1250 (eq (%fun-name macro-fun
) '.deprecation-warning.
)
1251 ;; If you name a function literally :EARLY and it happens to
1252 ;; be in :LATE deprecation, then this could be wrong; etc.
1253 ;; But come on now ... who would name a function like that?
1254 (find-if-in-closure (lambda (x) (member x
'(:early
:late
:final
)))
1257 ;; This is the moral equivalent of a warning from /usr/bin/ld that
1258 ;; "gets() is dangerous." You're informed by both the compiler and linker.
1259 (defun loader-deprecation-warn (stuff whence
)
1260 ;; Stuff is a list: ((<state> name . category) ...)
1261 ;; For now we only deal with category = :FUNCTION so we ignore it.
1262 (let ((warning-class
1263 ;; We're only going to warn once (per toplevel form),
1264 ;; so pick the most stern warning applicable.
1265 (if (every (lambda (x) (eq (car x
) :early
)) stuff
)
1266 'simple-style-warning
'simple-warning
)))
1268 :format-control
"Reference to deprecated function~P ~S~@[ from ~S~]"
1270 (list (length stuff
) (mapcar #'second stuff
) whence
))))
1274 ;;; :EARLY, for a compile-time style-warning.
1275 ;;; :LATE, for a compile-time full warning.
1276 ;;; :FINAL, for a compile-time full warning and runtime error.
1278 ;;; Suggested duration of each stage is one year, but some things can move faster,
1279 ;;; and some widely used legacy APIs might need to move slower. Internals we don't
1280 ;;; usually add deprecation notes for, but sometimes an internal API actually has
1281 ;;; several external users, in which case we try to be nice about it.
1283 ;;; When you deprecate something, note it here till it is fully gone: makes it
1284 ;;; easier to keep things progressing orderly. Also add the relevant section
1285 ;;; (or update it when deprecation proceeds) in the manual, in
1286 ;;; deprecated.texinfo.
1289 ;;; - SOCKINT::WIN32-BIND since 1.2.10 (03/2015) -> Late: 08/2015
1290 ;;; - SOCKINT::WIN32-GETSOCKNAME since 1.2.10 (03/2015) -> Late: 08/2015
1291 ;;; - SOCKINT::WIN32-LISTEN since 1.2.10 (03/2015) -> Late: 08/2015
1292 ;;; - SOCKINT::WIN32-RECV since 1.2.10 (03/2015) -> Late: 08/2015
1293 ;;; - SOCKINT::WIN32-RECVFROM since 1.2.10 (03/2015) -> Late: 08/2015
1294 ;;; - SOCKINT::WIN32-SEND since 1.2.10 (03/2015) -> Late: 08/2015
1295 ;;; - SOCKINT::WIN32-SENDTO since 1.2.10 (03/2015) -> Late: 08/2015
1296 ;;; - SOCKINT::WIN32-CLOSE since 1.2.10 (03/2015) -> Late: 08/2015
1297 ;;; - SOCKINT::WIN32-CONNECT since 1.2.10 (03/2015) -> Late: 08/2015
1298 ;;; - SOCKINT::WIN32-GETPEERNAME since 1.2.10 (03/2015) -> Late: 08/2015
1299 ;;; - SOCKINT::WIN32-IOCTL since 1.2.10 (03/2015) -> Late: 08/2015
1300 ;;; - SOCKINT::WIN32-SETSOCKOPT since 1.2.10 (03/2015) -> Late: 08/2015
1301 ;;; - SOCKINT::WIN32-GETSOCKOPT since 1.2.10 (03/2015) -> Late: 08/2015
1303 ;;; - SB-THREAD::GET-MUTEX, since 1.0.37.33 (04/2010) -> Late: 01/2013
1304 ;;; ^- initially deprecated without compile-time warning, hence the schedule
1305 ;;; - SB-THREAD::SPINLOCK (type), since 1.0.53.11 (08/2011) -> Late: 08/2012
1306 ;;; - SB-THREAD::MAKE-SPINLOCK, since 1.0.53.11 (08/2011) -> Late: 08/2012
1307 ;;; - SB-THREAD::WITH-SPINLOCK, since 1.0.53.11 (08/2011) -> Late: 08/2012
1308 ;;; - SB-THREAD::WITH-RECURSIVE-SPINLOCK, since 1.0.53.11 (08/2011) -> Late: 08/2012
1309 ;;; - SB-THREAD::GET-SPINLOCK, since 1.0.53.11 (08/2011) -> Late: 08/2012
1310 ;;; - SB-THREAD::RELEASE-SPINLOCK, since 1.0.53.11 (08/2011) -> Late: 08/2012
1311 ;;; - SB-THREAD::SPINLOCK-VALUE, since 1.0.53.11 (08/2011) -> Late: 08/2012
1312 ;;; - SB-THREAD::SPINLOCK-NAME, since 1.0.53.11 (08/2011) -> Late: 08/2012
1313 ;;; - SETF SB-THREAD::SPINLOCK-NAME, since 1.0.53.11 (08/2011) -> Late: 08/2012
1314 ;;; - SB-C::MERGE-TAIL-CALLS (policy), since 1.0.53.74 (11/2011) -> Late: 11/2012
1315 ;;; - SB-EXT:QUIT, since 1.0.56.55 (05/2012) -> Late: 05/2013
1316 ;;; - SB-UNIX:UNIX-EXIT, since 1.0.56.55 (05/2012) -> Late: 05/2013
1317 ;;; - SB-DEBUG:*SHOW-ENTRY-POINT-DETAILS*, since 1.1.4.9 (02/2013) -> Late: 02/2014
1320 ;;; - SB-SYS:OUTPUT-RAW-BYTES, since 1.0.8.16 (06/2007) -> Final: anytime
1321 ;;; Note: make sure CLX doesn't use it anymore!
1322 ;;; - SB-C::STACK-ALLOCATE-DYNAMIC-EXTENT (policy), since 1.0.19.7 -> Final: anytime
1323 ;;; - SB-C::STACK-ALLOCATE-VECTOR (policy), since 1.0.19.7 -> Final: anytime
1324 ;;; - SB-C::STACK-ALLOCATE-VALUE-CELLS (policy), since 1.0.19.7 -> Final: anytime
1325 ;;; - SB-INTROSPECT:FUNCTION-ARGLIST, since 1.0.24.5 (01/2009) -> Final: anytime
1326 ;;; - SB-THREAD:JOIN-THREAD-ERROR-THREAD, since 1.0.29.17 (06/2009) -> Final: 09/2012
1327 ;;; - SB-THREAD:INTERRUPT-THREAD-ERROR-THREAD since 1.0.29.17 (06/2009) -> Final: 06/2012
1329 (deftype deprecation-state
()
1330 '(member :early
:late
:final
))
1332 (defun print-deprecation-message (name since
&optional replacements stream
)
1333 (apply #'format stream
1334 (!uncross-format-control
1335 "~/sb!impl:print-symbol-with-prefix/ has been ~
1336 deprecated as of SBCL ~A.~
1338 ~2%Use ~/sb!impl:print-symbol-with-prefix/ instead.~;~
1339 ~2%Use ~/sb!impl:print-symbol-with-prefix/ or ~
1340 ~/sb!impl:print-symbol-with-prefix/ instead.~:;~
1341 ~2%Use~@{~#[~; or~] ~
1342 ~/sb!impl:print-symbol-with-prefix/~^,~} instead.~
1344 name since replacements
))
1346 (defmacro define-deprecated-function
(state since name replacements lambda-list
1348 (declare (type deprecation-state state
)
1350 (type function-name name
)
1351 (type (or function-name list
) replacements
)
1352 (type list lambda-list
))
1353 (let* ((replacements (normalize-deprecation-replacements replacements
))
1354 (doc (print-deprecation-message name since replacements
)))
1355 (declare (ignorable doc
))
1359 `(defun ,name
,lambda-list
1364 (declaim (ftype (function * nil
) ,name
))
1365 (setf (fdefinition ',name
)
1366 (deprecated-function ,since
',name
',replacements
1369 (setf (compiler-macro-function ',name
)
1370 (deprecation-compiler-macro ,state
,since
',name
',replacements
)))))
1372 (defun check-deprecated-variable (name)
1373 (let ((info (info :variable
:deprecated name
)))
1375 (deprecation-warning (first info
) (second info
) name
(third info
))
1376 (values-list info
))))
1378 (defmacro define-deprecated-variable
(state since name
1379 &key
(value nil valuep
) replacement
)
1380 (declare (ignorable replacement
)
1381 (type deprecation-state state
)
1385 (setf (info :variable
:deprecated
',name
)
1386 '(,state
,since
,(when replacement
`(,replacement
))))
1387 ,(if (member state
'(:early
:late
))
1388 `(defvar ,name
,@(when valuep
(list value
)))
1391 (setf (fdocumentation ',name
'variable
)
1392 ,(print-deprecation-message name since
(list replacement
)))))
1394 ;;; Anaphoric macros
1395 (defmacro awhen
(test &body body
)
1399 (defmacro acond
(&rest clauses
)
1402 (destructuring-bind ((test &body body
) &rest rest
) clauses
1403 (once-only ((test test
))
1405 (let ((it ,test
)) (declare (ignorable it
)),@body
)
1408 ;; Given DECLS as returned by from parse-body, and SYMBOLS to be bound
1409 ;; (with LET, MULTIPLE-VALUE-BIND, etc) return two sets of declarations:
1410 ;; those which pertain to the variables and those which don't.
1411 ;; The first returned value is NIL or a single expression headed by DECLARE.
1412 ;; The second is a list of expressions resembling the input DECLS.
1413 (defun extract-var-decls (decls symbols
)
1414 (unless symbols
; Don't bother filtering DECLS, just return them.
1415 (return-from extract-var-decls
(values nil decls
)))
1416 (labels ((applies-to-variables (decl)
1417 ;; If DECL is a variable-affecting declaration, then return
1418 ;; the subset of SYMBOLS to which DECL applies.
1419 (let ((id (car decl
)))
1420 (remove-if (lambda (x) (not (memq x symbols
)))
1421 (cond ((eq id
'type
)
1423 ((or (listp id
) ; must be a type-specifier
1424 (memq id
'(special ignorable ignore
1426 truly-dynamic-extent
))
1427 (info :type
:kind id
))
1430 ;; If SPEC is a declaration affecting some variables in SYMBOLS
1431 ;; and some not, split it into two mutually exclusive declarations.
1432 (acond ((applies-to-variables spec
)
1433 (multiple-value-bind (decl-head all-symbols
)
1434 (if (eq (car spec
) 'type
)
1435 (values `(type ,(cadr spec
)) (cddr spec
))
1436 (values `(,(car spec
)) (cdr spec
)))
1437 (let ((more (set-difference all-symbols it
)))
1438 (values `(,@decl-head
,@it
)
1439 (and more
`(,@decl-head
,@more
))))))
1441 (values nil spec
)))))
1442 ;; This loop is less inefficient than theoretically possible,
1443 ;; reconstructing the tree even if no need,
1444 ;; but it's just a macroexpander, so... fine.
1445 (collect ((binding-decls))
1447 (mapcar (lambda (decl-expr) ; a list headed by DECLARE
1448 (mapcan (lambda (spec)
1449 (multiple-value-bind (binding other
)
1452 (binding-decls binding
))
1453 (if other
(list other
))))
1456 (values (awhen (binding-decls) `(declare ,@it
))
1457 (mapcan (lambda (x) (if x
(list `(declare ,@x
)))) filtered
))))))
1459 ;;; Delayed evaluation
1460 (defmacro delay
(form)
1461 `(cons nil
(lambda () ,form
)))
1463 (defun force (promise)
1464 (cond ((not (consp promise
)) promise
)
1465 ((car promise
) (cdr promise
))
1466 (t (setf (car promise
) t
1467 (cdr promise
) (funcall (cdr promise
))))))
1469 (defun promise-ready-p (promise)
1470 (or (not (consp promise
))
1474 (defmacro with-rebound-io-syntax
(&body body
)
1475 `(%with-rebound-io-syntax
(lambda () ,@body
)))
1477 (defun %with-rebound-io-syntax
(function)
1478 (declare (type function function
))
1479 (let ((*package
* *package
*)
1480 (*print-array
* *print-array
*)
1481 (*print-base
* *print-base
*)
1482 (*print-case
* *print-case
*)
1483 (*print-circle
* *print-circle
*)
1484 (*print-escape
* *print-escape
*)
1485 (*print-gensym
* *print-gensym
*)
1486 (*print-length
* *print-length
*)
1487 (*print-level
* *print-level
*)
1488 (*print-lines
* *print-lines
*)
1489 (*print-miser-width
* *print-miser-width
*)
1490 (*print-pretty
* *print-pretty
*)
1491 (*print-radix
* *print-radix
*)
1492 (*print-readably
* *print-readably
*)
1493 (*print-right-margin
* *print-right-margin
*)
1494 (*read-base
* *read-base
*)
1495 (*read-default-float-format
* *read-default-float-format
*)
1496 (*read-eval
* *read-eval
*)
1497 (*read-suppress
* *read-suppress
*)
1498 (*readtable
* *readtable
*))
1499 (funcall function
)))
1501 ;;; Bind a few "potentially dangerous" printer control variables to
1502 ;;; safe values, respecting current values if possible.
1503 (defmacro with-sane-io-syntax
(&body forms
)
1504 `(call-with-sane-io-syntax (lambda () ,@forms
)))
1506 (defun call-with-sane-io-syntax (function)
1507 (declare (type function function
))
1508 (macrolet ((true (sym)
1509 `(and (boundp ',sym
) ,sym
)))
1510 (let ((*print-readably
* nil
)
1511 (*print-level
* (or (true *print-level
*) 6))
1512 (*print-length
* (or (true *print-length
*) 12)))
1513 (funcall function
))))
1515 ;;; Returns a list of members of LIST. Useful for dealing with circular lists.
1516 ;;; For a dotted list returns a secondary value of T -- in which case the
1517 ;;; primary return value does not include the dotted tail.
1518 ;;; If the maximum length is reached, return a secondary value of :MAYBE.
1519 (defun list-members (list &key max-length
)
1521 (do ((tail (cdr list
) (cdr tail
))
1522 (members (list (car list
)) (cons (car tail
) members
))
1523 (count 0 (1+ count
)))
1524 ((or (not (consp tail
)) (eq tail list
)
1525 (and max-length
(>= count max-length
)))
1526 (values members
(or (not (listp tail
))
1527 (and (>= count max-length
) :maybe
)))))))
1529 ;;; Default evaluator mode (interpeter / compiler)
1531 (declaim (type (member :compile
#!+sb-eval
:interpret
) *evaluator-mode
*))
1532 (!defparameter
*evaluator-mode
* :compile
1534 "Toggle between different evaluator implementations. If set to :COMPILE,
1535 an implementation of EVAL that calls the compiler will be used. If set
1536 to :INTERPRET, an interpreter will be used.")
1538 ;;; Helper for making the DX closure allocation in macros expanding
1539 ;;; to CALL-WITH-FOO less ugly.
1540 (defmacro dx-flet
(functions &body forms
)
1542 (declare (#+sb-xc-host dynamic-extent
#-sb-xc-host truly-dynamic-extent
1543 ,@(mapcar (lambda (func) `(function ,(car func
))) functions
)))
1546 ;;; Another similar one.
1547 (defmacro dx-let
(bindings &body forms
)
1549 (declare (#+sb-xc-host dynamic-extent
#-sb-xc-host truly-dynamic-extent
1550 ,@(mapcar (lambda (bind) (if (consp bind
) (car bind
) bind
))
1554 ;; This is not my preferred name for this function, but chosen for harmony
1555 ;; with everything else that refers to these as 'hash-caches'.
1556 ;; Hashing is just one particular way of memoizing, and it would have been
1557 ;; slightly more abstract and yet at the same time more concrete to say
1558 ;; "memoized-function-caches". "hash-caches" is pretty nonspecific.
1559 #.
(if *profile-hash-cache
*
1560 '(defun show-hash-cache-statistics ()
1561 (flet ((cache-stats (symbol)
1562 (let* ((name (string symbol
))
1563 (statistics (let ((*package
* (symbol-package symbol
)))
1564 (symbolicate symbol
"STATISTICS")))
1566 (subseq name
0 (- (length name
) (length "VECTOR**")))))
1567 (values (if (boundp statistics
)
1568 (symbol-value statistics
)
1569 (make-array 3 :element-type
'fixnum
))
1570 (subseq prefix
2 (1- (length prefix
)))))))
1571 (format t
"~%Type function memoization:~% Seek Hit (%)~:
1572 Evict (%) Size full~%")
1573 ;; Sort by descending seek count to rank by likely relative importance
1574 (dolist (symbol (sort (copy-list *cache-vector-symbols
*) #'>
1575 :key
(lambda (x) (aref (cache-stats x
) 0))))
1576 (binding* (((stats short-name
) (cache-stats symbol
))
1577 (seek (aref stats
0))
1578 (miss (aref stats
1))
1580 (evict (aref stats
2))
1581 (cache (symbol-value symbol
)))
1582 (format t
"~9d ~9d (~5,1f%) ~8d (~5,1f%) ~4d ~6,1f% ~A~%"
1584 (if (plusp seek
) (* 100 (/ hit seek
)))
1586 (if (plusp seek
) (* 100 (/ evict seek
)))
1588 (if (plusp (length cache
))
1589 (* 100 (/ (count-if-not #'fixnump cache
)
1593 (in-package "SB!KERNEL")
1595 (defun fp-zero-p (x)
1597 (single-float (zerop x
))
1598 (double-float (zerop x
))
1600 (long-float (zerop x
))
1603 (defun neg-fp-zero (x)
1607 (make-unportable-float :single-float-negative-zero
)
1611 (make-unportable-float :double-float-negative-zero
)
1616 (make-unportable-float :long-float-negative-zero
)
1619 ;;; Signalling an error when trying to print an error condition is
1620 ;;; generally a PITA, so whatever the failure encountered when
1621 ;;; wondering about FILE-POSITION within a condition printer, 'tis
1622 ;;; better silently to give up than to try to complain.
1623 (defun file-position-or-nil-for-error (stream &optional
(pos nil posp
))
1624 ;; Arguably FILE-POSITION shouldn't be signalling errors at all; but
1625 ;; "NIL if this cannot be determined" in the ANSI spec doesn't seem
1626 ;; absolutely unambiguously to prohibit errors when, e.g., STREAM
1627 ;; has been closed so that FILE-POSITION is a nonsense question. So
1628 ;; my (WHN) impression is that the conservative approach is to
1629 ;; IGNORE-ERRORS. (I encountered this failure from within a homebrew
1630 ;; defsystemish operation where the ERROR-STREAM had been CL:CLOSEd,
1631 ;; I think by nonlocally exiting through a WITH-OPEN-FILE, by the
1632 ;; time an error was reported.)
1635 (file-position stream pos
)
1636 (file-position stream
))))
1638 (defun stream-error-position-info (stream &optional position
)
1639 (when (and (not position
) (form-tracking-stream-p stream
))
1640 (let ((line/col
(line/col-from-charpos stream
)))
1641 (return-from stream-error-position-info
1642 `((:line
,(car line
/col
))
1643 (:column
,(cdr line
/col
))
1644 ,@(let ((position (file-position-or-nil-for-error stream
)))
1645 ;; FIXME: 1- is technically broken for multi-byte external
1646 ;; encodings, albeit bug-compatible with the broken code in
1647 ;; the general case (below) for non-form-tracking-streams.
1648 ;; i.e. If you position to this byte, it might not be the
1649 ;; first byte of any character.
1650 (when position
`((:file-position
,(1- position
)))))))))
1652 ;; Give up early for interactive streams and non-character stream.
1653 (when (or (ignore-errors (interactive-stream-p stream
))
1654 (not (subtypep (ignore-errors (stream-element-type stream
))
1656 (return-from stream-error-position-info
))
1658 (flet ((read-content (old-position position
)
1659 "Read the content of STREAM into a buffer in order to count
1661 (unless (and old-position position
1662 (< position sb
!xc
:array-dimension-limit
))
1663 (return-from read-content
))
1665 (make-string position
:element-type
(stream-element-type stream
))))
1666 (when (and (file-position-or-nil-for-error stream
:start
)
1667 (eql position
(ignore-errors (read-sequence content stream
))))
1668 (file-position-or-nil-for-error stream old-position
)
1670 ;; Lines count from 1, columns from 0. It's stupid and
1673 (1+ (count #\Newline string
)))
1674 (column (string position
)
1675 (- position
(or (position #\Newline string
:from-end t
) 0))))
1676 (let* ((stream-position (file-position-or-nil-for-error stream
))
1677 (position (or position
1678 ;; FILE-POSITION is the next character --
1679 ;; error is at the previous one.
1680 (and stream-position
(plusp stream-position
)
1681 (1- stream-position
))))
1682 (content (read-content stream-position position
)))
1683 `(,@(when content
`((:line
,(line content
))
1684 (:column
,(column content position
))))
1685 ,@(when position
`((:file-position
,position
)))))))
1687 (declaim (inline schwartzian-stable-sort-list
))
1688 (defun schwartzian-stable-sort-list (list comparator
&key key
)
1690 (stable-sort (copy-list list
) comparator
)
1691 (let* ((key (if (functionp key
)
1693 (symbol-function key
)))
1694 (wrapped (mapcar (lambda (x)
1695 (cons x
(funcall key x
)))
1697 (sorted (stable-sort wrapped comparator
:key
#'cdr
)))
1698 (map-into sorted
#'car sorted
))))
1700 ;;; Just like WITH-OUTPUT-TO-STRING but doesn't close the stream,
1701 ;;; producing more compact code.
1702 (defmacro with-simple-output-to-string
1703 ((var &optional string
)
1705 (multiple-value-bind (forms decls
)
1706 (parse-body body
:doc-string-allowed nil
)
1708 `(let ((,var
(sb!impl
::make-fill-pointer-output-stream
,string
)))
1711 `(let ((,var
(make-string-output-stream)))
1714 (truly-the (simple-array character
(*))
1715 (get-output-stream-string ,var
))))))