Provide a better type for FORMAT NIL.
[sbcl.git] / src / code / early-extensions.lisp
blobb8f96518a69272ef5812ff7622072b883efdd3f8
1 ;;;; various extensions (including SB-INT "internal extensions")
2 ;;;; available both in the cross-compilation host Lisp and in the
3 ;;;; target SBCL
5 ;;;; This software is part of the SBCL system. See the README file for
6 ;;;; more information.
7 ;;;;
8 ;;;; This software is derived from the CMU CL system, which was
9 ;;;; written at Carnegie Mellon University and released into the
10 ;;;; public domain. The software is in the public domain and is
11 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
12 ;;;; files for more information.
14 (in-package "SB!IMPL")
16 (defvar *core-pathname* nil
17 #!+sb-doc
18 "The absolute pathname of the running SBCL core.")
20 (defvar *runtime-pathname* nil
21 #!+sb-doc
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))
30 (def!type hash ()
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.
35 ;;;
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
42 ;;; length).
43 ;;;
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)
85 (- lowtag))
86 scale))
87 ,(truncate (- (+ (1- (ash 1 16)) lowtag)
88 (* max-offset sb!vm:n-word-bytes))
89 scale)))
91 #!+(or x86 x86-64)
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)
96 bytes-per-element))
97 (max (truncate (+ sb!vm::maximum-immediate-offset adjustment)
98 bytes-per-element)))
99 (values min max)))
101 #!+(or x86 x86-64)
102 (def!type constant-displacement (lowtag element-size data-offset)
103 (flet ((integerify (x)
104 (etypecase x
105 (integer 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
111 element-size
112 data-offset)
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 '*) '*)
121 ((or (atom result)
122 (not (eq (car result) 'values)))
123 `(values ,result &optional))
124 ((intersection (cdr result) sb!xc:lambda-list-keywords)
125 result)
126 (t `(values ,@(cdr result) &optional)))))
127 `(function ,args ,result)))
129 ;;; a type specifier
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?) --
165 ;;; WHN 19990713
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))
183 (and (listp x)
184 (labels ((safe-cddr (cons)
185 (let ((cdr (cdr cons)))
186 (when (consp cdr)
187 (cdr cdr))))
188 (check-cycle (object seen depth)
189 (when (and (consp object)
190 (or (> depth depth-limit)
191 (member object seen)
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)))
200 ((not (consp fast))
201 ;; Not CDR-circular, need to check remaining CARs yet
202 (do ((tail slow (and (cdr tail))))
203 ((not (consp tail))
204 nil)
205 (check-cycle (car tail) (cons tail seen) (1+ depth))))
206 (check-cycle (car slow) (cons slow seen) (1+ depth))
207 (when (eq fast slow)
208 (return t)))))
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
215 (and (consp x)
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.)
224 (declare (fixnum x))
225 (if (<= x 5)
226 (and (>= x 2) (/= x 4))
227 (and (not (evenp x))
228 (not (zerop (rem x 3)))
229 (do ((q 6)
230 (r 1)
231 (inc 2 (logxor inc 6)) ;; 2,4,2,4...
232 (d 5 (+ d inc)))
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)
240 (or (consp x)
241 (%instancep x)
242 (typep x '(array t *))))
244 ;;;; the COLLECT macro
245 ;;;;
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
255 ;;; is empty.
256 (eval-when (#-sb-xc :compile-toplevel :load-toplevel :execute)
257 (defun collect-normal-expander (n-value fun forms)
258 `(progn
259 ,@(mapcar (lambda (form) `(setq ,n-value (,fun ,form ,n-value))) forms)
260 ,n-value))
261 (defun collect-list-expander (n-value n-tail forms)
262 (let ((n-res (gensym)))
263 `(progn
264 ,@(mapcar (lambda (form)
265 `(let ((,n-res (cons ,form nil)))
266 (cond (,n-tail
267 (setf (cdr ,n-tail) ,n-res)
268 (setq ,n-tail ,n-res))
270 (setq ,n-tail ,n-res ,n-value ,n-res)))))
271 forms)
272 ,n-value))))
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)
294 (let ((macros ())
295 (binds ())
296 (ignores ()))
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
304 (symbol-name name)
305 "-N-VALUE-"))))
306 (push `(,n-value ,default) binds)
307 (if (eq kind 'collect)
308 (let ((n-tail (gensym (concatenate 'string
309 (symbol-name name)
310 "-N-TAIL-"))))
311 (push n-tail ignores)
312 (if default
313 (push `(,n-tail (last ,n-value)) binds)
314 (push n-tail binds))
315 (push `(,name (&rest args)
316 (collect-list-expander ',n-value ',n-tail args))
317 macros))
318 (push `(,name (&rest args)
319 (collect-normal-expander ',n-value ',kind args))
320 macros))))
321 `(macrolet ,macros
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))))
327 ,@body))))
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
332 ;;;; equivalent.)
334 ;;; like (MEMBER ITEM LIST :TEST #'EQ)
335 (defun memq (item list)
336 #!+sb-doc
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)))
346 ((null i))
347 (when (eq (car i) item)
348 (return i))))
350 ;;; like (ASSOC ITEM ALIST :TEST #'EQ):
351 ;;; Return the first pair of ALIST where ITEM is EQ to the key of
352 ;;; the pair.
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
362 ;; operations:
363 (dolist (pair alist)
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)))
370 (return 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)
376 (let ((list list))
377 (do ((x list (cdr x))
378 (splice '()))
379 ((endp x) list)
380 (cond ((eq item (car x))
381 (if (null splice)
382 (setq list (cdr 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))
391 (j 0 (1+ j)))
392 ((null i))
393 (when (eq (car i) item)
394 (return j))))
396 (declaim (inline neq))
397 (defun neq (x y)
398 (not (eq x y)))
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)
407 (nth index list))
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))
416 (t list))))
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)
426 (dolist (x binds)
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
435 (lambda (clause)
436 (and (consp clause)
437 (or (eq (car clause) 'type)
438 (eq (car clause) 'ignore))))
439 (cdr decl))))
440 decls))
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)
451 ,elt
452 ,result))
453 (let ((,elt (aref ,vec ,index)))
454 ,@decls
455 (tagbody
456 ,@forms)))))))
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)
464 (loop
465 (multiple-value-bind (,n-more ,key-var ,value-var) (,gen)
466 ,@decls
467 (unless ,n-more (return ,result))
468 ,@forms)))))
469 `(let ((,n-table ,table))
470 ,(if locked
471 `(with-locked-system-table (,n-table)
472 ,iter-form)
473 iter-form))))))
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))
482 (when (null ,tail)
483 (error "malformed plist, odd number of elements"))
484 (setq ,val (pop ,tail))
485 (progn ,@body)))))
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 (defmacro 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.
507 (let (repr)
508 (dolist (clause clauses)
509 (destructuring-bind (symbols value-form &optional flag) clause
510 (declare (type (member :exit-if-null nil) flag))
511 (let* ((ignore nil)
512 (symbols
513 (cond ((not (listp symbols)) (list symbols))
514 ((not symbols) (setq ignore (list (gensym))))
515 (t (mapcar
516 (lambda (x) (or x (car (push (gensym) ignore))))
517 symbols))))
518 (flags (logior (if (cdr symbols) 1 0) (if flag 2 0)))
519 (last (car repr)))
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)
528 repr))))))
529 ;; Starting with the innermost binding clause, snarf out the
530 ;; applicable declarations. (Clauses are currently reversed)
531 (dolist (abstract-clause repr)
532 (when decls
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)))
545 (setq listp nil))
546 body)
547 do (setq 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)))
555 listp nil
556 decls nil))
557 body)))
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:
594 ;;; :HASH-BITS <n>
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.
599 ;;; :VALUES <n>
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*)
605 (set name nil)))
607 ;; Make a new hash-cache and optionally create the statistics vector.
608 (defun alloc-hash-cache (size symbol)
609 (let (cache)
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)
613 `(#+sb-xc-host set
614 #-sb-xc-host sb!kernel:%set-symbol-global-value
615 ,symbol ,value))
616 (reset-stats ()
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*
622 `(let ((statistics
623 (let ((*package* (symbol-package symbol)))
624 (symbolicate symbol "STATISTICS"))))
625 (unless (boundp statistics)
626 (set! 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)
634 (reset-stats)
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))))
651 'vector)
652 (- n 2))))
653 (macrolet ((def (n)
654 (let* ((ftype `(sfunction ,(make-list n :initial-element t) t))
655 (fn (hash-cache-line-allocator n))
656 (args (make-gensym-list n)))
657 `(progn
658 (declaim (ftype ,ftype ,fn))
659 (defun ,fn ,args
660 (declare (optimize (safety 0)))
661 ,(if (<= n 3)
662 `(list* ,@args)
663 `(vector ,@args)))))))
664 (def 2)
665 (def 3)
666 (def 4)
667 (def 5)
668 (def 6))
670 (defmacro !define-hash-cache (name args
671 &key hash-function hash-bits memoizer
672 (values 1))
673 (declare (ignore memoizer))
674 (dolist (arg args)
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**"))
680 (statistics-name
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)))
693 arg-vars)
694 result-temps))
695 (tests (mapcar (lambda (arg temp) ; -> (EQx ARG #:ARG)
696 `(,(cadr arg) ,(car arg) ,temp))
697 args temps))
698 (cache-type `(simple-vector ,size))
699 (line-type (let ((n (+ nargs values)))
700 (if (<= n 3) 'cons `(simple-vector ,n))))
701 (binds
702 (case (length temps)
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))))))
712 (fun
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)))
719 (,cache ,var-name))
720 (when ,cache
721 (let ((,hashval ,hashval))
722 (declare (type (signed-byte #.sb!vm:n-fixnum-bits) ,hashval))
723 (loop repeat 2 do
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))
732 (let* ,binds
733 (when (and ,@tests)
734 (return-from ,fun-name
735 (values ,@result-temps))))))
736 (setq ,hashval (ash ,hashval ,(- hash-bits)))))))
737 (multiple-value-bind ,result-temps (funcall ,thunk)
738 (let ((,entry
739 (,(hash-cache-line-allocator (+ nargs values))
740 ,@arg-vars ,@result-temps))
741 (,cache
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))))))
762 `(progn
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))
771 ,fun)))
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:
777 ;;; :MEMOIZER <name>
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")
788 memoizer-supplied-p)
789 &allow-other-keys)
790 args &body body-decls-doc)
791 (binding* (((forms decls doc) (parse-body body-decls-doc))
792 (arg-names (mapcar #'car args)))
793 `(progn
794 (!define-hash-cache ,name ,args ,@options)
795 (defun ,name ,arg-names
796 ,@decls
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
805 forms
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.
820 ;;; So:
821 (defun equal-but-no-car-recursion (x y)
822 (do () (())
823 (cond ((eql x y) (return t))
824 ((and (consp x)
825 (consp y)
826 (eql (pop x) (pop y))))
828 (return)))))
830 ;;;; package idioms
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
849 maybe-result
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
868 :datum name
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)
884 fun-name
885 (multiple-value-bind (legalp block-name)
886 (valid-function-name-p fun-name)
887 (if legalp
888 block-name
889 (error "not legal as a function name: ~S" fun-name)))))
891 (defun looks-like-name-of-special-var-p (x)
892 (and (symbolp x)
893 (symbol-package 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))))))))
899 ;;;; ONCE-ONLY
900 ;;;;
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)
917 (body body))
918 (if (null specs)
919 `(progn ,@body)
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 ()
943 #!+sb-doc
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)
957 `(unless ,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")
965 (fresh-line)
966 (write-line "failed AVER:")
967 (write expr)
968 (terpri))
969 (bug "~@<failed AVER: ~2I~_~A~:>" expr))
971 (defun bug (format-control &rest format-arguments)
972 (error 'bug
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
985 :datum value
986 :expected-type type
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))
995 (lambda (x y)
996 (funcall fun y x)))
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)
1007 (if (consp 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.
1021 (defun featurep (x)
1022 (typecase x
1023 (cons
1024 (case (car x)
1025 ((:not not)
1026 (cond
1027 ((cddr x)
1028 (error "too many subexpressions in feature expression: ~S" x))
1029 ((null (cdr 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)
1048 (if ,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)
1055 (values nil t)
1056 (multiple-value-bind (val2 win2) ,y
1057 (if (and val1 val2)
1058 (values t t)
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))
1069 (let ((certain? t))
1070 (dolist (i list (values nil certain?))
1071 (multiple-value-bind (sub-value sub-certain?) (funcall op thing i)
1072 (if sub-certain?
1073 (when sub-value (return (values t t)))
1074 (setf certain? nil))))))
1075 (defun every/type (op thing list)
1076 (declare (type function op))
1077 (let ((certain? t))
1078 (dolist (i list (if certain? (values t t) (values nil nil)))
1079 (multiple-value-bind (sub-value sub-certain?) (funcall op thing i)
1080 (if sub-certain?
1081 (unless sub-value (return (values nil t)))
1082 (setf certain? nil))))))
1084 ;;;; DEFPRINTER
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)
1100 (values))
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
1123 ;;; as if by PRIN1.
1125 ;;; The structure being printed is bound to STRUCTURE and the stream
1126 ;;; is bound to STREAM.
1127 (defmacro defprinter ((name
1128 &key
1129 (conc-name (concatenate 'simple-string
1130 (symbol-name name)
1131 "-"))
1132 identity)
1133 &rest slot-descs)
1134 (let ((first? t)
1135 maybe-print-space
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)
1141 (if first?
1142 (setf maybe-print-space nil
1143 first? 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)
1148 reversed-prints))
1150 (let ((sname (first slot-desc))
1151 (test t))
1152 (collect ((stuff))
1153 (do ((option (rest slot-desc) (cddr option)))
1154 ((null option)
1155 (push `(let ((,sname ,(sref sname)))
1156 (when ,test
1157 ,maybe-print-space
1158 ,@(or (stuff)
1159 `((defprinter-prin1
1160 ',sname ,sname ,stream)))))
1161 reversed-prints))
1162 (case (first option)
1163 (:prin1
1164 (stuff `(defprinter-prin1
1165 ',sname ,(second option) ,stream)))
1166 (:princ
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
1175 ,stream
1176 :type t
1177 :identity ,identity)
1178 ,@(nreverse reversed-prints))))))
1180 (defun print-symbol-with-prefix (stream symbol colon at)
1181 #!+sb-doc
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)))
1191 ;;;; etc.
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)))
1204 (list replacements)
1205 replacements))
1207 (defun deprecation-error (since name replacements)
1208 (error 'deprecation-error
1209 :name name
1210 :replacements (normalize-deprecation-replacements replacements)
1211 :since since))
1213 (defun deprecation-warning (state since name replacements
1214 &key (runtime-error (neq :early state)))
1215 (warn (ecase state
1216 (:early 'early-deprecation-warning)
1217 (:late 'late-deprecation-warning)
1218 (:final 'final-deprecation-warning))
1219 :name name
1220 :replacements (normalize-deprecation-replacements replacements)
1221 :since since
1222 :runtime-error runtime-error))
1224 (defun deprecated-function (since name replacements &optional doc)
1225 (let ((closure
1226 ;; setting the name is mildly redundant since the closure captures
1227 ;; its name. However %FUN-DOC can't make use of that fact.
1228 (set-closure-name
1229 (lambda (&rest deprecated-function-args)
1230 (declare (ignore deprecated-function-args))
1231 (deprecation-error since name replacements))
1232 name)))
1233 (when doc
1234 (setf (%fun-doc closure) doc))
1235 closure))
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)
1242 form))
1244 ;; Return the stage of deprecation of thing identified by KIND and NAME, or NIL.
1245 (defun deprecated-thing-p (kind name)
1246 (ecase kind
1247 (:function
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)))
1255 macro-fun))))))
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)))
1267 (warn warning-class
1268 :format-control "Reference to deprecated function~P ~S~@[ from ~S~]"
1269 :format-arguments
1270 (list (length stuff) (mapcar #'second stuff) whence))))
1272 ;;; STATE is one of
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.
1288 ;;; EARLY:
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
1319 ;;; LATE:
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.~
1337 ~#[~;~
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.~
1343 ~]")
1344 name since replacements))
1346 (defmacro define-deprecated-function (state since name replacements lambda-list
1347 &body body)
1348 (declare (type deprecation-state state)
1349 (type string since)
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))
1356 `(prog1
1357 ,(ecase state
1358 ((:early :late)
1359 `(defun ,name ,lambda-list
1360 #!+sb-doc ,doc
1361 ,@body))
1362 ((:final)
1363 `(progn
1364 (declaim (ftype (function * nil) ,name))
1365 (setf (fdefinition ',name)
1366 (deprecated-function ,since ',name ',replacements
1367 #!+sb-doc ,doc))
1368 ',name)))
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)))
1374 (when info
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)
1382 (type string since)
1383 (type symbol name))
1384 `(prog2
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)))
1389 `',name)
1390 #!+sb-doc
1391 (setf (fdocumentation ',name 'variable)
1392 ,(print-deprecation-message name since (list replacement)))))
1394 ;;; Anaphoric macros
1395 (defmacro awhen (test &body body)
1396 `(let ((it ,test))
1397 (when it ,@body)))
1399 (defmacro acond (&rest clauses)
1400 (if (null clauses)
1402 (destructuring-bind ((test &body body) &rest rest) clauses
1403 (once-only ((test test))
1404 `(if ,test
1405 (let ((it ,test)) (declare (ignorable it)),@body)
1406 (acond ,@rest))))))
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 (defun extract-var-decls (decls symbols)
1412 (labels ((applies-to-variables (decl)
1413 ;; If DECL is a variable-affecting declaration, then return
1414 ;; the subset of SYMBOLS to which DECL applies.
1415 (let ((id (car decl)))
1416 (remove-if (lambda (x) (not (memq x symbols)))
1417 (cond ((eq id 'type)
1418 (cddr decl))
1419 ((or (listp id) ; must be a type-specifier
1420 (memq id '(special ignorable ignore
1421 dynamic-extent
1422 truly-dynamic-extent))
1423 (info :type :kind id))
1424 (cdr decl))))))
1425 (partition (spec)
1426 ;; If SPEC is a declaration affecting some variables in SYMBOLS
1427 ;; and some not, split it into two mutually exclusive declarations.
1428 (acond ((applies-to-variables spec)
1429 (multiple-value-bind (decl-head all-symbols)
1430 (if (eq (car spec) 'type)
1431 (values `(type ,(cadr spec)) (cddr spec))
1432 (values `(,(car spec)) (cdr spec)))
1433 (let ((more (set-difference all-symbols it)))
1434 (values `(,@decl-head ,@it)
1435 (and more `(,@decl-head ,@more))))))
1437 (values nil spec)))))
1438 ;; This loop is less inefficient than theoretically possible,
1439 ;; reconstructing the tree even if no need,
1440 ;; but it's just a macroexpander, so... fine.
1441 (collect ((binding-decls))
1442 (let ((filtered
1443 (mapcar (lambda (decl-expr) ; a list headed by DECLARE
1444 (mapcan (lambda (spec)
1445 (multiple-value-bind (binding other)
1446 (partition spec)
1447 (when binding
1448 (binding-decls binding))
1449 (if other (list other))))
1450 (cdr decl-expr)))
1451 decls)))
1452 (values (awhen (binding-decls) `(declare ,@it))
1453 (mapcan (lambda (x) (if x (list `(declare ,@x)))) filtered))))))
1455 ;;; Delayed evaluation
1456 (defmacro delay (form)
1457 `(cons nil (lambda () ,form)))
1459 (defun force (promise)
1460 (cond ((not (consp promise)) promise)
1461 ((car promise) (cdr promise))
1462 (t (setf (car promise) t
1463 (cdr promise) (funcall (cdr promise))))))
1465 (defun promise-ready-p (promise)
1466 (or (not (consp promise))
1467 (car promise)))
1469 ;;; toplevel helper
1470 (defmacro with-rebound-io-syntax (&body body)
1471 `(%with-rebound-io-syntax (lambda () ,@body)))
1473 (defun %with-rebound-io-syntax (function)
1474 (declare (type function function))
1475 (let ((*package* *package*)
1476 (*print-array* *print-array*)
1477 (*print-base* *print-base*)
1478 (*print-case* *print-case*)
1479 (*print-circle* *print-circle*)
1480 (*print-escape* *print-escape*)
1481 (*print-gensym* *print-gensym*)
1482 (*print-length* *print-length*)
1483 (*print-level* *print-level*)
1484 (*print-lines* *print-lines*)
1485 (*print-miser-width* *print-miser-width*)
1486 (*print-pretty* *print-pretty*)
1487 (*print-radix* *print-radix*)
1488 (*print-readably* *print-readably*)
1489 (*print-right-margin* *print-right-margin*)
1490 (*read-base* *read-base*)
1491 (*read-default-float-format* *read-default-float-format*)
1492 (*read-eval* *read-eval*)
1493 (*read-suppress* *read-suppress*)
1494 (*readtable* *readtable*))
1495 (funcall function)))
1497 ;;; Bind a few "potentially dangerous" printer control variables to
1498 ;;; safe values, respecting current values if possible.
1499 (defmacro with-sane-io-syntax (&body forms)
1500 `(call-with-sane-io-syntax (lambda () ,@forms)))
1502 (defun call-with-sane-io-syntax (function)
1503 (declare (type function function))
1504 (macrolet ((true (sym)
1505 `(and (boundp ',sym) ,sym)))
1506 (let ((*print-readably* nil)
1507 (*print-level* (or (true *print-level*) 6))
1508 (*print-length* (or (true *print-length*) 12)))
1509 (funcall function))))
1511 ;;; Returns a list of members of LIST. Useful for dealing with circular lists.
1512 ;;; For a dotted list returns a secondary value of T -- in which case the
1513 ;;; primary return value does not include the dotted tail.
1514 ;;; If the maximum length is reached, return a secondary value of :MAYBE.
1515 (defun list-members (list &key max-length)
1516 (when list
1517 (do ((tail (cdr list) (cdr tail))
1518 (members (list (car list)) (cons (car tail) members))
1519 (count 0 (1+ count)))
1520 ((or (not (consp tail)) (eq tail list)
1521 (and max-length (>= count max-length)))
1522 (values members (or (not (listp tail))
1523 (and (>= count max-length) :maybe)))))))
1525 ;;; Default evaluator mode (interpeter / compiler)
1527 (declaim (type (member :compile #!+sb-eval :interpret) *evaluator-mode*))
1528 (!defparameter *evaluator-mode* :compile
1529 #!+sb-doc
1530 "Toggle between different evaluator implementations. If set to :COMPILE,
1531 an implementation of EVAL that calls the compiler will be used. If set
1532 to :INTERPRET, an interpreter will be used.")
1534 ;;; Helper for making the DX closure allocation in macros expanding
1535 ;;; to CALL-WITH-FOO less ugly.
1536 (defmacro dx-flet (functions &body forms)
1537 `(flet ,functions
1538 (declare (#+sb-xc-host dynamic-extent #-sb-xc-host truly-dynamic-extent
1539 ,@(mapcar (lambda (func) `(function ,(car func))) functions)))
1540 ,@forms))
1542 ;;; Another similar one.
1543 (defmacro dx-let (bindings &body forms)
1544 `(let ,bindings
1545 (declare (#+sb-xc-host dynamic-extent #-sb-xc-host truly-dynamic-extent
1546 ,@(mapcar (lambda (bind) (if (consp bind) (car bind) bind))
1547 bindings)))
1548 ,@forms))
1550 ;; This is not my preferred name for this function, but chosen for harmony
1551 ;; with everything else that refers to these as 'hash-caches'.
1552 ;; Hashing is just one particular way of memoizing, and it would have been
1553 ;; slightly more abstract and yet at the same time more concrete to say
1554 ;; "memoized-function-caches". "hash-caches" is pretty nonspecific.
1555 #.(if *profile-hash-cache*
1556 '(defun show-hash-cache-statistics ()
1557 (flet ((cache-stats (symbol)
1558 (let* ((name (string symbol))
1559 (statistics (let ((*package* (symbol-package symbol)))
1560 (symbolicate symbol "STATISTICS")))
1561 (prefix
1562 (subseq name 0 (- (length name) (length "VECTOR**")))))
1563 (values (if (boundp statistics)
1564 (symbol-value statistics)
1565 (make-array 3 :element-type 'fixnum))
1566 (subseq prefix 2 (1- (length prefix)))))))
1567 (format t "~%Type function memoization:~% Seek Hit (%)~:
1568 Evict (%) Size full~%")
1569 ;; Sort by descending seek count to rank by likely relative importance
1570 (dolist (symbol (sort (copy-list *cache-vector-symbols*) #'>
1571 :key (lambda (x) (aref (cache-stats x) 0))))
1572 (binding* (((stats short-name) (cache-stats symbol))
1573 (seek (aref stats 0))
1574 (miss (aref stats 1))
1575 (hit (- seek miss))
1576 (evict (aref stats 2))
1577 (cache (symbol-value symbol)))
1578 (format t "~9d ~9d (~5,1f%) ~8d (~5,1f%) ~4d ~6,1f% ~A~%"
1579 seek hit
1580 (if (plusp seek) (* 100 (/ hit seek)))
1581 evict
1582 (if (plusp seek) (* 100 (/ evict seek)))
1583 (length cache)
1584 (if (plusp (length cache))
1585 (* 100 (/ (count-if-not #'fixnump cache)
1586 (length cache))))
1587 short-name))))))
1589 (in-package "SB!KERNEL")
1591 (defun fp-zero-p (x)
1592 (typecase x
1593 (single-float (zerop x))
1594 (double-float (zerop x))
1595 #!+long-float
1596 (long-float (zerop x))
1597 (t nil)))
1599 (defun neg-fp-zero (x)
1600 (etypecase x
1601 (single-float
1602 (if (eql x 0.0f0)
1603 (make-unportable-float :single-float-negative-zero)
1604 0.0f0))
1605 (double-float
1606 (if (eql x 0.0d0)
1607 (make-unportable-float :double-float-negative-zero)
1608 0.0d0))
1609 #!+long-float
1610 (long-float
1611 (if (eql x 0.0l0)
1612 (make-unportable-float :long-float-negative-zero)
1613 0.0l0))))
1615 ;;; Signalling an error when trying to print an error condition is
1616 ;;; generally a PITA, so whatever the failure encountered when
1617 ;;; wondering about FILE-POSITION within a condition printer, 'tis
1618 ;;; better silently to give up than to try to complain.
1619 (defun file-position-or-nil-for-error (stream &optional (pos nil posp))
1620 ;; Arguably FILE-POSITION shouldn't be signalling errors at all; but
1621 ;; "NIL if this cannot be determined" in the ANSI spec doesn't seem
1622 ;; absolutely unambiguously to prohibit errors when, e.g., STREAM
1623 ;; has been closed so that FILE-POSITION is a nonsense question. So
1624 ;; my (WHN) impression is that the conservative approach is to
1625 ;; IGNORE-ERRORS. (I encountered this failure from within a homebrew
1626 ;; defsystemish operation where the ERROR-STREAM had been CL:CLOSEd,
1627 ;; I think by nonlocally exiting through a WITH-OPEN-FILE, by the
1628 ;; time an error was reported.)
1629 (ignore-errors
1630 (if posp
1631 (file-position stream pos)
1632 (file-position stream))))
1634 (defun stream-error-position-info (stream &optional position)
1635 (when (and (not position) (form-tracking-stream-p stream))
1636 (let ((line/col (line/col-from-charpos stream)))
1637 (return-from stream-error-position-info
1638 `((:line ,(car line/col))
1639 (:column ,(cdr line/col))
1640 ,@(let ((position (file-position-or-nil-for-error stream)))
1641 ;; FIXME: 1- is technically broken for multi-byte external
1642 ;; encodings, albeit bug-compatible with the broken code in
1643 ;; the general case (below) for non-form-tracking-streams.
1644 ;; i.e. If you position to this byte, it might not be the
1645 ;; first byte of any character.
1646 (when position `((:file-position ,(1- position)))))))))
1648 ;; Give up early for interactive streams and non-character stream.
1649 (when (or (ignore-errors (interactive-stream-p stream))
1650 (not (subtypep (ignore-errors (stream-element-type stream))
1651 'character)))
1652 (return-from stream-error-position-info))
1654 (flet ((read-content (old-position position)
1655 "Read the content of STREAM into a buffer in order to count
1656 lines and columns."
1657 (unless (and old-position position
1658 (< position sb!xc:array-dimension-limit))
1659 (return-from read-content))
1660 (let ((content
1661 (make-string position :element-type (stream-element-type stream))))
1662 (when (and (file-position-or-nil-for-error stream :start)
1663 (eql position (ignore-errors (read-sequence content stream))))
1664 (file-position-or-nil-for-error stream old-position)
1665 content)))
1666 ;; Lines count from 1, columns from 0. It's stupid and
1667 ;; traditional.
1668 (line (string)
1669 (1+ (count #\Newline string)))
1670 (column (string position)
1671 (- position (or (position #\Newline string :from-end t) 0))))
1672 (let* ((stream-position (file-position-or-nil-for-error stream))
1673 (position (or position
1674 ;; FILE-POSITION is the next character --
1675 ;; error is at the previous one.
1676 (and stream-position (plusp stream-position)
1677 (1- stream-position))))
1678 (content (read-content stream-position position)))
1679 `(,@(when content `((:line ,(line content))
1680 (:column ,(column content position))))
1681 ,@(when position `((:file-position ,position)))))))
1683 (declaim (inline schwartzian-stable-sort-list))
1684 (defun schwartzian-stable-sort-list (list comparator &key key)
1685 (if (null key)
1686 (stable-sort (copy-list list) comparator)
1687 (let* ((key (if (functionp key)
1689 (symbol-function key)))
1690 (wrapped (mapcar (lambda (x)
1691 (cons x (funcall key x)))
1692 list))
1693 (sorted (stable-sort wrapped comparator :key #'cdr)))
1694 (map-into sorted #'car sorted))))
1696 ;;; Just like WITH-OUTPUT-TO-STRING but doesn't close the stream,
1697 ;;; producing more compact code.
1698 (defmacro with-simple-output-to-string
1699 ((var &optional string)
1700 &body body)
1701 (multiple-value-bind (forms decls)
1702 (parse-body body :doc-string-allowed nil)
1703 (if string
1704 `(let ((,var (sb!impl::make-fill-pointer-output-stream ,string)))
1705 ,@decls
1706 ,@forms)
1707 `(let ((,var (make-string-output-stream)))
1708 ,@decls
1709 ,@forms
1710 (truly-the (simple-array character (*))
1711 (get-output-stream-string ,var))))))