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 ;;; something not EQ to anything we might legitimately READ
17 (defparameter *eof-object* (make-symbol "EOF-OBJECT"))
19 ;;; a type used for indexing into arrays, and for related quantities
20 ;;; like lengths of lists
22 ;;; It's intentionally limited to one less than the
23 ;;; ARRAY-DIMENSION-LIMIT for efficiency reasons, because in SBCL
24 ;;; ARRAY-DIMENSION-LIMIT is MOST-POSITIVE-FIXNUM, and staying below
25 ;;; that lets the system know it can increment a value of this type
26 ;;; without having to worry about using a bignum to represent the
29 ;;; (It should be safe to use ARRAY-DIMENSION-LIMIT as an exclusive
30 ;;; bound because ANSI specifies it as an exclusive bound.)
31 (def!type index () `(integer 0 (,sb!xc:array-dimension-limit)))
33 ;;; like INDEX, but augmented with -1 (useful when using the index
34 ;;; to count downwards to 0, e.g. LOOP FOR I FROM N DOWNTO 0, with
35 ;;; an implementation which terminates the loop by testing for the
36 ;;; index leaving the loop range)
37 (def!type index-or-minus-1 () `(integer -1 (,sb!xc:array-dimension-limit)))
39 ;;; A couple of VM-related types that are currently used only on the
40 ;;; alpha platform. -- CSR, 2002-06-24
41 (def!type unsigned-byte-with-a-bite-out (s bite)
42 (cond ((eq s '*) 'integer)
43 ((and (integerp s) (> s 0))
44 (let ((bound (ash 1 s)))
45 `(integer 0 ,(- bound bite 1))))
47 (error "Bad size specified for UNSIGNED-BYTE type specifier: ~S." s))))
49 ;;; Motivated by the mips port. -- CSR, 2002-08-22
50 (def!type signed-byte-with-a-bite-out (s bite)
51 (cond ((eq s '*) 'integer)
52 ((and (integerp s) (> s 1))
53 (let ((bound (ash 1 (1- s))))
54 `(integer ,(- bound) ,(- bound bite 1))))
56 (error "Bad size specified for SIGNED-BYTE type specifier: ~S." s))))
58 (def!type load/store-index (scale lowtag min-offset
59 &optional (max-offset min-offset))
60 `(integer ,(- (truncate (+ (ash 1 16)
61 (* min-offset sb!vm:n-word-bytes)
64 ,(truncate (- (+ (1- (ash 1 16)) lowtag)
65 (* max-offset sb!vm:n-word-bytes))
68 ;;; Similar to FUNCTION, but the result type is "exactly" specified:
69 ;;; if it is an object type, then the function returns exactly one
70 ;;; value, if it is a short form of VALUES, then this short form
71 ;;; specifies the exact number of values.
72 (def!type sfunction (args &optional result)
73 (let ((result (cond ((eq result '*) '*)
75 (not (eq (car result) 'values)))
76 `(values ,result &optional))
77 ((intersection (cdr result) lambda-list-keywords)
79 (t `(values ,@(cdr result) &optional)))))
80 `(function ,args ,result)))
82 ;;; the default value used for initializing character data. The ANSI
83 ;;; spec says this is arbitrary, so we use the value that falls
84 ;;; through when we just let the low-level consing code initialize
85 ;;; all newly-allocated memory to zero.
87 ;;; KLUDGE: It might be nice to use something which is a
88 ;;; STANDARD-CHAR, both to reduce user surprise a little and, probably
89 ;;; more significantly, to help SBCL's cross-compiler (which knows how
90 ;;; to dump STANDARD-CHARs). Unfortunately, the old CMU CL code is
91 ;;; shot through with implicit assumptions that it's #\NULL, and code
92 ;;; in several places (notably both DEFUN MAKE-ARRAY and DEFTRANSFORM
93 ;;; MAKE-ARRAY) would have to be rewritten. -- WHN 2001-10-04
94 (eval-when (:compile-toplevel :load-toplevel :execute)
95 ;; an expression we can use to construct a DEFAULT-INIT-CHAR value
96 ;; at load time (so that we don't need to teach the cross-compiler
97 ;; how to represent and dump non-STANDARD-CHARs like #\NULL)
98 (defparameter *default-init-char-form* '(code-char 0)))
100 ;;; CHAR-CODE values for ASCII characters which we care about but
101 ;;; which aren't defined in section "2.1.3 Standard Characters" of the
102 ;;; ANSI specification for Lisp
104 ;;; KLUDGE: These are typically used in the idiom (CODE-CHAR
105 ;;; FOO-CHAR-CODE). I suspect that the current implementation is
106 ;;; expanding this idiom into a full call to CODE-CHAR, which is an
107 ;;; annoying overhead. I should check whether this is happening, and
108 ;;; if so, perhaps implement a DEFTRANSFORM or something to stop it.
109 ;;; (or just find a nicer way of expressing characters portably?) --
111 (def!constant bell-char-code 7)
112 (def!constant backspace-char-code 8)
113 (def!constant tab-char-code 9)
114 (def!constant line-feed-char-code 10)
115 (def!constant form-feed-char-code 12)
116 (def!constant return-char-code 13)
117 (def!constant escape-char-code 27)
118 (def!constant rubout-char-code 127)
120 ;;;; type-ish predicates
122 ;;; Is X a list containing a cycle?
123 (defun cyclic-list-p (x)
125 (labels ((safe-cddr (x) (if (listp (cdr x)) (cddr x))))
126 (do ((y x (safe-cddr y))
129 ((not (and (consp z) (consp y))) nil)
130 (when (and started-p (eq y z))
133 ;;; Is X a (possibly-improper) list of at least N elements?
134 (declaim (ftype (function (t index)) list-of-length-at-least-p))
135 (defun list-of-length-at-least-p (x n)
136 (or (zerop n) ; since anything can be considered an improper list of length 0
138 (list-of-length-at-least-p (cdr x) (1- n)))))
140 (declaim (inline singleton-p))
141 (defun singleton-p (list)
145 ;;; Is X is a positive prime integer?
146 (defun positive-primep (x)
147 ;; This happens to be called only from one place in sbcl-0.7.0, and
148 ;; only for fixnums, we can limit it to fixnums for efficiency. (And
149 ;; if we didn't limit it to fixnums, we should use a cleverer
150 ;; algorithm, since this one scales pretty badly for huge X.)
153 (and (>= x 2) (/= x 4))
155 (not (zerop (rem x 3)))
158 (inc 2 (logxor inc 6)) ;; 2,4,2,4...
160 ((or (= r 0) (> d q)) (/= r 0))
161 (declare (fixnum inc))
162 (multiple-value-setq (q r) (truncate x d))))))
164 ;;; Could this object contain other objects? (This is important to
165 ;;; the implementation of things like *PRINT-CIRCLE* and the dumper.)
166 (defun compound-object-p (x)
169 (typep x '(array t *))))
171 ;;;; the COLLECT macro
173 ;;;; comment from CMU CL: "the ultimate collection macro..."
175 ;;; helper functions for COLLECT, which become the expanders of the
176 ;;; MACROLET definitions created by COLLECT
178 ;;; COLLECT-NORMAL-EXPANDER handles normal collection macros.
180 ;;; COLLECT-LIST-EXPANDER handles the list collection case. N-TAIL
181 ;;; is the pointer to the current tail of the list, or NIL if the list
183 (eval-when (#-sb-xc :compile-toplevel :load-toplevel :execute)
184 (defun collect-normal-expander (n-value fun forms)
186 ,@(mapcar (lambda (form) `(setq ,n-value (,fun ,form ,n-value))) forms)
188 (defun collect-list-expander (n-value n-tail forms)
189 (let ((n-res (gensym)))
191 ,@(mapcar (lambda (form)
192 `(let ((,n-res (cons ,form nil)))
194 (setf (cdr ,n-tail) ,n-res)
195 (setq ,n-tail ,n-res))
197 (setq ,n-tail ,n-res ,n-value ,n-res)))))
201 ;;; Collect some values somehow. Each of the collections specifies a
202 ;;; bunch of things which collected during the evaluation of the body
203 ;;; of the form. The name of the collection is used to define a local
204 ;;; macro, a la MACROLET. Within the body, this macro will evaluate
205 ;;; each of its arguments and collect the result, returning the
206 ;;; current value after the collection is done. The body is evaluated
207 ;;; as a PROGN; to get the final values when you are done, just call
208 ;;; the collection macro with no arguments.
210 ;;; INITIAL-VALUE is the value that the collection starts out with,
211 ;;; which defaults to NIL. FUNCTION is the function which does the
212 ;;; collection. It is a function which will accept two arguments: the
213 ;;; value to be collected and the current collection. The result of
214 ;;; the function is made the new value for the collection. As a
215 ;;; totally magical special-case, FUNCTION may be COLLECT, which tells
216 ;;; us to build a list in forward order; this is the default. If an
217 ;;; INITIAL-VALUE is supplied for COLLECT, the stuff will be RPLACD'd
218 ;;; onto the end. Note that FUNCTION may be anything that can appear
219 ;;; in the functional position, including macros and lambdas.
220 (defmacro collect (collections &body body)
223 (dolist (spec collections)
224 (unless (proper-list-of-length-p spec 1 3)
225 (error "malformed collection specifier: ~S" spec))
226 (let* ((name (first spec))
227 (default (second spec))
228 (kind (or (third spec) 'collect))
229 (n-value (gensym (concatenate 'string
232 (push `(,n-value ,default) binds)
233 (if (eq kind 'collect)
234 (let ((n-tail (gensym (concatenate 'string
238 (push `(,n-tail (last ,n-value)) binds)
240 (push `(,name (&rest args)
241 (collect-list-expander ',n-value ',n-tail args))
243 (push `(,name (&rest args)
244 (collect-normal-expander ',n-value ',kind args))
246 `(macrolet ,macros (let* ,(nreverse binds) ,@body))))
248 ;;;; some old-fashioned functions. (They're not just for old-fashioned
249 ;;;; code, they're also used as optimized forms of the corresponding
250 ;;;; general functions when the compiler can prove that they're
253 ;;; like (MEMBER ITEM LIST :TEST #'EQ)
254 (defun memq (item list)
256 "Return tail of LIST beginning with first element EQ to ITEM."
257 ;; KLUDGE: These could be and probably should be defined as
258 ;; (MEMBER ITEM LIST :TEST #'EQ)),
259 ;; but when I try to cross-compile that, I get an error from
260 ;; LTN-ANALYZE-KNOWN-CALL, "Recursive known function definition". The
261 ;; comments for that error say it "is probably a botched interpreter stub".
262 ;; Rather than try to figure that out, I just rewrote this function from
263 ;; scratch. -- WHN 19990512
264 (do ((i list (cdr i)))
266 (when (eq (car i) item)
269 ;;; like (ASSOC ITEM ALIST :TEST #'EQ):
270 ;;; Return the first pair of ALIST where ITEM is EQ to the key of
272 (defun assq (item alist)
273 ;; KLUDGE: CMU CL defined this with
274 ;; (DECLARE (INLINE ASSOC))
275 ;; (ASSOC ITEM ALIST :TEST #'EQ))
276 ;; which is pretty, but which would have required adding awkward
277 ;; build order constraints on SBCL (or figuring out some way to make
278 ;; inline definitions installable at build-the-cross-compiler time,
279 ;; which was too ambitious for now). Rather than mess with that, we
280 ;; just define ASSQ explicitly in terms of more primitive
283 (when (eq (car pair) item)
286 ;;; like (DELETE .. :TEST #'EQ):
287 ;;; Delete all LIST entries EQ to ITEM (destructively modifying
288 ;;; LIST), and return the modified LIST.
289 (defun delq (item list)
291 (do ((x list (cdr x))
294 (cond ((eq item (car x))
297 (rplacd splice (cdr x))))
298 (t (setq splice x)))))) ; Move splice along to include element.
301 ;;; like (POSITION .. :TEST #'EQ):
302 ;;; Return the position of the first element EQ to ITEM.
303 (defun posq (item list)
304 (do ((i list (cdr i))
307 (when (eq (car i) item)
310 (declaim (inline neq))
314 ;;; not really an old-fashioned function, but what the calling
315 ;;; convention should've been: like NTH, but with the same argument
316 ;;; order as in all the other dereferencing functions, with the
317 ;;; collection first and the index second
318 (declaim (inline nth-but-with-sane-arg-order))
319 (declaim (ftype (function (list index) t) nth-but-with-sane-arg-order))
320 (defun nth-but-with-sane-arg-order (list index)
323 (defun adjust-list (list length initial-element)
324 (let ((old-length (length list)))
325 (cond ((< old-length length)
326 (append list (make-list (- length old-length)
327 :initial-element initial-element)))
328 ((> old-length length)
329 (subseq list 0 length))
332 ;;;; miscellaneous iteration extensions
334 ;;; "the ultimate iteration macro"
336 ;;; note for Schemers: This seems to be identical to Scheme's "named LET".
337 (defmacro named-let (name binds &body body)
340 (unless (proper-list-of-length-p x 2)
341 (error "malformed NAMED-LET variable spec: ~S" x)))
342 `(labels ((,name ,(mapcar #'first binds) ,@body))
343 (,name ,@(mapcar #'second binds))))
345 ;;; just like DOLIST, but with one-dimensional arrays
346 (defmacro dovector ((elt vector &optional result) &rest forms)
347 (let ((index (gensym))
350 `(let ((,vec ,vector))
351 (declare (type vector ,vec))
352 (do ((,index 0 (1+ ,index))
353 (,length (length ,vec)))
354 ((>= ,index ,length) ,result)
355 (let ((,elt (aref ,vec ,index)))
358 ;;; Iterate over the entries in a HASH-TABLE.
359 (defmacro dohash ((key-var value-var table &optional result) &body body)
360 (multiple-value-bind (forms decls) (parse-body body nil)
363 `(with-hash-table-iterator (,gen ,table)
365 (multiple-value-bind (,n-more ,key-var ,value-var) (,gen)
367 (unless ,n-more (return ,result))
370 ;;;; hash cache utility
372 (eval-when (:compile-toplevel :load-toplevel :execute)
373 (defvar *profile-hash-cache* nil))
375 ;;; a flag for whether it's too early in cold init to use caches so
376 ;;; that we have a better chance of recovering so that we have a
377 ;;; better chance of getting the system running so that we have a
378 ;;; better chance of diagnosing the problem which caused us to use the
381 (defvar *hash-caches-initialized-p*)
383 ;;; Define a hash cache that associates some number of argument values
384 ;;; with a result value. The TEST-FUNCTION paired with each ARG-NAME
385 ;;; is used to compare the value for that arg in a cache entry with a
386 ;;; supplied arg. The TEST-FUNCTION must not error when passed NIL as
387 ;;; its first arg, but need not return any particular value.
388 ;;; TEST-FUNCTION may be any thing that can be placed in CAR position.
390 ;;; NAME is used to define these functions:
391 ;;; <name>-CACHE-LOOKUP Arg*
392 ;;; See whether there is an entry for the specified ARGs in the
393 ;;; cache. If not present, the :DEFAULT keyword (default NIL)
394 ;;; determines the result(s).
395 ;;; <name>-CACHE-ENTER Arg* Value*
396 ;;; Encache the association of the specified args with VALUE.
397 ;;; <name>-CACHE-CLEAR
398 ;;; Reinitialize the cache, invalidating all entries and allowing
399 ;;; the arguments and result values to be GC'd.
401 ;;; These other keywords are defined:
403 ;;; The size of the cache as a power of 2.
404 ;;; :HASH-FUNCTION function
405 ;;; Some thing that can be placed in CAR position which will compute
406 ;;; a value between 0 and (1- (expt 2 <hash-bits>)).
408 ;;; the number of return values cached for each function call
409 ;;; :INIT-WRAPPER <name>
410 ;;; The code for initializing the cache is wrapped in a form with
411 ;;; the specified name. (:INIT-WRAPPER is set to COLD-INIT-FORMS
412 ;;; in type system definitions so that caches will be created
413 ;;; before top level forms run.)
414 (defmacro define-hash-cache (name args &key hash-function hash-bits default
415 (init-wrapper 'progn)
417 (let* ((var-name (symbolicate "*" name "-CACHE-VECTOR*"))
418 (nargs (length args))
419 (entry-size (+ nargs values))
420 (size (ash 1 hash-bits))
421 (total-size (* entry-size size))
422 (default-values (if (and (consp default) (eq (car default) 'values))
428 (unless (= (length default-values) values)
429 (error "The number of default values ~S differs from :VALUES ~W."
441 (values-indices `(+ ,n-index ,(+ nargs i)))
442 (values-names (gensym)))
445 (unless (= (length arg) 2)
446 (error "bad argument spec: ~S" arg))
447 (let ((arg-name (first arg))
450 (tests `(,test (svref ,n-cache (+ ,n-index ,n)) ,arg-name))
451 (sets `(setf (svref ,n-cache (+ ,n-index ,n)) ,arg-name)))
454 (when *profile-hash-cache*
455 (let ((n-probe (symbolicate "*" name "-CACHE-PROBES*"))
456 (n-miss (symbolicate "*" name "-CACHE-MISSES*")))
457 (inits `(setq ,n-probe 0))
458 (inits `(setq ,n-miss 0))
459 (forms `(defvar ,n-probe))
460 (forms `(defvar ,n-miss))
461 (forms `(declaim (fixnum ,n-miss ,n-probe)))))
463 (let ((fun-name (symbolicate name "-CACHE-LOOKUP")))
466 `(defun ,fun-name ,(arg-vars)
467 ,@(when *profile-hash-cache*
468 `((incf ,(symbolicate "*" name "-CACHE-PROBES*"))))
469 (let ((,n-index (* (,hash-function ,@(arg-vars)) ,entry-size))
470 (,n-cache ,var-name))
471 (declare (type fixnum ,n-index))
472 (cond ((and ,@(tests))
473 (values ,@(mapcar (lambda (x) `(svref ,n-cache ,x))
476 ,@(when *profile-hash-cache*
477 `((incf ,(symbolicate "*" name "-CACHE-MISSES*"))))
480 (let ((fun-name (symbolicate name "-CACHE-ENTER")))
483 `(defun ,fun-name (,@(arg-vars) ,@(values-names))
484 (let ((,n-index (* (,hash-function ,@(arg-vars)) ,entry-size))
485 (,n-cache ,var-name))
486 (declare (type fixnum ,n-index))
488 ,@(mapcar (lambda (i val)
489 `(setf (svref ,n-cache ,i) ,val))
494 (let ((fun-name (symbolicate name "-CACHE-CLEAR")))
497 (do ((,n-index ,(- total-size entry-size) (- ,n-index ,entry-size))
498 (,n-cache ,var-name))
500 (declare (type fixnum ,n-index))
501 ,@(collect ((arg-sets))
503 (arg-sets `(setf (svref ,n-cache (+ ,n-index ,i)) nil)))
505 ,@(mapcar (lambda (i val)
506 `(setf (svref ,n-cache ,i) ,val))
510 (forms `(,fun-name)))
512 (inits `(unless (boundp ',var-name)
513 (setq ,var-name (make-array ,total-size))))
514 #!+sb-show (inits `(setq *hash-caches-initialized-p* t))
518 (declaim (type (simple-vector ,total-size) ,var-name))
519 #!-sb-fluid (declaim (inline ,@(inlines)))
520 (,init-wrapper ,@(inits))
524 ;;; some syntactic sugar for defining a function whose values are
525 ;;; cached by DEFINE-HASH-CACHE
526 (defmacro defun-cached ((name &rest options &key (values 1) default
528 args &body body-decls-doc)
529 (let ((default-values (if (and (consp default) (eq (car default) 'values))
532 (arg-names (mapcar #'car args)))
533 (collect ((values-names))
535 (values-names (gensym)))
536 (multiple-value-bind (body decls doc) (parse-body body-decls-doc)
538 (define-hash-cache ,name ,args ,@options)
539 (defun ,name ,arg-names
543 ((not (boundp '*hash-caches-initialized-p*))
544 ;; This shouldn't happen, but it did happen to me
545 ;; when revising the type system, and it's a lot
546 ;; easier to figure out what what's going on with
547 ;; that kind of problem if the system can be kept
548 ;; alive until cold boot is complete. The recovery
549 ;; mechanism should definitely be conditional on
550 ;; some debugging feature (e.g. SB-SHOW) because
551 ;; it's big, duplicating all the BODY code. -- WHN
552 (/show0 ,name " too early in cold init, uncached")
553 (/show0 ,(first arg-names) "=..")
554 (/hexstr ,(first arg-names))
557 (multiple-value-bind ,(values-names)
558 (,(symbolicate name "-CACHE-LOOKUP") ,@arg-names)
559 (if (and ,@(mapcar (lambda (val def)
561 (values-names) default-values))
562 (multiple-value-bind ,(values-names)
564 (,(symbolicate name "-CACHE-ENTER") ,@arg-names
566 (values ,@(values-names)))
567 (values ,@(values-names))))))))))))
569 (defmacro define-cached-synonym
570 (name &optional (original (symbolicate "%" name)))
571 (let ((cached-name (symbolicate "%%" name "-cached")))
573 (defun-cached (,cached-name :hash-bits 8
574 :hash-function (lambda (x)
575 (logand (sxhash x) #xff)))
577 (apply #',original args))
578 (defun ,name (&rest args)
579 (,cached-name args)))))
581 ;;; FIXME: maybe not the best place
583 ;;; FIXME: think of a better name -- not only does this not have the
584 ;;; CAR recursion of EQUAL, it also doesn't have the special treatment
585 ;;; of pathnames, bit-vectors and strings.
587 ;;; KLUDGE: This means that we will no longer cache specifiers of the
588 ;;; form '(INTEGER (0) 4). This is probably not a disaster.
590 ;;; A helper function for the type system, which is the main user of
591 ;;; these caches: we must be more conservative than EQUAL for some of
592 ;;; our equality tests, because MEMBER and friends refer to EQLity.
594 (defun equal-but-no-car-recursion (x y)
599 (eql (car x) (car y))
600 (equal-but-no-car-recursion (cdr x) (cdr y))))
605 ;;; Note: Almost always you want to use FIND-UNDELETED-PACKAGE-OR-LOSE
606 ;;; instead of this function. (The distinction only actually matters when
607 ;;; PACKAGE-DESIGNATOR is actually a deleted package, and in that case
608 ;;; you generally do want to signal an error instead of proceeding.)
609 (defun %find-package-or-lose (package-designator)
610 (or (find-package package-designator)
611 (error 'sb!kernel:simple-package-error
612 :package package-designator
613 :format-control "The name ~S does not designate any package."
614 :format-arguments (list package-designator))))
616 ;;; ANSI specifies (in the section for FIND-PACKAGE) that the
617 ;;; consequences of most operations on deleted packages are
618 ;;; unspecified. We try to signal errors in such cases.
619 (defun find-undeleted-package-or-lose (package-designator)
620 (let ((maybe-result (%find-package-or-lose package-designator)))
621 (if (package-name maybe-result) ; if not deleted
623 (error 'sb!kernel:simple-package-error
624 :package maybe-result
625 :format-control "The package ~S has been deleted."
626 :format-arguments (list maybe-result)))))
628 ;;;; various operations on names
630 ;;; Is NAME a legal function name?
631 (defun legal-fun-name-p (name)
632 (values (valid-function-name-p name)))
634 ;;; Signal an error unless NAME is a legal function name.
635 (defun legal-fun-name-or-type-error (name)
636 (unless (legal-fun-name-p name)
637 (error 'simple-type-error
639 :expected-type '(or symbol list)
640 :format-control "invalid function name: ~S"
641 :format-arguments (list name))))
643 ;;; Given a function name, return the symbol embedded in it.
645 ;;; The ordinary use for this operator (and the motivation for the
646 ;;; name of this operator) is to convert from a function name to the
647 ;;; name of the BLOCK which encloses its body.
649 ;;; Occasionally the operator is useful elsewhere, where the operator
650 ;;; name is less mnemonic. (Maybe it should be changed?)
651 (declaim (ftype (function ((or symbol cons)) symbol) fun-name-block-name))
652 (defun fun-name-block-name (fun-name)
653 (cond ((symbolp fun-name)
656 (multiple-value-bind (legalp block-name)
657 (valid-function-name-p fun-name)
660 (error "not legal as a function name: ~S" fun-name))))
662 (error "not legal as a function name: ~S" fun-name))))
664 (defun looks-like-name-of-special-var-p (x)
666 (let ((name (symbol-name x)))
667 (and (> (length name) 2) ; to exclude '* and '**
668 (char= #\* (aref name 0))
669 (char= #\* (aref name (1- (length name))))))))
671 ;;; Some symbols are defined by ANSI to be self-evaluating. Return
672 ;;; non-NIL for such symbols (and make the non-NIL value a traditional
673 ;;; message, for use in contexts where the user asks us to change such
675 (defun symbol-self-evaluating-p (symbol)
676 (declare (type symbol symbol))
678 "Veritas aeterna. (can't change T)")
680 "Nihil ex nihil. (can't change NIL)")
682 "Keyword values can't be changed.")
686 ;;; This function is to be called just before a change which would
687 ;;; affect the symbol value. (We don't absolutely have to call this
688 ;;; function before such changes, since such changes are given as
689 ;;; undefined behavior. In particular, we don't if the runtime cost
690 ;;; would be annoying. But otherwise it's nice to do so.)
691 (defun about-to-modify-symbol-value (symbol)
692 (declare (type symbol symbol))
693 (let ((reason (symbol-self-evaluating-p symbol)))
696 ;; (Note: Just because a value is CONSTANTP is not a good enough
697 ;; reason to complain here, because we want DEFCONSTANT to be able
698 ;; to use this function, and it's legal to DEFCONSTANT a constant as
699 ;; long as the new value is EQL to the old value.)
703 ;;; If COLD-FSET occurs not at top level, just treat it as an ordinary
704 ;;; assignment instead of doing cold static linking. That way things like
705 ;;; (FLET ((FROB (X) ..))
706 ;;; (DEFUN FOO (X Y) (FROB X) ..)
707 ;;; (DEFUN BAR (Z) (AND (FROB X) ..)))
708 ;;; can still "work" for cold init: they don't do magical static
709 ;;; linking the way that true toplevel DEFUNs do, but at least they do
710 ;;; the linking eventually, so as long as #'FOO and #'BAR aren't
711 ;;; needed until "cold toplevel forms" have executed, it's OK.
712 (defmacro cold-fset (name lambda)
714 "~@<COLD-FSET ~S not cross-compiled at top level: demoting to ~
715 (SETF FDEFINITION)~:@>"
717 ;; We convert the LAMBDA expression to the corresponding NAMED-LAMBDA
718 ;; expression so that the compiler can use NAME in debug names etc.
719 (destructuring-bind (lambda-symbol &rest lambda-rest) lambda
720 (assert (eql lambda-symbol 'lambda)) ; else dunno how to do conversion
721 `(setf (fdefinition ',name)
722 (named-lambda ,name ,@lambda-rest))))
726 ;;;; "The macro ONCE-ONLY has been around for a long time on various
727 ;;;; systems [..] if you can understand how to write and when to use
728 ;;;; ONCE-ONLY, then you truly understand macro." -- Peter Norvig,
729 ;;;; _Paradigms of Artificial Intelligence Programming: Case Studies
730 ;;;; in Common Lisp_, p. 853
732 ;;; ONCE-ONLY is a utility useful in writing source transforms and
733 ;;; macros. It provides a concise way to wrap a LET around some code
734 ;;; to ensure that some forms are only evaluated once.
736 ;;; Create a LET* which evaluates each value expression, binding a
737 ;;; temporary variable to the result, and wrapping the LET* around the
738 ;;; result of the evaluation of BODY. Within the body, each VAR is
739 ;;; bound to the corresponding temporary variable.
740 (defmacro once-only (specs &body body)
741 (named-let frob ((specs specs)
745 (let ((spec (first specs)))
746 ;; FIXME: should just be DESTRUCTURING-BIND of SPEC
747 (unless (proper-list-of-length-p spec 2)
748 (error "malformed ONCE-ONLY binding spec: ~S" spec))
749 (let* ((name (first spec))
750 (exp-temp (gensym (symbol-name name))))
751 `(let ((,exp-temp ,(second spec))
752 (,name (gensym "ONCE-ONLY-")))
753 `(let ((,,name ,,exp-temp))
754 ,,(frob (rest specs) body))))))))
756 ;;;; various error-checking utilities
758 ;;; This function can be used as the default value for keyword
759 ;;; arguments that must be always be supplied. Since it is known by
760 ;;; the compiler to never return, it will avoid any compile-time type
761 ;;; warnings that would result from a default value inconsistent with
762 ;;; the declared type. When this function is called, it signals an
763 ;;; error indicating that a required &KEY argument was not supplied.
764 ;;; This function is also useful for DEFSTRUCT slot defaults
765 ;;; corresponding to required arguments.
766 (declaim (ftype (function () nil) missing-arg))
767 (defun missing-arg ()
769 (/show0 "entering MISSING-ARG")
770 (error "A required &KEY or &OPTIONAL argument was not supplied."))
772 ;;; like CL:ASSERT and CL:CHECK-TYPE, but lighter-weight
774 ;;; (As of sbcl-0.6.11.20, we were using some 400 calls to CL:ASSERT.
775 ;;; The CL:ASSERT restarts and whatnot expand into a significant
776 ;;; amount of code when you multiply them by 400, so replacing them
777 ;;; with this should reduce the size of the system by enough to be
778 ;;; worthwhile. ENFORCE-TYPE is much less common, but might still be
779 ;;; worthwhile, and since I don't really like CERROR stuff deep in the
780 ;;; guts of complex systems anyway, I replaced it too.)
781 (defmacro aver (expr)
783 (%failed-aver ,(format nil "~A" expr))))
785 (defun %failed-aver (expr-as-string)
786 (bug "~@<failed AVER: ~2I~_~S~:>" expr-as-string))
788 ;;; We need a definition of BUG here for the host compiler to be able
789 ;;; to deal with BUGs in sbcl. This should never affect an end-user,
790 ;;; who will pick up the definition that signals a CONDITION of
791 ;;; condition-class BUG; however, this is not defined on the host
792 ;;; lisp, but for the target. SBCL developers sometimes trigger BUGs
793 ;;; in their efforts, and it is useful to get the details of the BUG
794 ;;; rather than an undefined function error. - CSR, 2002-04-12
796 (defun bug (format-control &rest format-arguments)
798 :format-control "~@< ~? ~:@_~?~:>"
799 :format-arguments `(,format-control
801 "~@<If you see this and are an SBCL ~
802 developer, then it is probable that you have made a change to the ~
803 system that has broken the ability for SBCL to compile, usually by ~
804 removing an assumed invariant of the system, but sometimes by making ~
805 an averrance that is violated (check your code!). If you are a user, ~
806 please submit a bug report to the developers' mailing list, details of ~
807 which can be found at <http://sbcl.sourceforge.net/>.~:@>"
810 (defmacro enforce-type (value type)
811 (once-only ((value value))
812 `(unless (typep ,value ',type)
813 (%failed-enforce-type ,value ',type))))
815 (defun %failed-enforce-type (value type)
816 (error 'simple-type-error ; maybe should be TYPE-BUG, subclass of BUG?
819 :format-string "~@<~S ~_is not a ~_~S~:>"
820 :format-arguments (list value type)))
822 ;;; Return a function like FUN, but expecting its (two) arguments in
823 ;;; the opposite order that FUN does.
824 (declaim (inline swapped-args-fun))
825 (defun swapped-args-fun (fun)
826 (declare (type function fun))
830 ;;; Return the numeric value of a type bound, i.e. an interval bound
831 ;;; more or less in the format of bounds in ANSI's type specifiers,
832 ;;; where a bare numeric value is a closed bound and a list of a
833 ;;; single numeric value is an open bound.
835 ;;; The "more or less" bit is that the no-bound-at-all case is
836 ;;; represented by NIL (not by * as in ANSI type specifiers); and in
837 ;;; this case we return NIL.
838 (defun type-bound-number (x)
840 (destructuring-bind (result) x result)
843 ;;; some commonly-occuring CONSTANTLY forms
844 (macrolet ((def-constantly-fun (name constant-expr)
845 `(setf (symbol-function ',name)
846 (constantly ,constant-expr))))
847 (def-constantly-fun constantly-t t)
848 (def-constantly-fun constantly-nil nil)
849 (def-constantly-fun constantly-0 0))
851 ;;; If X is an atom, see whether it is present in *FEATURES*. Also
852 ;;; handle arbitrary combinations of atoms using NOT, AND, OR.
858 (error "too many subexpressions in feature expression: ~S" x)
859 (not (featurep (cadr x)))))
860 ((:and and) (every #'featurep (cdr x)))
861 ((:or or) (some #'featurep (cdr x)))
863 (error "unknown operator in feature expression: ~S." x)))
864 (not (null (memq x *features*)))))
866 ;;; Given a list of keyword substitutions `(,OLD ,NEW), and a
867 ;;; &KEY-argument-list-style list of alternating keywords and
868 ;;; arbitrary values, return a new &KEY-argument-list-style list with
869 ;;; all substitutions applied to it.
871 ;;; Note: If efficiency mattered, we could do less consing. (But if
872 ;;; efficiency mattered, why would we be using &KEY arguments at
873 ;;; all, much less renaming &KEY arguments?)
875 ;;; KLUDGE: It would probably be good to get rid of this. -- WHN 19991201
876 (defun rename-key-args (rename-list key-args)
877 (declare (type list rename-list key-args))
878 ;; Walk through RENAME-LIST modifying RESULT as per each element in
880 (do ((result (copy-list key-args))) ; may be modified below
881 ((null rename-list) result)
882 (destructuring-bind (old new) (pop rename-list)
883 ;; ANSI says &KEY arg names aren't necessarily KEYWORDs.
884 (declare (type symbol old new))
885 ;; Walk through RESULT renaming any OLD key argument to NEW.
886 (do ((in-result result (cddr in-result)))
888 (declare (type list in-result))
889 (when (eq (car in-result) old)
890 (setf (car in-result) new))))))
892 ;;; ANSI Common Lisp's READ-SEQUENCE function, unlike most of the
893 ;;; other ANSI input functions, is defined to communicate end of file
894 ;;; status with its return value, not by signalling. That is not the
895 ;;; behavior that we usually want. This function is a wrapper which
896 ;;; restores the behavior that we usually want, causing READ-SEQUENCE
897 ;;; to communicate end-of-file status by signalling.
898 (defun read-sequence-or-die (sequence stream &key start end)
899 ;; implementation using READ-SEQUENCE
900 #-no-ansi-read-sequence
901 (let ((read-end (read-sequence sequence
905 (unless (= read-end end)
906 (error 'end-of-file :stream stream))
908 ;; workaround for broken READ-SEQUENCE
909 #+no-ansi-read-sequence
911 (aver (<= start end))
912 (let ((etype (stream-element-type stream)))
913 (cond ((equal etype '(unsigned-byte 8))
914 (do ((i start (1+ i)))
917 (setf (aref sequence i)
918 (read-byte stream))))
919 (t (error "unsupported element type ~S" etype))))))
921 ;;;; utilities for two-VALUES predicates
923 (defmacro not/type (x)
924 (let ((val (gensym "VAL"))
925 (win (gensym "WIN")))
926 `(multiple-value-bind (,val ,win)
929 (values (not ,val) t)
932 (defmacro and/type (x y)
933 `(multiple-value-bind (val1 win1) ,x
934 (if (and (not val1) win1)
936 (multiple-value-bind (val2 win2) ,y
939 (values nil (and win2 (not val2))))))))
941 ;;; sort of like ANY and EVERY, except:
942 ;;; * We handle two-VALUES predicate functions, as SUBTYPEP does.
943 ;;; (And if the result is uncertain, then we return (VALUES NIL NIL),
944 ;;; as SUBTYPEP does.)
945 ;;; * THING is just an atom, and we apply OP (an arity-2 function)
946 ;;; successively to THING and each element of LIST.
947 (defun any/type (op thing list)
948 (declare (type function op))
950 (dolist (i list (values nil certain?))
951 (multiple-value-bind (sub-value sub-certain?) (funcall op thing i)
953 (when sub-value (return (values t t)))
954 (setf certain? nil))))))
955 (defun every/type (op thing list)
956 (declare (type function op))
958 (dolist (i list (if certain? (values t t) (values nil nil)))
959 (multiple-value-bind (sub-value sub-certain?) (funcall op thing i)
961 (unless sub-value (return (values nil t)))
962 (setf certain? nil))))))
966 ;;; These functions are called by the expansion of the DEFPRINTER
967 ;;; macro to do the actual printing.
968 (declaim (ftype (function (symbol t stream) (values))
969 defprinter-prin1 defprinter-princ))
970 (defun defprinter-prin1 (name value stream)
971 (defprinter-prinx #'prin1 name value stream))
972 (defun defprinter-princ (name value stream)
973 (defprinter-prinx #'princ name value stream))
974 (defun defprinter-prinx (prinx name value stream)
975 (declare (type function prinx))
977 (pprint-newline :linear stream))
978 (format stream ":~A " name)
979 (funcall prinx value stream)
981 (defun defprinter-print-space (stream)
982 (write-char #\space stream))
984 ;;; Define some kind of reasonable PRINT-OBJECT method for a
985 ;;; STRUCTURE-OBJECT class.
987 ;;; NAME is the name of the structure class, and CONC-NAME is the same
990 ;;; The SLOT-DESCS describe how each slot should be printed. Each
991 ;;; SLOT-DESC can be a slot name, indicating that the slot should
992 ;;; simply be printed. A SLOT-DESC may also be a list of a slot name
993 ;;; and other stuff. The other stuff is composed of keywords followed
994 ;;; by expressions. The expressions are evaluated with the variable
995 ;;; which is the slot name bound to the value of the slot. These
996 ;;; keywords are defined:
998 ;;; :PRIN1 Print the value of the expression instead of the slot value.
999 ;;; :PRINC Like :PRIN1, only PRINC the value
1000 ;;; :TEST Only print something if the test is true.
1002 ;;; If no printing thing is specified then the slot value is printed
1005 ;;; The structure being printed is bound to STRUCTURE and the stream
1006 ;;; is bound to STREAM.
1007 (defmacro defprinter ((name
1009 (conc-name (concatenate 'simple-string
1016 (reversed-prints nil)
1017 (stream (gensym "STREAM")))
1018 (flet ((sref (slot-name)
1019 `(,(symbolicate conc-name slot-name) structure)))
1020 (dolist (slot-desc slot-descs)
1022 (setf maybe-print-space nil
1024 (setf maybe-print-space `(defprinter-print-space ,stream)))
1025 (cond ((atom slot-desc)
1026 (push maybe-print-space reversed-prints)
1027 (push `(defprinter-prin1 ',slot-desc ,(sref slot-desc) ,stream)
1030 (let ((sname (first slot-desc))
1033 (do ((option (rest slot-desc) (cddr option)))
1035 (push `(let ((,sname ,(sref sname)))
1040 ',sname ,sname ,stream)))))
1042 (case (first option)
1044 (stuff `(defprinter-prin1
1045 ',sname ,(second option) ,stream)))
1047 (stuff `(defprinter-princ
1048 ',sname ,(second option) ,stream)))
1049 (:test (setq test (second option)))
1051 (error "bad option: ~S" (first option)))))))))))
1052 `(def!method print-object ((structure ,name) ,stream)
1053 (pprint-logical-block (,stream nil)
1054 (print-unreadable-object (structure
1057 :identity ,identity)
1058 ,@(nreverse reversed-prints))))))
1062 ;;; Given a pathname, return a corresponding physical pathname.
1063 (defun physicalize-pathname (possibly-logical-pathname)
1064 (if (typep possibly-logical-pathname 'logical-pathname)
1065 (translate-logical-pathname possibly-logical-pathname)
1066 possibly-logical-pathname))
1068 (defun deprecation-warning (bad-name &optional good-name)
1069 (warn "using deprecated ~S~@[, should use ~S instead~]"
1073 ;;; Anaphoric macros
1074 (defmacro awhen (test &body body)
1078 (defmacro acond (&rest clauses)
1081 (destructuring-bind ((test &body body) &rest rest) clauses
1082 (once-only ((test test))
1084 (let ((it ,test)) (declare (ignorable it)),@body)
1088 ;;; Delayed evaluation
1089 (defmacro delay (form)
1090 `(cons nil (lambda () ,form)))
1092 (defun force (promise)
1093 (cond ((not (consp promise)) promise)
1094 ((car promise) (cdr promise))
1095 (t (setf (car promise) t
1096 (cdr promise) (funcall (cdr promise))))))
1098 (defun promise-ready-p (promise)
1099 (or (not (consp promise))