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)))
84 ;;; FIXME: The SB!KERNEL:INSTANCE here really means CL:CLASS.
85 ;;; However, the CL:CLASS type is only defined once PCL is loaded,
86 ;;; which is before this is evaluated. Once PCL is moved into cold
87 ;;; init, this might be fixable.
88 (def!type type-specifier () '(or list symbol sb!kernel:instance))
90 ;;; the default value used for initializing character data. The ANSI
91 ;;; spec says this is arbitrary, so we use the value that falls
92 ;;; through when we just let the low-level consing code initialize
93 ;;; all newly-allocated memory to zero.
95 ;;; KLUDGE: It might be nice to use something which is a
96 ;;; STANDARD-CHAR, both to reduce user surprise a little and, probably
97 ;;; more significantly, to help SBCL's cross-compiler (which knows how
98 ;;; to dump STANDARD-CHARs). Unfortunately, the old CMU CL code is
99 ;;; shot through with implicit assumptions that it's #\NULL, and code
100 ;;; in several places (notably both DEFUN MAKE-ARRAY and DEFTRANSFORM
101 ;;; MAKE-ARRAY) would have to be rewritten. -- WHN 2001-10-04
102 (eval-when (:compile-toplevel :load-toplevel :execute)
103 ;; an expression we can use to construct a DEFAULT-INIT-CHAR value
104 ;; at load time (so that we don't need to teach the cross-compiler
105 ;; how to represent and dump non-STANDARD-CHARs like #\NULL)
106 (defparameter *default-init-char-form* '(code-char 0)))
108 ;;; CHAR-CODE values for ASCII characters which we care about but
109 ;;; which aren't defined in section "2.1.3 Standard Characters" of the
110 ;;; ANSI specification for Lisp
112 ;;; KLUDGE: These are typically used in the idiom (CODE-CHAR
113 ;;; FOO-CHAR-CODE). I suspect that the current implementation is
114 ;;; expanding this idiom into a full call to CODE-CHAR, which is an
115 ;;; annoying overhead. I should check whether this is happening, and
116 ;;; if so, perhaps implement a DEFTRANSFORM or something to stop it.
117 ;;; (or just find a nicer way of expressing characters portably?) --
119 (def!constant bell-char-code 7)
120 (def!constant backspace-char-code 8)
121 (def!constant tab-char-code 9)
122 (def!constant line-feed-char-code 10)
123 (def!constant form-feed-char-code 12)
124 (def!constant return-char-code 13)
125 (def!constant escape-char-code 27)
126 (def!constant rubout-char-code 127)
128 ;;;; type-ish predicates
130 ;;; Is X a list containing a cycle?
131 (defun cyclic-list-p (x)
133 (labels ((safe-cddr (x) (if (listp (cdr x)) (cddr x))))
134 (do ((y x (safe-cddr y))
137 ((not (and (consp z) (consp y))) nil)
138 (when (and started-p (eq y z))
141 ;;; Is X a (possibly-improper) list of at least N elements?
142 (declaim (ftype (function (t index)) list-of-length-at-least-p))
143 (defun list-of-length-at-least-p (x n)
144 (or (zerop n) ; since anything can be considered an improper list of length 0
146 (list-of-length-at-least-p (cdr x) (1- n)))))
148 (declaim (inline singleton-p))
149 (defun singleton-p (list)
153 ;;; Is X is a positive prime integer?
154 (defun positive-primep (x)
155 ;; This happens to be called only from one place in sbcl-0.7.0, and
156 ;; only for fixnums, we can limit it to fixnums for efficiency. (And
157 ;; if we didn't limit it to fixnums, we should use a cleverer
158 ;; algorithm, since this one scales pretty badly for huge X.)
161 (and (>= x 2) (/= x 4))
163 (not (zerop (rem x 3)))
166 (inc 2 (logxor inc 6)) ;; 2,4,2,4...
168 ((or (= r 0) (> d q)) (/= r 0))
169 (declare (fixnum inc))
170 (multiple-value-setq (q r) (truncate x d))))))
172 ;;; Could this object contain other objects? (This is important to
173 ;;; the implementation of things like *PRINT-CIRCLE* and the dumper.)
174 (defun compound-object-p (x)
177 (typep x '(array t *))))
179 ;;;; the COLLECT macro
181 ;;;; comment from CMU CL: "the ultimate collection macro..."
183 ;;; helper functions for COLLECT, which become the expanders of the
184 ;;; MACROLET definitions created by COLLECT
186 ;;; COLLECT-NORMAL-EXPANDER handles normal collection macros.
188 ;;; COLLECT-LIST-EXPANDER handles the list collection case. N-TAIL
189 ;;; is the pointer to the current tail of the list, or NIL if the list
191 (eval-when (#-sb-xc :compile-toplevel :load-toplevel :execute)
192 (defun collect-normal-expander (n-value fun forms)
194 ,@(mapcar (lambda (form) `(setq ,n-value (,fun ,form ,n-value))) forms)
196 (defun collect-list-expander (n-value n-tail forms)
197 (let ((n-res (gensym)))
199 ,@(mapcar (lambda (form)
200 `(let ((,n-res (cons ,form nil)))
202 (setf (cdr ,n-tail) ,n-res)
203 (setq ,n-tail ,n-res))
205 (setq ,n-tail ,n-res ,n-value ,n-res)))))
209 ;;; Collect some values somehow. Each of the collections specifies a
210 ;;; bunch of things which collected during the evaluation of the body
211 ;;; of the form. The name of the collection is used to define a local
212 ;;; macro, a la MACROLET. Within the body, this macro will evaluate
213 ;;; each of its arguments and collect the result, returning the
214 ;;; current value after the collection is done. The body is evaluated
215 ;;; as a PROGN; to get the final values when you are done, just call
216 ;;; the collection macro with no arguments.
218 ;;; INITIAL-VALUE is the value that the collection starts out with,
219 ;;; which defaults to NIL. FUNCTION is the function which does the
220 ;;; collection. It is a function which will accept two arguments: the
221 ;;; value to be collected and the current collection. The result of
222 ;;; the function is made the new value for the collection. As a
223 ;;; totally magical special-case, FUNCTION may be COLLECT, which tells
224 ;;; us to build a list in forward order; this is the default. If an
225 ;;; INITIAL-VALUE is supplied for COLLECT, the stuff will be RPLACD'd
226 ;;; onto the end. Note that FUNCTION may be anything that can appear
227 ;;; in the functional position, including macros and lambdas.
228 (defmacro collect (collections &body body)
231 (dolist (spec collections)
232 (unless (proper-list-of-length-p spec 1 3)
233 (error "malformed collection specifier: ~S" spec))
234 (let* ((name (first spec))
235 (default (second spec))
236 (kind (or (third spec) 'collect))
237 (n-value (gensym (concatenate 'string
240 (push `(,n-value ,default) binds)
241 (if (eq kind 'collect)
242 (let ((n-tail (gensym (concatenate 'string
246 (push `(,n-tail (last ,n-value)) binds)
248 (push `(,name (&rest args)
249 (collect-list-expander ',n-value ',n-tail args))
251 (push `(,name (&rest args)
252 (collect-normal-expander ',n-value ',kind args))
254 `(macrolet ,macros (let* ,(nreverse binds) ,@body))))
256 ;;;; some old-fashioned functions. (They're not just for old-fashioned
257 ;;;; code, they're also used as optimized forms of the corresponding
258 ;;;; general functions when the compiler can prove that they're
261 ;;; like (MEMBER ITEM LIST :TEST #'EQ)
262 (defun memq (item list)
264 "Return tail of LIST beginning with first element EQ to ITEM."
265 ;; KLUDGE: These could be and probably should be defined as
266 ;; (MEMBER ITEM LIST :TEST #'EQ)),
267 ;; but when I try to cross-compile that, I get an error from
268 ;; LTN-ANALYZE-KNOWN-CALL, "Recursive known function definition". The
269 ;; comments for that error say it "is probably a botched interpreter stub".
270 ;; Rather than try to figure that out, I just rewrote this function from
271 ;; scratch. -- WHN 19990512
272 (do ((i list (cdr i)))
274 (when (eq (car i) item)
277 ;;; like (ASSOC ITEM ALIST :TEST #'EQ):
278 ;;; Return the first pair of ALIST where ITEM is EQ to the key of
280 (defun assq (item alist)
281 ;; KLUDGE: CMU CL defined this with
282 ;; (DECLARE (INLINE ASSOC))
283 ;; (ASSOC ITEM ALIST :TEST #'EQ))
284 ;; which is pretty, but which would have required adding awkward
285 ;; build order constraints on SBCL (or figuring out some way to make
286 ;; inline definitions installable at build-the-cross-compiler time,
287 ;; which was too ambitious for now). Rather than mess with that, we
288 ;; just define ASSQ explicitly in terms of more primitive
291 (when (eq (car pair) item)
294 ;;; like (DELETE .. :TEST #'EQ):
295 ;;; Delete all LIST entries EQ to ITEM (destructively modifying
296 ;;; LIST), and return the modified LIST.
297 (defun delq (item list)
299 (do ((x list (cdr x))
302 (cond ((eq item (car x))
305 (rplacd splice (cdr x))))
306 (t (setq splice x)))))) ; Move splice along to include element.
309 ;;; like (POSITION .. :TEST #'EQ):
310 ;;; Return the position of the first element EQ to ITEM.
311 (defun posq (item list)
312 (do ((i list (cdr i))
315 (when (eq (car i) item)
318 (declaim (inline neq))
322 ;;; not really an old-fashioned function, but what the calling
323 ;;; convention should've been: like NTH, but with the same argument
324 ;;; order as in all the other dereferencing functions, with the
325 ;;; collection first and the index second
326 (declaim (inline nth-but-with-sane-arg-order))
327 (declaim (ftype (function (list index) t) nth-but-with-sane-arg-order))
328 (defun nth-but-with-sane-arg-order (list index)
331 (defun adjust-list (list length initial-element)
332 (let ((old-length (length list)))
333 (cond ((< old-length length)
334 (append list (make-list (- length old-length)
335 :initial-element initial-element)))
336 ((> old-length length)
337 (subseq list 0 length))
340 ;;;; miscellaneous iteration extensions
342 ;;; "the ultimate iteration macro"
344 ;;; note for Schemers: This seems to be identical to Scheme's "named LET".
345 (defmacro named-let (name binds &body body)
348 (unless (proper-list-of-length-p x 2)
349 (error "malformed NAMED-LET variable spec: ~S" x)))
350 `(labels ((,name ,(mapcar #'first binds) ,@body))
351 (,name ,@(mapcar #'second binds))))
353 ;;; just like DOLIST, but with one-dimensional arrays
354 (defmacro dovector ((elt vector &optional result) &rest forms)
355 (let ((index (gensym))
358 `(let ((,vec ,vector))
359 (declare (type vector ,vec))
360 (do ((,index 0 (1+ ,index))
361 (,length (length ,vec)))
362 ((>= ,index ,length) ,result)
363 (let ((,elt (aref ,vec ,index)))
366 ;;; Iterate over the entries in a HASH-TABLE.
367 (defmacro dohash ((key-var value-var table &optional result) &body body)
368 (multiple-value-bind (forms decls) (parse-body body nil)
371 `(with-hash-table-iterator (,gen ,table)
373 (multiple-value-bind (,n-more ,key-var ,value-var) (,gen)
375 (unless ,n-more (return ,result))
378 ;;;; hash cache utility
380 (eval-when (:compile-toplevel :load-toplevel :execute)
381 (defvar *profile-hash-cache* nil))
383 ;;; a flag for whether it's too early in cold init to use caches so
384 ;;; that we have a better chance of recovering so that we have a
385 ;;; better chance of getting the system running so that we have a
386 ;;; better chance of diagnosing the problem which caused us to use the
389 (defvar *hash-caches-initialized-p*)
391 ;;; Define a hash cache that associates some number of argument values
392 ;;; with a result value. The TEST-FUNCTION paired with each ARG-NAME
393 ;;; is used to compare the value for that arg in a cache entry with a
394 ;;; supplied arg. The TEST-FUNCTION must not error when passed NIL as
395 ;;; its first arg, but need not return any particular value.
396 ;;; TEST-FUNCTION may be any thing that can be placed in CAR position.
398 ;;; NAME is used to define these functions:
399 ;;; <name>-CACHE-LOOKUP Arg*
400 ;;; See whether there is an entry for the specified ARGs in the
401 ;;; cache. If not present, the :DEFAULT keyword (default NIL)
402 ;;; determines the result(s).
403 ;;; <name>-CACHE-ENTER Arg* Value*
404 ;;; Encache the association of the specified args with VALUE.
405 ;;; <name>-CACHE-CLEAR
406 ;;; Reinitialize the cache, invalidating all entries and allowing
407 ;;; the arguments and result values to be GC'd.
409 ;;; These other keywords are defined:
411 ;;; The size of the cache as a power of 2.
412 ;;; :HASH-FUNCTION function
413 ;;; Some thing that can be placed in CAR position which will compute
414 ;;; a value between 0 and (1- (expt 2 <hash-bits>)).
416 ;;; the number of return values cached for each function call
417 ;;; :INIT-WRAPPER <name>
418 ;;; The code for initializing the cache is wrapped in a form with
419 ;;; the specified name. (:INIT-WRAPPER is set to COLD-INIT-FORMS
420 ;;; in type system definitions so that caches will be created
421 ;;; before top level forms run.)
422 (defmacro define-hash-cache (name args &key hash-function hash-bits default
423 (init-wrapper 'progn)
425 (let* ((var-name (symbolicate "*" name "-CACHE-VECTOR*"))
426 (nargs (length args))
427 (entry-size (+ nargs values))
428 (size (ash 1 hash-bits))
429 (total-size (* entry-size size))
430 (default-values (if (and (consp default) (eq (car default) 'values))
436 (unless (= (length default-values) values)
437 (error "The number of default values ~S differs from :VALUES ~W."
449 (values-indices `(+ ,n-index ,(+ nargs i)))
450 (values-names (gensym)))
453 (unless (= (length arg) 2)
454 (error "bad argument spec: ~S" arg))
455 (let ((arg-name (first arg))
458 (tests `(,test (svref ,n-cache (+ ,n-index ,n)) ,arg-name))
459 (sets `(setf (svref ,n-cache (+ ,n-index ,n)) ,arg-name)))
462 (when *profile-hash-cache*
463 (let ((n-probe (symbolicate "*" name "-CACHE-PROBES*"))
464 (n-miss (symbolicate "*" name "-CACHE-MISSES*")))
465 (inits `(setq ,n-probe 0))
466 (inits `(setq ,n-miss 0))
467 (forms `(defvar ,n-probe))
468 (forms `(defvar ,n-miss))
469 (forms `(declaim (fixnum ,n-miss ,n-probe)))))
471 (let ((fun-name (symbolicate name "-CACHE-LOOKUP")))
474 `(defun ,fun-name ,(arg-vars)
475 ,@(when *profile-hash-cache*
476 `((incf ,(symbolicate "*" name "-CACHE-PROBES*"))))
477 (let ((,n-index (* (,hash-function ,@(arg-vars)) ,entry-size))
478 (,n-cache ,var-name))
479 (declare (type fixnum ,n-index))
480 (cond ((and ,@(tests))
481 (values ,@(mapcar (lambda (x) `(svref ,n-cache ,x))
484 ,@(when *profile-hash-cache*
485 `((incf ,(symbolicate "*" name "-CACHE-MISSES*"))))
488 (let ((fun-name (symbolicate name "-CACHE-ENTER")))
491 `(defun ,fun-name (,@(arg-vars) ,@(values-names))
492 (let ((,n-index (* (,hash-function ,@(arg-vars)) ,entry-size))
493 (,n-cache ,var-name))
494 (declare (type fixnum ,n-index))
496 ,@(mapcar (lambda (i val)
497 `(setf (svref ,n-cache ,i) ,val))
502 (let ((fun-name (symbolicate name "-CACHE-CLEAR")))
505 (do ((,n-index ,(- total-size entry-size) (- ,n-index ,entry-size))
506 (,n-cache ,var-name))
508 (declare (type fixnum ,n-index))
509 ,@(collect ((arg-sets))
511 (arg-sets `(setf (svref ,n-cache (+ ,n-index ,i)) nil)))
513 ,@(mapcar (lambda (i val)
514 `(setf (svref ,n-cache ,i) ,val))
518 (forms `(,fun-name)))
520 (inits `(unless (boundp ',var-name)
521 (setq ,var-name (make-array ,total-size))))
522 #!+sb-show (inits `(setq *hash-caches-initialized-p* t))
526 (declaim (type (simple-vector ,total-size) ,var-name))
527 #!-sb-fluid (declaim (inline ,@(inlines)))
528 (,init-wrapper ,@(inits))
532 ;;; some syntactic sugar for defining a function whose values are
533 ;;; cached by DEFINE-HASH-CACHE
534 (defmacro defun-cached ((name &rest options &key (values 1) default
536 args &body body-decls-doc)
537 (let ((default-values (if (and (consp default) (eq (car default) 'values))
540 (arg-names (mapcar #'car args)))
541 (collect ((values-names))
543 (values-names (gensym)))
544 (multiple-value-bind (body decls doc) (parse-body body-decls-doc)
546 (define-hash-cache ,name ,args ,@options)
547 (defun ,name ,arg-names
551 ((not (boundp '*hash-caches-initialized-p*))
552 ;; This shouldn't happen, but it did happen to me
553 ;; when revising the type system, and it's a lot
554 ;; easier to figure out what what's going on with
555 ;; that kind of problem if the system can be kept
556 ;; alive until cold boot is complete. The recovery
557 ;; mechanism should definitely be conditional on
558 ;; some debugging feature (e.g. SB-SHOW) because
559 ;; it's big, duplicating all the BODY code. -- WHN
560 (/show0 ,name " too early in cold init, uncached")
561 (/show0 ,(first arg-names) "=..")
562 (/hexstr ,(first arg-names))
565 (multiple-value-bind ,(values-names)
566 (,(symbolicate name "-CACHE-LOOKUP") ,@arg-names)
567 (if (and ,@(mapcar (lambda (val def)
569 (values-names) default-values))
570 (multiple-value-bind ,(values-names)
572 (,(symbolicate name "-CACHE-ENTER") ,@arg-names
574 (values ,@(values-names)))
575 (values ,@(values-names))))))))))))
577 (defmacro define-cached-synonym
578 (name &optional (original (symbolicate "%" name)))
579 (let ((cached-name (symbolicate "%%" name "-cached")))
581 (defun-cached (,cached-name :hash-bits 8
582 :hash-function (lambda (x)
583 (logand (sxhash x) #xff)))
585 (apply #',original args))
586 (defun ,name (&rest args)
587 (,cached-name args)))))
589 ;;; FIXME: maybe not the best place
591 ;;; FIXME: think of a better name -- not only does this not have the
592 ;;; CAR recursion of EQUAL, it also doesn't have the special treatment
593 ;;; of pathnames, bit-vectors and strings.
595 ;;; KLUDGE: This means that we will no longer cache specifiers of the
596 ;;; form '(INTEGER (0) 4). This is probably not a disaster.
598 ;;; A helper function for the type system, which is the main user of
599 ;;; these caches: we must be more conservative than EQUAL for some of
600 ;;; our equality tests, because MEMBER and friends refer to EQLity.
602 (defun equal-but-no-car-recursion (x y)
607 (eql (car x) (car y))
608 (equal-but-no-car-recursion (cdr x) (cdr y))))
613 ;;; Note: Almost always you want to use FIND-UNDELETED-PACKAGE-OR-LOSE
614 ;;; instead of this function. (The distinction only actually matters when
615 ;;; PACKAGE-DESIGNATOR is actually a deleted package, and in that case
616 ;;; you generally do want to signal an error instead of proceeding.)
617 (defun %find-package-or-lose (package-designator)
618 (or (find-package package-designator)
619 (error 'sb!kernel:simple-package-error
620 :package package-designator
621 :format-control "The name ~S does not designate any package."
622 :format-arguments (list package-designator))))
624 ;;; ANSI specifies (in the section for FIND-PACKAGE) that the
625 ;;; consequences of most operations on deleted packages are
626 ;;; unspecified. We try to signal errors in such cases.
627 (defun find-undeleted-package-or-lose (package-designator)
628 (let ((maybe-result (%find-package-or-lose package-designator)))
629 (if (package-name maybe-result) ; if not deleted
631 (error 'sb!kernel:simple-package-error
632 :package maybe-result
633 :format-control "The package ~S has been deleted."
634 :format-arguments (list maybe-result)))))
636 ;;;; various operations on names
638 ;;; Is NAME a legal function name?
639 (defun legal-fun-name-p (name)
640 (values (valid-function-name-p name)))
642 ;;; Signal an error unless NAME is a legal function name.
643 (defun legal-fun-name-or-type-error (name)
644 (unless (legal-fun-name-p name)
645 (error 'simple-type-error
647 :expected-type '(or symbol list)
648 :format-control "invalid function name: ~S"
649 :format-arguments (list name))))
651 ;;; Given a function name, return the symbol embedded in it.
653 ;;; The ordinary use for this operator (and the motivation for the
654 ;;; name of this operator) is to convert from a function name to the
655 ;;; name of the BLOCK which encloses its body.
657 ;;; Occasionally the operator is useful elsewhere, where the operator
658 ;;; name is less mnemonic. (Maybe it should be changed?)
659 (declaim (ftype (function ((or symbol cons)) symbol) fun-name-block-name))
660 (defun fun-name-block-name (fun-name)
661 (cond ((symbolp fun-name)
664 (multiple-value-bind (legalp block-name)
665 (valid-function-name-p fun-name)
668 (error "not legal as a function name: ~S" fun-name))))
670 (error "not legal as a function name: ~S" fun-name))))
672 (defun looks-like-name-of-special-var-p (x)
674 (let ((name (symbol-name x)))
675 (and (> (length name) 2) ; to exclude '* and '**
676 (char= #\* (aref name 0))
677 (char= #\* (aref name (1- (length name))))))))
679 ;;; Some symbols are defined by ANSI to be self-evaluating. Return
680 ;;; non-NIL for such symbols (and make the non-NIL value a traditional
681 ;;; message, for use in contexts where the user asks us to change such
683 (defun symbol-self-evaluating-p (symbol)
684 (declare (type symbol symbol))
686 "Veritas aeterna. (can't change T)")
688 "Nihil ex nihil. (can't change NIL)")
690 "Keyword values can't be changed.")
694 ;;; This function is to be called just before a change which would
695 ;;; affect the symbol value. (We don't absolutely have to call this
696 ;;; function before such changes, since such changes are given as
697 ;;; undefined behavior. In particular, we don't if the runtime cost
698 ;;; would be annoying. But otherwise it's nice to do so.)
699 (defun about-to-modify-symbol-value (symbol)
700 (declare (type symbol symbol))
701 (let ((reason (symbol-self-evaluating-p symbol)))
704 ;; (Note: Just because a value is CONSTANTP is not a good enough
705 ;; reason to complain here, because we want DEFCONSTANT to be able
706 ;; to use this function, and it's legal to DEFCONSTANT a constant as
707 ;; long as the new value is EQL to the old value.)
711 ;;; If COLD-FSET occurs not at top level, just treat it as an ordinary
712 ;;; assignment instead of doing cold static linking. That way things like
713 ;;; (FLET ((FROB (X) ..))
714 ;;; (DEFUN FOO (X Y) (FROB X) ..)
715 ;;; (DEFUN BAR (Z) (AND (FROB X) ..)))
716 ;;; can still "work" for cold init: they don't do magical static
717 ;;; linking the way that true toplevel DEFUNs do, but at least they do
718 ;;; the linking eventually, so as long as #'FOO and #'BAR aren't
719 ;;; needed until "cold toplevel forms" have executed, it's OK.
720 (defmacro cold-fset (name lambda)
722 "~@<COLD-FSET ~S not cross-compiled at top level: demoting to ~
723 (SETF FDEFINITION)~:@>"
725 ;; We convert the LAMBDA expression to the corresponding NAMED-LAMBDA
726 ;; expression so that the compiler can use NAME in debug names etc.
727 (destructuring-bind (lambda-symbol &rest lambda-rest) lambda
728 (assert (eql lambda-symbol 'lambda)) ; else dunno how to do conversion
729 `(setf (fdefinition ',name)
730 (named-lambda ,name ,@lambda-rest))))
734 ;;;; "The macro ONCE-ONLY has been around for a long time on various
735 ;;;; systems [..] if you can understand how to write and when to use
736 ;;;; ONCE-ONLY, then you truly understand macro." -- Peter Norvig,
737 ;;;; _Paradigms of Artificial Intelligence Programming: Case Studies
738 ;;;; in Common Lisp_, p. 853
740 ;;; ONCE-ONLY is a utility useful in writing source transforms and
741 ;;; macros. It provides a concise way to wrap a LET around some code
742 ;;; to ensure that some forms are only evaluated once.
744 ;;; Create a LET* which evaluates each value expression, binding a
745 ;;; temporary variable to the result, and wrapping the LET* around the
746 ;;; result of the evaluation of BODY. Within the body, each VAR is
747 ;;; bound to the corresponding temporary variable.
748 (defmacro once-only (specs &body body)
749 (named-let frob ((specs specs)
753 (let ((spec (first specs)))
754 ;; FIXME: should just be DESTRUCTURING-BIND of SPEC
755 (unless (proper-list-of-length-p spec 2)
756 (error "malformed ONCE-ONLY binding spec: ~S" spec))
757 (let* ((name (first spec))
758 (exp-temp (gensym (symbol-name name))))
759 `(let ((,exp-temp ,(second spec))
760 (,name (gensym "ONCE-ONLY-")))
761 `(let ((,,name ,,exp-temp))
762 ,,(frob (rest specs) body))))))))
764 ;;;; various error-checking utilities
766 ;;; This function can be used as the default value for keyword
767 ;;; arguments that must be always be supplied. Since it is known by
768 ;;; the compiler to never return, it will avoid any compile-time type
769 ;;; warnings that would result from a default value inconsistent with
770 ;;; the declared type. When this function is called, it signals an
771 ;;; error indicating that a required &KEY argument was not supplied.
772 ;;; This function is also useful for DEFSTRUCT slot defaults
773 ;;; corresponding to required arguments.
774 (declaim (ftype (function () nil) missing-arg))
775 (defun missing-arg ()
777 (/show0 "entering MISSING-ARG")
778 (error "A required &KEY or &OPTIONAL argument was not supplied."))
780 ;;; like CL:ASSERT and CL:CHECK-TYPE, but lighter-weight
782 ;;; (As of sbcl-0.6.11.20, we were using some 400 calls to CL:ASSERT.
783 ;;; The CL:ASSERT restarts and whatnot expand into a significant
784 ;;; amount of code when you multiply them by 400, so replacing them
785 ;;; with this should reduce the size of the system by enough to be
786 ;;; worthwhile. ENFORCE-TYPE is much less common, but might still be
787 ;;; worthwhile, and since I don't really like CERROR stuff deep in the
788 ;;; guts of complex systems anyway, I replaced it too.)
789 (defmacro aver (expr)
791 (%failed-aver ,(format nil "~A" expr))))
793 (defun %failed-aver (expr-as-string)
794 (bug "~@<failed AVER: ~2I~_~S~:>" expr-as-string))
796 ;;; We need a definition of BUG here for the host compiler to be able
797 ;;; to deal with BUGs in sbcl. This should never affect an end-user,
798 ;;; who will pick up the definition that signals a CONDITION of
799 ;;; condition-class BUG; however, this is not defined on the host
800 ;;; lisp, but for the target. SBCL developers sometimes trigger BUGs
801 ;;; in their efforts, and it is useful to get the details of the BUG
802 ;;; rather than an undefined function error. - CSR, 2002-04-12
804 (defun bug (format-control &rest format-arguments)
806 :format-control "~@< ~? ~:@_~?~:>"
807 :format-arguments `(,format-control
809 "~@<If you see this and are an SBCL ~
810 developer, then it is probable that you have made a change to the ~
811 system that has broken the ability for SBCL to compile, usually by ~
812 removing an assumed invariant of the system, but sometimes by making ~
813 an averrance that is violated (check your code!). If you are a user, ~
814 please submit a bug report to the developers' mailing list, details of ~
815 which can be found at <http://sbcl.sourceforge.net/>.~:@>"
818 (defmacro enforce-type (value type)
819 (once-only ((value value))
820 `(unless (typep ,value ',type)
821 (%failed-enforce-type ,value ',type))))
823 (defun %failed-enforce-type (value type)
824 (error 'simple-type-error ; maybe should be TYPE-BUG, subclass of BUG?
827 :format-control "~@<~S ~_is not a ~_~S~:>"
828 :format-arguments (list value type)))
830 ;;; Return a function like FUN, but expecting its (two) arguments in
831 ;;; the opposite order that FUN does.
832 (declaim (inline swapped-args-fun))
833 (defun swapped-args-fun (fun)
834 (declare (type function fun))
838 ;;; Return the numeric value of a type bound, i.e. an interval bound
839 ;;; more or less in the format of bounds in ANSI's type specifiers,
840 ;;; where a bare numeric value is a closed bound and a list of a
841 ;;; single numeric value is an open bound.
843 ;;; The "more or less" bit is that the no-bound-at-all case is
844 ;;; represented by NIL (not by * as in ANSI type specifiers); and in
845 ;;; this case we return NIL.
846 (defun type-bound-number (x)
848 (destructuring-bind (result) x result)
851 ;;; some commonly-occuring CONSTANTLY forms
852 (macrolet ((def-constantly-fun (name constant-expr)
853 `(setf (symbol-function ',name)
854 (constantly ,constant-expr))))
855 (def-constantly-fun constantly-t t)
856 (def-constantly-fun constantly-nil nil)
857 (def-constantly-fun constantly-0 0))
859 ;;; If X is an atom, see whether it is present in *FEATURES*. Also
860 ;;; handle arbitrary combinations of atoms using NOT, AND, OR.
866 (error "too many subexpressions in feature expression: ~S" x)
867 (not (featurep (cadr x)))))
868 ((:and and) (every #'featurep (cdr x)))
869 ((:or or) (some #'featurep (cdr x)))
871 (error "unknown operator in feature expression: ~S." x)))
872 (not (null (memq x *features*)))))
874 ;;; Given a list of keyword substitutions `(,OLD ,NEW), and a
875 ;;; &KEY-argument-list-style list of alternating keywords and
876 ;;; arbitrary values, return a new &KEY-argument-list-style list with
877 ;;; all substitutions applied to it.
879 ;;; Note: If efficiency mattered, we could do less consing. (But if
880 ;;; efficiency mattered, why would we be using &KEY arguments at
881 ;;; all, much less renaming &KEY arguments?)
883 ;;; KLUDGE: It would probably be good to get rid of this. -- WHN 19991201
884 (defun rename-key-args (rename-list key-args)
885 (declare (type list rename-list key-args))
886 ;; Walk through RENAME-LIST modifying RESULT as per each element in
888 (do ((result (copy-list key-args))) ; may be modified below
889 ((null rename-list) result)
890 (destructuring-bind (old new) (pop rename-list)
891 ;; ANSI says &KEY arg names aren't necessarily KEYWORDs.
892 (declare (type symbol old new))
893 ;; Walk through RESULT renaming any OLD key argument to NEW.
894 (do ((in-result result (cddr in-result)))
896 (declare (type list in-result))
897 (when (eq (car in-result) old)
898 (setf (car in-result) new))))))
900 ;;; ANSI Common Lisp's READ-SEQUENCE function, unlike most of the
901 ;;; other ANSI input functions, is defined to communicate end of file
902 ;;; status with its return value, not by signalling. That is not the
903 ;;; behavior that we usually want. This function is a wrapper which
904 ;;; restores the behavior that we usually want, causing READ-SEQUENCE
905 ;;; to communicate end-of-file status by signalling.
906 (defun read-sequence-or-die (sequence stream &key start end)
907 ;; implementation using READ-SEQUENCE
908 #-no-ansi-read-sequence
909 (let ((read-end (read-sequence sequence
913 (unless (= read-end end)
914 (error 'end-of-file :stream stream))
916 ;; workaround for broken READ-SEQUENCE
917 #+no-ansi-read-sequence
919 (aver (<= start end))
920 (let ((etype (stream-element-type stream)))
921 (cond ((equal etype '(unsigned-byte 8))
922 (do ((i start (1+ i)))
925 (setf (aref sequence i)
926 (read-byte stream))))
927 (t (error "unsupported element type ~S" etype))))))
929 ;;;; utilities for two-VALUES predicates
931 (defmacro not/type (x)
932 (let ((val (gensym "VAL"))
933 (win (gensym "WIN")))
934 `(multiple-value-bind (,val ,win)
937 (values (not ,val) t)
940 (defmacro and/type (x y)
941 `(multiple-value-bind (val1 win1) ,x
942 (if (and (not val1) win1)
944 (multiple-value-bind (val2 win2) ,y
947 (values nil (and win2 (not val2))))))))
949 ;;; sort of like ANY and EVERY, except:
950 ;;; * We handle two-VALUES predicate functions, as SUBTYPEP does.
951 ;;; (And if the result is uncertain, then we return (VALUES NIL NIL),
952 ;;; as SUBTYPEP does.)
953 ;;; * THING is just an atom, and we apply OP (an arity-2 function)
954 ;;; successively to THING and each element of LIST.
955 (defun any/type (op thing list)
956 (declare (type function op))
958 (dolist (i list (values nil certain?))
959 (multiple-value-bind (sub-value sub-certain?) (funcall op thing i)
961 (when sub-value (return (values t t)))
962 (setf certain? nil))))))
963 (defun every/type (op thing list)
964 (declare (type function op))
966 (dolist (i list (if certain? (values t t) (values nil nil)))
967 (multiple-value-bind (sub-value sub-certain?) (funcall op thing i)
969 (unless sub-value (return (values nil t)))
970 (setf certain? nil))))))
974 ;;; These functions are called by the expansion of the DEFPRINTER
975 ;;; macro to do the actual printing.
976 (declaim (ftype (function (symbol t stream) (values))
977 defprinter-prin1 defprinter-princ))
978 (defun defprinter-prin1 (name value stream)
979 (defprinter-prinx #'prin1 name value stream))
980 (defun defprinter-princ (name value stream)
981 (defprinter-prinx #'princ name value stream))
982 (defun defprinter-prinx (prinx name value stream)
983 (declare (type function prinx))
985 (pprint-newline :linear stream))
986 (format stream ":~A " name)
987 (funcall prinx value stream)
989 (defun defprinter-print-space (stream)
990 (write-char #\space stream))
992 ;;; Define some kind of reasonable PRINT-OBJECT method for a
993 ;;; STRUCTURE-OBJECT class.
995 ;;; NAME is the name of the structure class, and CONC-NAME is the same
998 ;;; The SLOT-DESCS describe how each slot should be printed. Each
999 ;;; SLOT-DESC can be a slot name, indicating that the slot should
1000 ;;; simply be printed. A SLOT-DESC may also be a list of a slot name
1001 ;;; and other stuff. The other stuff is composed of keywords followed
1002 ;;; by expressions. The expressions are evaluated with the variable
1003 ;;; which is the slot name bound to the value of the slot. These
1004 ;;; keywords are defined:
1006 ;;; :PRIN1 Print the value of the expression instead of the slot value.
1007 ;;; :PRINC Like :PRIN1, only PRINC the value
1008 ;;; :TEST Only print something if the test is true.
1010 ;;; If no printing thing is specified then the slot value is printed
1013 ;;; The structure being printed is bound to STRUCTURE and the stream
1014 ;;; is bound to STREAM.
1015 (defmacro defprinter ((name
1017 (conc-name (concatenate 'simple-string
1024 (reversed-prints nil)
1025 (stream (gensym "STREAM")))
1026 (flet ((sref (slot-name)
1027 `(,(symbolicate conc-name slot-name) structure)))
1028 (dolist (slot-desc slot-descs)
1030 (setf maybe-print-space nil
1032 (setf maybe-print-space `(defprinter-print-space ,stream)))
1033 (cond ((atom slot-desc)
1034 (push maybe-print-space reversed-prints)
1035 (push `(defprinter-prin1 ',slot-desc ,(sref slot-desc) ,stream)
1038 (let ((sname (first slot-desc))
1041 (do ((option (rest slot-desc) (cddr option)))
1043 (push `(let ((,sname ,(sref sname)))
1048 ',sname ,sname ,stream)))))
1050 (case (first option)
1052 (stuff `(defprinter-prin1
1053 ',sname ,(second option) ,stream)))
1055 (stuff `(defprinter-princ
1056 ',sname ,(second option) ,stream)))
1057 (:test (setq test (second option)))
1059 (error "bad option: ~S" (first option)))))))))))
1060 `(def!method print-object ((structure ,name) ,stream)
1061 (pprint-logical-block (,stream nil)
1062 (print-unreadable-object (structure
1065 :identity ,identity)
1066 ,@(nreverse reversed-prints))))))
1070 ;;; Given a pathname, return a corresponding physical pathname.
1071 (defun physicalize-pathname (possibly-logical-pathname)
1072 (if (typep possibly-logical-pathname 'logical-pathname)
1073 (translate-logical-pathname possibly-logical-pathname)
1074 possibly-logical-pathname))
1076 (defun deprecation-warning (bad-name &optional good-name)
1077 (warn "using deprecated ~S~@[, should use ~S instead~]"
1081 ;;; Anaphoric macros
1082 (defmacro awhen (test &body body)
1086 (defmacro acond (&rest clauses)
1089 (destructuring-bind ((test &body body) &rest rest) clauses
1090 (once-only ((test test))
1092 (let ((it ,test)) (declare (ignorable it)),@body)
1096 ;;; Delayed evaluation
1097 (defmacro delay (form)
1098 `(cons nil (lambda () ,form)))
1100 (defun force (promise)
1101 (cond ((not (consp promise)) promise)
1102 ((car promise) (cdr promise))
1103 (t (setf (car promise) t
1104 (cdr promise) (funcall (cdr promise))))))
1106 (defun promise-ready-p (promise)
1107 (or (not (consp promise))