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
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
))
29 `(integer 0 ,max-hash
))
31 ;;; A number that can represent an index into a vector, including
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.
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
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
)
93 ,(truncate (- (+ (1- (ash 1 16)) lowtag
)
94 (* max-offset sb
!vm
:n-word-bytes
))
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
)
103 (max (truncate (+ sb
!vm
::maximum-immediate-offset adjustment
)
108 (def!type constant-displacement
(lowtag element-size data-offset
)
109 (flet ((integerify (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
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?) --
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
))
168 (labels ((safe-cddr (cons)
169 (let ((cdr (cdr cons
)))
172 (check-cycle (cdr seen depth
)
173 (let ((object (car cdr
)))
174 (when (and (consp object
)
175 (or (= depth depth-limit
)
177 (let ((seen (cons cdr seen
)))
178 (declare (dynamic-extent 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
)))
189 ;; Not CDR-circular, need to check remaining CARs yet
190 (do ((tail slow
(cdr tail
)))
192 (check-cycle tail seen depth
)))
193 (check-cycle slow seen depth
)
194 (when (or (eq fast slow
)
195 (zerop (setf size-limit
198 (return-from coalesce-tree-p
)))))
199 (declare (inline check-cycle
))
200 (recurse x
(list x
) 0)
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
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.)
218 (and (>= x
2) (/= x
4))
220 (not (zerop (rem x
3)))
223 (inc 2 (logxor inc
6)) ;; 2,4,2,4...
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)
234 (typep x
'(array t
*))))
236 ;;;; the COLLECT macro
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)))
248 ,@(mapcar (lambda (form)
249 `(let ((,n-res
(cons ,form nil
)))
251 (setf (cdr ,n-tail
) ,n-res
)
252 (setq ,n-tail
,n-res
))
254 (setq ,n-tail
,n-res
,n-value
,n-res
)))))
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
)
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
)
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
))
292 ,@(mapcar (lambda (x)
293 `(setq ,',n-value
(,',collector
,x
,',n-value
)))
296 (push `(,name
(&rest args
) ,macro-body
) 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
))))
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
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
)))
323 (when (eq (car i
) item
)
326 ;;; like (ASSOC ITEM ALIST :TEST #'EQ):
327 ;;; Return the first pair of ALIST where ITEM is EQ to the key of
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
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
)))
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))
355 (do ((x list
(cdr x
))
358 (cond ((eq item
(car 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
))
371 (when (eq (car i
) item
)
374 (declaim (inline neq
))
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
))
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
)
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
406 (or (eq (car clause
) 'type
)
407 (eq (car clause
) 'ignore
))))
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
)
422 (let ((,elt
(aref ,vec
,index
)))
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
)
435 `(let ((,n-table
,table
))
437 `(with-locked-system-table (,n-table
) ,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
))
448 (error "malformed plist, odd number of elements"))
449 (setq ,val
(pop ,tail
))
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
456 (defmacro ensure-gethash
(key hash-table
&optional default
)
457 (with-unique-names (n-key n-hash-table value foundp
)
459 (,n-hash-table
,hash-table
))
460 (multiple-value-bind (,value
,foundp
) (gethash ,n-key
,n-hash-table
)
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.
486 (dolist (clause clauses
)
487 (destructuring-bind (symbols value-form
&optional flag
) clause
488 (declare (type (member :exit-if-null nil
) flag
))
491 (cond ((not (listp symbols
)) (list symbols
))
492 ((not symbols
) (setq ignore
(list (gensym))))
494 (lambda (x) (or x
(car (push (gensym) ignore
))))
496 (flags (logior (if (cdr symbols
) 1 0) (if flag
2 0)))
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
)
507 ;; Starting with the innermost binding clause, snarf out the
508 ;; applicable declarations. (Clauses are currently reversed)
509 (dolist (abstract-clause repr
)
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
)))
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
)))
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
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:
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.
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
*)
606 ;; Make a new hash-cache and optionally create the statistics vector.
607 (defun alloc-hash-cache (size symbol
)
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
)
613 #-sb-xc-host sb
!kernel
:%set-symbol-global-value
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
*
622 (let ((*package
* (symbol-package symbol
)))
623 (symbolicate symbol
"STATISTICS"))))
624 (unless (boundp 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
)
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))))
653 (let* ((ftype `(sfunction ,(make-list n
:initial-element t
) t
))
654 (fn (hash-cache-line-allocator n
))
655 (args (make-gensym-list n
)))
657 (declaim (ftype ,ftype
,fn
))
659 (declare (optimize (safety 0)))
662 `(vector ,@args
)))))))
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
))
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**"))
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
))
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
)))
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
))
702 (cache-type `(simple-vector ,size
))
703 (line-type (let ((n (+ nargs nvalues
)))
704 (if (<= n
3) 'cons
`(simple-vector ,n
))))
706 `((,hashval
(the (signed-byte #.sb
!vm
:n-fixnum-bits
)
707 (funcall ,hash-function
,@arg-vars
)))
710 (lambda (ignore action
)
712 (let ((,hashval
,hashval
) ; gets clobbered in probe loop
713 (,cache
(truly-the ,cache-type
,cache
)))
715 (declare (type (signed-byte #.sb
!vm
:n-fixnum-bits
) ,hashval
))
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
))
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
)))))
738 (when (and ,@tests
) ,action
))))
739 (setq ,hashval
(ash ,hashval
,(- hash-bits
)))))))))
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)))))
746 ,(funcall probe-it nil
747 `(return-from ,fun-name
(values ,@result-temps
)))
748 (multiple-value-bind ,result-temps
(funcall ,thunk
)
750 (,(hash-cache-line-allocator (+ nargs nvalues
))
751 ,@(mapcar (lambda (spec) (or (caddr spec
) (car spec
)))
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
))))))
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
787 `((declare (ignore ,@result-temps
)))
788 `(return (setf (svref ,cache
789 (ldb (byte ,hash-bits
0) ,hashval
))
791 (declaim (inline ,fun-name
))
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:
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")
823 args
&body body-decls-doc
)
824 (binding* (((forms decls doc
) (parse-body body-decls-doc t
))
826 (let ((aux (member '&aux args
)))
828 (values (ldiff args aux
) aux
)
830 (arg-names (mapcar #'car inputs
)))
832 (!define-hash-cache
,name
,inputs
,aux-vars
,@options
)
833 (defun ,name
,arg-names
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
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.
859 (defun equal-but-no-car-recursion (x y
)
861 (cond ((eql x y
) (return t
))
864 (eql (pop x
) (pop y
))))
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
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
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
)
930 (multiple-value-bind (legalp block-name
)
931 (valid-function-name-p fun-name
)
934 (error "not legal as a function name: ~S" fun-name
)))))
936 (defun looks-like-name-of-special-var-p (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
))))))))
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
)
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
999 (defmacro aver
(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
)
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
))
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)
1029 (destructuring-bind (result) x result
)
1032 ;;; some commonly-occurring CONSTANTLY forms
1033 (macrolet ((def-constantly-fun (name constant-expr
)
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
)
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
)
1058 (multiple-value-bind (val2 win2
) ,y
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
))
1072 (dolist (i list
(values nil certain?
))
1073 (multiple-value-bind (sub-value sub-certain?
) (funcall op thing i
)
1075 (when sub-value
(return (values t t
)))
1076 (setf certain? nil
))))))
1077 (defun every/type
(op thing list
)
1078 (declare (type function op
))
1080 (dolist (i list
(if certain?
(values t t
) (values nil nil
)))
1081 (multiple-value-bind (sub-value sub-certain?
) (funcall op thing i
)
1083 (unless sub-value
(return (values nil t
)))
1084 (setf certain? nil
))))))
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
)
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
1127 ;;; The structure being printed is bound to STRUCTURE and the stream
1128 ;;; is bound to STREAM.
1129 (defmacro defprinter
((name
1131 (conc-name (concatenate 'simple-string
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
)
1144 (setf maybe-print-space 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
)
1152 (let ((sname (first slot-desc
))
1155 (do ((option (rest slot-desc
) (cddr option
)))
1157 (push `(let ((,sname
,(sref sname
)))
1162 ',sname
,sname
,stream
)))))
1164 (case (first option
)
1166 (stuff `(defprinter-prin1
1167 ',sname
,(second option
) ,stream
)))
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
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
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
))))
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
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
)
1246 (values-list since
)))
1248 (defun normalize-deprecation-replacements (replacements)
1249 (if (or (not (listp replacements
))
1250 (eq 'setf
(car replacements
)))
1254 (defstruct (deprecation-info
1255 (:constructor make-deprecation-info
1256 (state software version
&optional replacement-spec
1258 (replacements (normalize-deprecation-replacements
1259 replacement-spec
))))
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
)
1271 (variable (info :variable
:deprecated name
))
1272 (function (info :function
:deprecated name
))
1273 (type (info :type
:deprecated name
)))
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
1290 :replacements
(normalize-deprecation-replacements replacements
)))
1292 (defun deprecation-warn (state software version namespace name replacements
1293 &key
(runtime-error (neq :early state
)))
1295 (:early
'early-deprecation-warning
)
1296 (:late
'late-deprecation-warning
)
1297 (:final
'final-deprecation-warning
))
1298 :namespace namespace
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
)
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)
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
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.
1331 ((sb!kernel
::parse-deprecated-type
1333 (let ((type-specifier (sb!kernel
::parse-deprecated-type-specifier
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
)
1341 (declare (ignore condition
))
1343 (specifier-type type-specifier
)))))
1345 (defun check-deprecated-type (type-specifier)
1346 (typecase type-specifier
1348 (%check-deprecated-type type-specifier
))
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
)))
1366 :format-control
"Reference to deprecated function~P ~S~@[ from ~S~]"
1368 (list (length stuff
) (mapcar #'second stuff
) whence
))))
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.
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
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
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.~:;~
1417 ~/sb-ext:print-symbol-with-prefix/~^,~} instead.~
1421 (defun print-deprecation-message (namespace name software version
1422 &optional replacements 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
))
1433 (setf (fdefinition name
)
1435 (lambda (&rest args
)
1436 (declare (ignore args
))
1437 (deprecation-error software version
'function name replacement-spec
))
1441 (defun setup-variable-in-final-deprecation
1442 (software version name replacement-spec
)
1443 (sb!c
::%define-symbol-macro
1446 ,software
,version
'variable
',name
1448 (lambda (replacement)
1450 (normalize-deprecation-replacements replacement-spec
))))
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
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
))
1468 (declaim (deprecated
1469 ,state
("SBCL" ,version
)
1470 (function ,name
,@(when replacements
1471 `(:replacement
,replacements
)))))
1474 `(defun ,name
,lambda-list
1479 (defmacro define-deprecated-variable
(state version name
1480 &key
(value nil valuep
) replacement
)
1481 (declare (type deprecation-state state
)
1482 (type string version
)
1484 #+sb-xc-host
(ignore version replacement
))
1487 (declaim (deprecated
1488 ,state
("SBCL" ,version
)
1489 (variable ,name
,@(when replacement
1490 `(:replacement
,replacement
)))))
1493 `(defvar ,name
,@(when valuep
(list value
))))
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
)
1512 ((or (listp id
) ; must be a type-specifier
1513 (memq id
'(special ignorable ignore
1515 truly-dynamic-extent
))
1516 (info :type
:kind id
))
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))
1536 (mapcar (lambda (decl-expr) ; a list headed by DECLARE
1537 (mapcan (lambda (spec)
1538 (multiple-value-bind (binding other
)
1541 (binding-decls binding
))
1542 (if other
(list other
))))
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
))
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
)
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
)
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")))
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))
1659 (evict (aref stats
2))
1660 (cache (symbol-value symbol
)))
1661 (format t
"~9d ~9d (~5,1f%) ~8d (~5,1f%) ~4d ~6,1f% ~A~%"
1663 (if (plusp seek
) (* 100 (/ hit seek
)))
1665 (if (plusp seek
) (* 100 (/ evict seek
)))
1667 (if (plusp (length cache
))
1668 (* 100 (/ (count-if-not #'fixnump cache
)
1672 (in-package "SB!KERNEL")
1674 (defun fp-zero-p (x)
1676 (single-float (zerop x
))
1677 (double-float (zerop x
))
1679 (long-float (zerop x
))
1682 (defun neg-fp-zero (x)
1686 (make-unportable-float :single-float-negative-zero
)
1690 (make-unportable-float :double-float-negative-zero
)
1695 (make-unportable-float :long-float-negative-zero
)
1698 (declaim (inline schwartzian-stable-sort-list
))
1699 (defun schwartzian-stable-sort-list (list comparator
&key 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
)))
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
)
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
)))
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
)
1729 (multiple-value-bind (forms decls
) (parse-body body nil
)
1731 `(let ((,var
(sb!impl
::make-fill-pointer-output-stream
,string
)))
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
)))
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)
1755 (symbol (or (eq x t
) (eq (symbol-package x
) *keyword-package
*)))
1759 (defmacro eval-when-compile-toplevel
(&body body
)
1760 `(eval-when (:compile-toplevel
:execute
#!+sb-devel
:load-toplevel
)