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 ;; though it may look more natural to write this as
292 ;; (AND PAIR (EQ (CAR PAIR) ITEM))
293 ;; the temptation to do so should be resisted, as pointed out by PFD
294 ;; sbcl-devel 2003-08-16, as NIL elements are rare in association
295 ;; lists. -- CSR, 2003-08-16
296 (when (and (eq (car pair) item) (not (null pair)))
299 ;;; like (DELETE .. :TEST #'EQ):
300 ;;; Delete all LIST entries EQ to ITEM (destructively modifying
301 ;;; LIST), and return the modified LIST.
302 (defun delq (item list)
304 (do ((x list (cdr x))
307 (cond ((eq item (car x))
310 (rplacd splice (cdr x))))
311 (t (setq splice x)))))) ; Move splice along to include element.
314 ;;; like (POSITION .. :TEST #'EQ):
315 ;;; Return the position of the first element EQ to ITEM.
316 (defun posq (item list)
317 (do ((i list (cdr i))
320 (when (eq (car i) item)
323 (declaim (inline neq))
327 ;;; not really an old-fashioned function, but what the calling
328 ;;; convention should've been: like NTH, but with the same argument
329 ;;; order as in all the other dereferencing functions, with the
330 ;;; collection first and the index second
331 (declaim (inline nth-but-with-sane-arg-order))
332 (declaim (ftype (function (list index) t) nth-but-with-sane-arg-order))
333 (defun nth-but-with-sane-arg-order (list index)
336 (defun adjust-list (list length initial-element)
337 (let ((old-length (length list)))
338 (cond ((< old-length length)
339 (append list (make-list (- length old-length)
340 :initial-element initial-element)))
341 ((> old-length length)
342 (subseq list 0 length))
345 ;;;; miscellaneous iteration extensions
347 ;;; "the ultimate iteration macro"
349 ;;; note for Schemers: This seems to be identical to Scheme's "named LET".
350 (defmacro named-let (name binds &body body)
353 (unless (proper-list-of-length-p x 2)
354 (error "malformed NAMED-LET variable spec: ~S" x)))
355 `(labels ((,name ,(mapcar #'first binds) ,@body))
356 (,name ,@(mapcar #'second binds))))
358 ;;; just like DOLIST, but with one-dimensional arrays
359 (defmacro dovector ((elt vector &optional result) &rest forms)
360 (let ((index (gensym))
363 `(let ((,vec ,vector))
364 (declare (type vector ,vec))
365 (do ((,index 0 (1+ ,index))
366 (,length (length ,vec)))
367 ((>= ,index ,length) ,result)
368 (let ((,elt (aref ,vec ,index)))
371 ;;; Iterate over the entries in a HASH-TABLE.
372 (defmacro dohash ((key-var value-var table &optional result) &body body)
373 (multiple-value-bind (forms decls) (parse-body body :doc-string-allowed nil)
376 `(with-hash-table-iterator (,gen ,table)
378 (multiple-value-bind (,n-more ,key-var ,value-var) (,gen)
380 (unless ,n-more (return ,result))
383 ;;;; hash cache utility
385 (eval-when (:compile-toplevel :load-toplevel :execute)
386 (defvar *profile-hash-cache* nil))
388 ;;; a flag for whether it's too early in cold init to use caches so
389 ;;; that we have a better chance of recovering so that we have a
390 ;;; better chance of getting the system running so that we have a
391 ;;; better chance of diagnosing the problem which caused us to use the
394 (defvar *hash-caches-initialized-p*)
396 ;;; Define a hash cache that associates some number of argument values
397 ;;; with a result value. The TEST-FUNCTION paired with each ARG-NAME
398 ;;; is used to compare the value for that arg in a cache entry with a
399 ;;; supplied arg. The TEST-FUNCTION must not error when passed NIL as
400 ;;; its first arg, but need not return any particular value.
401 ;;; TEST-FUNCTION may be any thing that can be placed in CAR position.
403 ;;; NAME is used to define these functions:
404 ;;; <name>-CACHE-LOOKUP Arg*
405 ;;; See whether there is an entry for the specified ARGs in the
406 ;;; cache. If not present, the :DEFAULT keyword (default NIL)
407 ;;; determines the result(s).
408 ;;; <name>-CACHE-ENTER Arg* Value*
409 ;;; Encache the association of the specified args with VALUE.
410 ;;; <name>-CACHE-CLEAR
411 ;;; Reinitialize the cache, invalidating all entries and allowing
412 ;;; the arguments and result values to be GC'd.
414 ;;; These other keywords are defined:
416 ;;; The size of the cache as a power of 2.
417 ;;; :HASH-FUNCTION function
418 ;;; Some thing that can be placed in CAR position which will compute
419 ;;; a value between 0 and (1- (expt 2 <hash-bits>)).
421 ;;; the number of return values cached for each function call
422 ;;; :INIT-WRAPPER <name>
423 ;;; The code for initializing the cache is wrapped in a form with
424 ;;; the specified name. (:INIT-WRAPPER is set to COLD-INIT-FORMS
425 ;;; in type system definitions so that caches will be created
426 ;;; before top level forms run.)
427 (defmacro define-hash-cache (name args &key hash-function hash-bits default
428 (init-wrapper 'progn)
430 (let* ((var-name (symbolicate "*" name "-CACHE-VECTOR*"))
431 (nargs (length args))
432 (entry-size (+ nargs values))
433 (size (ash 1 hash-bits))
434 (total-size (* entry-size size))
435 (default-values (if (and (consp default) (eq (car default) 'values))
441 (unless (= (length default-values) values)
442 (error "The number of default values ~S differs from :VALUES ~W."
454 (values-indices `(+ ,n-index ,(+ nargs i)))
455 (values-names (gensym)))
458 (unless (= (length arg) 2)
459 (error "bad argument spec: ~S" arg))
460 (let ((arg-name (first arg))
463 (tests `(,test (svref ,n-cache (+ ,n-index ,n)) ,arg-name))
464 (sets `(setf (svref ,n-cache (+ ,n-index ,n)) ,arg-name)))
467 (when *profile-hash-cache*
468 (let ((n-probe (symbolicate "*" name "-CACHE-PROBES*"))
469 (n-miss (symbolicate "*" name "-CACHE-MISSES*")))
470 (inits `(setq ,n-probe 0))
471 (inits `(setq ,n-miss 0))
472 (forms `(defvar ,n-probe))
473 (forms `(defvar ,n-miss))
474 (forms `(declaim (fixnum ,n-miss ,n-probe)))))
476 (let ((fun-name (symbolicate name "-CACHE-LOOKUP")))
479 `(defun ,fun-name ,(arg-vars)
480 ,@(when *profile-hash-cache*
481 `((incf ,(symbolicate "*" name "-CACHE-PROBES*"))))
482 (let ((,n-index (* (,hash-function ,@(arg-vars)) ,entry-size))
483 (,n-cache ,var-name))
484 (declare (type fixnum ,n-index))
485 (cond ((and ,@(tests))
486 (values ,@(mapcar (lambda (x) `(svref ,n-cache ,x))
489 ,@(when *profile-hash-cache*
490 `((incf ,(symbolicate "*" name "-CACHE-MISSES*"))))
493 (let ((fun-name (symbolicate name "-CACHE-ENTER")))
496 `(defun ,fun-name (,@(arg-vars) ,@(values-names))
497 (let ((,n-index (* (,hash-function ,@(arg-vars)) ,entry-size))
498 (,n-cache ,var-name))
499 (declare (type fixnum ,n-index))
501 ,@(mapcar (lambda (i val)
502 `(setf (svref ,n-cache ,i) ,val))
507 (let ((fun-name (symbolicate name "-CACHE-CLEAR")))
510 (do ((,n-index ,(- total-size entry-size) (- ,n-index ,entry-size))
511 (,n-cache ,var-name))
513 (declare (type fixnum ,n-index))
514 ,@(collect ((arg-sets))
516 (arg-sets `(setf (svref ,n-cache (+ ,n-index ,i)) nil)))
518 ,@(mapcar (lambda (i val)
519 `(setf (svref ,n-cache ,i) ,val))
523 (forms `(,fun-name)))
525 (inits `(unless (boundp ',var-name)
526 (setq ,var-name (make-array ,total-size))))
527 #!+sb-show (inits `(setq *hash-caches-initialized-p* t))
531 (declaim (type (simple-vector ,total-size) ,var-name))
532 #!-sb-fluid (declaim (inline ,@(inlines)))
533 (,init-wrapper ,@(inits))
537 ;;; some syntactic sugar for defining a function whose values are
538 ;;; cached by DEFINE-HASH-CACHE
539 (defmacro defun-cached ((name &rest options &key (values 1) default
541 args &body body-decls-doc)
542 (let ((default-values (if (and (consp default) (eq (car default) 'values))
545 (arg-names (mapcar #'car args)))
546 (collect ((values-names))
548 (values-names (gensym)))
549 (multiple-value-bind (body decls doc) (parse-body body-decls-doc)
551 (define-hash-cache ,name ,args ,@options)
552 (defun ,name ,arg-names
556 ((not (boundp '*hash-caches-initialized-p*))
557 ;; This shouldn't happen, but it did happen to me
558 ;; when revising the type system, and it's a lot
559 ;; easier to figure out what what's going on with
560 ;; that kind of problem if the system can be kept
561 ;; alive until cold boot is complete. The recovery
562 ;; mechanism should definitely be conditional on
563 ;; some debugging feature (e.g. SB-SHOW) because
564 ;; it's big, duplicating all the BODY code. -- WHN
565 (/show0 ,name " too early in cold init, uncached")
566 (/show0 ,(first arg-names) "=..")
567 (/hexstr ,(first arg-names))
570 (multiple-value-bind ,(values-names)
571 (,(symbolicate name "-CACHE-LOOKUP") ,@arg-names)
572 (if (and ,@(mapcar (lambda (val def)
574 (values-names) default-values))
575 (multiple-value-bind ,(values-names)
577 (,(symbolicate name "-CACHE-ENTER") ,@arg-names
579 (values ,@(values-names)))
580 (values ,@(values-names))))))))))))
582 (defmacro define-cached-synonym
583 (name &optional (original (symbolicate "%" name)))
584 (let ((cached-name (symbolicate "%%" name "-CACHED")))
586 (defun-cached (,cached-name :hash-bits 8
587 :hash-function (lambda (x)
588 (logand (sxhash x) #xff)))
590 (apply #',original args))
591 (defun ,name (&rest args)
592 (,cached-name args)))))
594 ;;; FIXME: maybe not the best place
596 ;;; FIXME: think of a better name -- not only does this not have the
597 ;;; CAR recursion of EQUAL, it also doesn't have the special treatment
598 ;;; of pathnames, bit-vectors and strings.
600 ;;; KLUDGE: This means that we will no longer cache specifiers of the
601 ;;; form '(INTEGER (0) 4). This is probably not a disaster.
603 ;;; A helper function for the type system, which is the main user of
604 ;;; these caches: we must be more conservative than EQUAL for some of
605 ;;; our equality tests, because MEMBER and friends refer to EQLity.
607 (defun equal-but-no-car-recursion (x y)
612 (eql (car x) (car y))
613 (equal-but-no-car-recursion (cdr x) (cdr y))))
618 ;;; Note: Almost always you want to use FIND-UNDELETED-PACKAGE-OR-LOSE
619 ;;; instead of this function. (The distinction only actually matters when
620 ;;; PACKAGE-DESIGNATOR is actually a deleted package, and in that case
621 ;;; you generally do want to signal an error instead of proceeding.)
622 (defun %find-package-or-lose (package-designator)
623 (or (find-package package-designator)
624 (error 'sb!kernel:simple-package-error
625 :package package-designator
626 :format-control "The name ~S does not designate any package."
627 :format-arguments (list package-designator))))
629 ;;; ANSI specifies (in the section for FIND-PACKAGE) that the
630 ;;; consequences of most operations on deleted packages are
631 ;;; unspecified. We try to signal errors in such cases.
632 (defun find-undeleted-package-or-lose (package-designator)
633 (let ((maybe-result (%find-package-or-lose package-designator)))
634 (if (package-name maybe-result) ; if not deleted
636 (error 'sb!kernel:simple-package-error
637 :package maybe-result
638 :format-control "The package ~S has been deleted."
639 :format-arguments (list maybe-result)))))
641 ;;;; various operations on names
643 ;;; Is NAME a legal function name?
644 (declaim (inline legal-fun-name-p))
645 (defun legal-fun-name-p (name)
646 (values (valid-function-name-p name)))
648 (deftype function-name () '(satisfies legal-fun-name-p))
650 ;;; Signal an error unless NAME is a legal function name.
651 (defun legal-fun-name-or-type-error (name)
652 (unless (legal-fun-name-p name)
653 (error 'simple-type-error
655 :expected-type 'function-name
656 :format-control "invalid function name: ~S"
657 :format-arguments (list name))))
659 ;;; Given a function name, return the symbol embedded in it.
661 ;;; The ordinary use for this operator (and the motivation for the
662 ;;; name of this operator) is to convert from a function name to the
663 ;;; name of the BLOCK which encloses its body.
665 ;;; Occasionally the operator is useful elsewhere, where the operator
666 ;;; name is less mnemonic. (Maybe it should be changed?)
667 (declaim (ftype (function ((or symbol cons)) symbol) fun-name-block-name))
668 (defun fun-name-block-name (fun-name)
669 (cond ((symbolp fun-name)
672 (multiple-value-bind (legalp block-name)
673 (valid-function-name-p fun-name)
676 (error "not legal as a function name: ~S" fun-name))))
678 (error "not legal as a function name: ~S" fun-name))))
680 (defun looks-like-name-of-special-var-p (x)
682 (let ((name (symbol-name x)))
683 (and (> (length name) 2) ; to exclude '* and '**
684 (char= #\* (aref name 0))
685 (char= #\* (aref name (1- (length name))))))))
687 ;;; Some symbols are defined by ANSI to be self-evaluating. Return
688 ;;; non-NIL for such symbols (and make the non-NIL value a traditional
689 ;;; message, for use in contexts where the user asks us to change such
691 (defun symbol-self-evaluating-p (symbol)
692 (declare (type symbol symbol))
694 "Veritas aeterna. (can't change T)")
696 "Nihil ex nihil. (can't change NIL)")
698 "Keyword values can't be changed.")
702 ;;; This function is to be called just before a change which would
703 ;;; affect the symbol value. (We don't absolutely have to call this
704 ;;; function before such changes, since such changes are given as
705 ;;; undefined behavior. In particular, we don't if the runtime cost
706 ;;; would be annoying. But otherwise it's nice to do so.)
707 (defun about-to-modify-symbol-value (symbol)
708 (declare (type symbol symbol))
709 (let ((reason (symbol-self-evaluating-p symbol)))
712 ;; (Note: Just because a value is CONSTANTP is not a good enough
713 ;; reason to complain here, because we want DEFCONSTANT to be able
714 ;; to use this function, and it's legal to DEFCONSTANT a constant as
715 ;; long as the new value is EQL to the old value.)
719 ;;; If COLD-FSET occurs not at top level, just treat it as an ordinary
720 ;;; assignment instead of doing cold static linking. That way things like
721 ;;; (FLET ((FROB (X) ..))
722 ;;; (DEFUN FOO (X Y) (FROB X) ..)
723 ;;; (DEFUN BAR (Z) (AND (FROB X) ..)))
724 ;;; can still "work" for cold init: they don't do magical static
725 ;;; linking the way that true toplevel DEFUNs do, but at least they do
726 ;;; the linking eventually, so as long as #'FOO and #'BAR aren't
727 ;;; needed until "cold toplevel forms" have executed, it's OK.
728 (defmacro cold-fset (name lambda)
730 "~@<COLD-FSET ~S not cross-compiled at top level: demoting to ~
731 (SETF FDEFINITION)~:@>"
733 ;; We convert the LAMBDA expression to the corresponding NAMED-LAMBDA
734 ;; expression so that the compiler can use NAME in debug names etc.
735 (destructuring-bind (lambda-symbol &rest lambda-rest) lambda
736 (assert (eql lambda-symbol 'lambda)) ; else dunno how to do conversion
737 `(setf (fdefinition ',name)
738 (named-lambda ,name ,@lambda-rest))))
742 ;;;; "The macro ONCE-ONLY has been around for a long time on various
743 ;;;; systems [..] if you can understand how to write and when to use
744 ;;;; ONCE-ONLY, then you truly understand macro." -- Peter Norvig,
745 ;;;; _Paradigms of Artificial Intelligence Programming: Case Studies
746 ;;;; in Common Lisp_, p. 853
748 ;;; ONCE-ONLY is a utility useful in writing source transforms and
749 ;;; macros. It provides a concise way to wrap a LET around some code
750 ;;; to ensure that some forms are only evaluated once.
752 ;;; Create a LET* which evaluates each value expression, binding a
753 ;;; temporary variable to the result, and wrapping the LET* around the
754 ;;; result of the evaluation of BODY. Within the body, each VAR is
755 ;;; bound to the corresponding temporary variable.
756 (defmacro once-only (specs &body body)
757 (named-let frob ((specs specs)
761 (let ((spec (first specs)))
762 ;; FIXME: should just be DESTRUCTURING-BIND of SPEC
763 (unless (proper-list-of-length-p spec 2)
764 (error "malformed ONCE-ONLY binding spec: ~S" spec))
765 (let* ((name (first spec))
766 (exp-temp (gensym (symbol-name name))))
767 `(let ((,exp-temp ,(second spec))
768 (,name (gensym "ONCE-ONLY-")))
769 `(let ((,,name ,,exp-temp))
770 ,,(frob (rest specs) body))))))))
772 ;;;; various error-checking utilities
774 ;;; This function can be used as the default value for keyword
775 ;;; arguments that must be always be supplied. Since it is known by
776 ;;; the compiler to never return, it will avoid any compile-time type
777 ;;; warnings that would result from a default value inconsistent with
778 ;;; the declared type. When this function is called, it signals an
779 ;;; error indicating that a required &KEY argument was not supplied.
780 ;;; This function is also useful for DEFSTRUCT slot defaults
781 ;;; corresponding to required arguments.
782 (declaim (ftype (function () nil) missing-arg))
783 (defun missing-arg ()
785 (/show0 "entering MISSING-ARG")
786 (error "A required &KEY or &OPTIONAL argument was not supplied."))
788 ;;; like CL:ASSERT and CL:CHECK-TYPE, but lighter-weight
790 ;;; (As of sbcl-0.6.11.20, we were using some 400 calls to CL:ASSERT.
791 ;;; The CL:ASSERT restarts and whatnot expand into a significant
792 ;;; amount of code when you multiply them by 400, so replacing them
793 ;;; with this should reduce the size of the system by enough to be
794 ;;; worthwhile. ENFORCE-TYPE is much less common, but might still be
795 ;;; worthwhile, and since I don't really like CERROR stuff deep in the
796 ;;; guts of complex systems anyway, I replaced it too.)
797 (defmacro aver (expr)
799 (%failed-aver ,(format nil "~A" expr))))
801 (defun %failed-aver (expr-as-string)
802 ;; hackish way to tell we're in a cold sbcl and output the
803 ;; message before signallign error, as it may be this is too
804 ;; early in the cold init.
805 (when (find-package "SB!C")
807 (write-line "failed AVER:")
808 (write-line expr-as-string)
810 (bug "~@<failed AVER: ~2I~_~S~:>" expr-as-string))
812 (defun bug (format-control &rest format-arguments)
814 :format-control format-control
815 :format-arguments format-arguments))
817 (defmacro enforce-type (value type)
818 (once-only ((value value))
819 `(unless (typep ,value ',type)
820 (%failed-enforce-type ,value ',type))))
822 (defun %failed-enforce-type (value type)
823 ;; maybe should be TYPE-BUG, subclass of BUG? If it is changed,
824 ;; check uses of it in user-facing code (e.g. WARN)
825 (error 'simple-type-error
828 :format-control "~@<~S ~_is not a ~_~S~:>"
829 :format-arguments (list value type)))
831 ;;; Return a function like FUN, but expecting its (two) arguments in
832 ;;; the opposite order that FUN does.
833 (declaim (inline swapped-args-fun))
834 (defun swapped-args-fun (fun)
835 (declare (type function fun))
839 ;;; Return the numeric value of a type bound, i.e. an interval bound
840 ;;; more or less in the format of bounds in ANSI's type specifiers,
841 ;;; where a bare numeric value is a closed bound and a list of a
842 ;;; single numeric value is an open bound.
844 ;;; The "more or less" bit is that the no-bound-at-all case is
845 ;;; represented by NIL (not by * as in ANSI type specifiers); and in
846 ;;; this case we return NIL.
847 (defun type-bound-number (x)
849 (destructuring-bind (result) x result)
852 ;;; some commonly-occuring CONSTANTLY forms
853 (macrolet ((def-constantly-fun (name constant-expr)
854 `(setf (symbol-function ',name)
855 (constantly ,constant-expr))))
856 (def-constantly-fun constantly-t t)
857 (def-constantly-fun constantly-nil nil)
858 (def-constantly-fun constantly-0 0))
860 ;;; If X is an atom, see whether it is present in *FEATURES*. Also
861 ;;; handle arbitrary combinations of atoms using NOT, AND, OR.
867 (error "too many subexpressions in feature expression: ~S" x)
868 (not (featurep (cadr x)))))
869 ((:and and) (every #'featurep (cdr x)))
870 ((:or or) (some #'featurep (cdr x)))
872 (error "unknown operator in feature expression: ~S." x)))
873 (not (null (memq x *features*)))))
875 ;;; Given a list of keyword substitutions `(,OLD ,NEW), and a
876 ;;; &KEY-argument-list-style list of alternating keywords and
877 ;;; arbitrary values, return a new &KEY-argument-list-style list with
878 ;;; all substitutions applied to it.
880 ;;; Note: If efficiency mattered, we could do less consing. (But if
881 ;;; efficiency mattered, why would we be using &KEY arguments at
882 ;;; all, much less renaming &KEY arguments?)
884 ;;; KLUDGE: It would probably be good to get rid of this. -- WHN 19991201
885 (defun rename-key-args (rename-list key-args)
886 (declare (type list rename-list key-args))
887 ;; Walk through RENAME-LIST modifying RESULT as per each element in
889 (do ((result (copy-list key-args))) ; may be modified below
890 ((null rename-list) result)
891 (destructuring-bind (old new) (pop rename-list)
892 ;; ANSI says &KEY arg names aren't necessarily KEYWORDs.
893 (declare (type symbol old new))
894 ;; Walk through RESULT renaming any OLD key argument to NEW.
895 (do ((in-result result (cddr in-result)))
897 (declare (type list in-result))
898 (when (eq (car in-result) old)
899 (setf (car in-result) new))))))
901 ;;; ANSI Common Lisp's READ-SEQUENCE function, unlike most of the
902 ;;; other ANSI input functions, is defined to communicate end of file
903 ;;; status with its return value, not by signalling. That is not the
904 ;;; behavior that we usually want. This function is a wrapper which
905 ;;; restores the behavior that we usually want, causing READ-SEQUENCE
906 ;;; to communicate end-of-file status by signalling.
907 (defun read-sequence-or-die (sequence stream &key start end)
908 ;; implementation using READ-SEQUENCE
909 #-no-ansi-read-sequence
910 (let ((read-end (read-sequence sequence
914 (unless (= read-end end)
915 (error 'end-of-file :stream stream))
917 ;; workaround for broken READ-SEQUENCE
918 #+no-ansi-read-sequence
920 (aver (<= start end))
921 (let ((etype (stream-element-type stream)))
922 (cond ((equal etype '(unsigned-byte 8))
923 (do ((i start (1+ i)))
926 (setf (aref sequence i)
927 (read-byte stream))))
928 (t (error "unsupported element type ~S" etype))))))
930 ;;;; utilities for two-VALUES predicates
932 (defmacro not/type (x)
933 (let ((val (gensym "VAL"))
934 (win (gensym "WIN")))
935 `(multiple-value-bind (,val ,win)
938 (values (not ,val) t)
941 (defmacro and/type (x y)
942 `(multiple-value-bind (val1 win1) ,x
943 (if (and (not val1) win1)
945 (multiple-value-bind (val2 win2) ,y
948 (values nil (and win2 (not val2))))))))
950 ;;; sort of like ANY and EVERY, except:
951 ;;; * We handle two-VALUES predicate functions, as SUBTYPEP does.
952 ;;; (And if the result is uncertain, then we return (VALUES NIL NIL),
953 ;;; as SUBTYPEP does.)
954 ;;; * THING is just an atom, and we apply OP (an arity-2 function)
955 ;;; successively to THING and each element of LIST.
956 (defun any/type (op thing list)
957 (declare (type function op))
959 (dolist (i list (values nil certain?))
960 (multiple-value-bind (sub-value sub-certain?) (funcall op thing i)
962 (when sub-value (return (values t t)))
963 (setf certain? nil))))))
964 (defun every/type (op thing list)
965 (declare (type function op))
967 (dolist (i list (if certain? (values t t) (values nil nil)))
968 (multiple-value-bind (sub-value sub-certain?) (funcall op thing i)
970 (unless sub-value (return (values nil t)))
971 (setf certain? nil))))))
975 ;;; These functions are called by the expansion of the DEFPRINTER
976 ;;; macro to do the actual printing.
977 (declaim (ftype (function (symbol t stream) (values))
978 defprinter-prin1 defprinter-princ))
979 (defun defprinter-prin1 (name value stream)
980 (defprinter-prinx #'prin1 name value stream))
981 (defun defprinter-princ (name value stream)
982 (defprinter-prinx #'princ name value stream))
983 (defun defprinter-prinx (prinx name value stream)
984 (declare (type function prinx))
986 (pprint-newline :linear stream))
987 (format stream ":~A " name)
988 (funcall prinx value stream)
990 (defun defprinter-print-space (stream)
991 (write-char #\space stream))
993 ;;; Define some kind of reasonable PRINT-OBJECT method for a
994 ;;; STRUCTURE-OBJECT class.
996 ;;; NAME is the name of the structure class, and CONC-NAME is the same
999 ;;; The SLOT-DESCS describe how each slot should be printed. Each
1000 ;;; SLOT-DESC can be a slot name, indicating that the slot should
1001 ;;; simply be printed. A SLOT-DESC may also be a list of a slot name
1002 ;;; and other stuff. The other stuff is composed of keywords followed
1003 ;;; by expressions. The expressions are evaluated with the variable
1004 ;;; which is the slot name bound to the value of the slot. These
1005 ;;; keywords are defined:
1007 ;;; :PRIN1 Print the value of the expression instead of the slot value.
1008 ;;; :PRINC Like :PRIN1, only PRINC the value
1009 ;;; :TEST Only print something if the test is true.
1011 ;;; If no printing thing is specified then the slot value is printed
1014 ;;; The structure being printed is bound to STRUCTURE and the stream
1015 ;;; is bound to STREAM.
1016 (defmacro defprinter ((name
1018 (conc-name (concatenate 'simple-string
1025 (reversed-prints nil)
1026 (stream (gensym "STREAM")))
1027 (flet ((sref (slot-name)
1028 `(,(symbolicate conc-name slot-name) structure)))
1029 (dolist (slot-desc slot-descs)
1031 (setf maybe-print-space nil
1033 (setf maybe-print-space `(defprinter-print-space ,stream)))
1034 (cond ((atom slot-desc)
1035 (push maybe-print-space reversed-prints)
1036 (push `(defprinter-prin1 ',slot-desc ,(sref slot-desc) ,stream)
1039 (let ((sname (first slot-desc))
1042 (do ((option (rest slot-desc) (cddr option)))
1044 (push `(let ((,sname ,(sref sname)))
1049 ',sname ,sname ,stream)))))
1051 (case (first option)
1053 (stuff `(defprinter-prin1
1054 ',sname ,(second option) ,stream)))
1056 (stuff `(defprinter-princ
1057 ',sname ,(second option) ,stream)))
1058 (:test (setq test (second option)))
1060 (error "bad option: ~S" (first option)))))))))))
1061 `(def!method print-object ((structure ,name) ,stream)
1062 (pprint-logical-block (,stream nil)
1063 (print-unreadable-object (structure
1066 :identity ,identity)
1067 ,@(nreverse reversed-prints))))))
1071 ;;; Given a pathname, return a corresponding physical pathname.
1072 (defun physicalize-pathname (possibly-logical-pathname)
1073 (if (typep possibly-logical-pathname 'logical-pathname)
1074 (translate-logical-pathname possibly-logical-pathname)
1075 possibly-logical-pathname))
1077 (defun deprecation-warning (bad-name &optional good-name)
1078 (warn "using deprecated ~S~@[, should use ~S instead~]"
1082 ;;; Anaphoric macros
1083 (defmacro awhen (test &body body)
1087 (defmacro acond (&rest clauses)
1090 (destructuring-bind ((test &body body) &rest rest) clauses
1091 (once-only ((test test))
1093 (let ((it ,test)) (declare (ignorable it)),@body)
1096 ;;; (binding* ({(names initial-value [flag])}*) body)
1097 ;;; FLAG may be NIL or :EXIT-IF-NULL
1099 ;;; This form unites LET*, MULTIPLE-VALUE-BIND and AWHEN.
1100 (defmacro binding* ((&rest bindings) &body body)
1101 (let ((bindings (reverse bindings)))
1102 (loop with form = `(progn ,@body)
1103 for binding in bindings
1104 do (destructuring-bind (names initial-value &optional flag)
1106 (multiple-value-bind (names declarations)
1109 (let ((name (gensym)))
1110 (values (list name) `((declare (ignorable ,name))))))
1112 (values (list names) nil))
1114 (collect ((new-names) (ignorable))
1115 (dolist (name names)
1117 (setq name (gensym))
1122 `((declare (ignorable ,@(ignorable)))))))))
1123 (setq form `(multiple-value-bind ,names
1129 `(when ,(first names) ,form)))))))
1130 finally (return form))))
1132 ;;; Delayed evaluation
1133 (defmacro delay (form)
1134 `(cons nil (lambda () ,form)))
1136 (defun force (promise)
1137 (cond ((not (consp promise)) promise)
1138 ((car promise) (cdr promise))
1139 (t (setf (car promise) t
1140 (cdr promise) (funcall (cdr promise))))))
1142 (defun promise-ready-p (promise)
1143 (or (not (consp promise))
1147 (defmacro with-rebound-io-syntax (&body body)
1148 `(%with-rebound-io-syntax (lambda () ,@body)))
1150 (defun %with-rebound-io-syntax (function)
1151 (declare (type function function))
1152 (let ((*package* *package*)
1153 (*print-array* *print-array*)
1154 (*print-base* *print-base*)
1155 (*print-case* *print-case*)
1156 (*print-circle* *print-circle*)
1157 (*print-escape* *print-escape*)
1158 (*print-gensym* *print-gensym*)
1159 (*print-length* *print-length*)
1160 (*print-level* *print-level*)
1161 (*print-lines* *print-lines*)
1162 (*print-miser-width* *print-miser-width*)
1163 (*print-pretty* *print-pretty*)
1164 (*print-radix* *print-radix*)
1165 (*print-readably* *print-readably*)
1166 (*print-right-margin* *print-right-margin*)
1167 (*read-base* *read-base*)
1168 (*read-default-float-format* *read-default-float-format*)
1169 (*read-eval* *read-eval*)
1170 (*read-suppress* *read-suppress*)
1171 (*readtable* *readtable*))
1172 (funcall function)))
1174 ;;; Bind a few "potentially dangerous" printer control variables to
1175 ;;; safe values, respecting current values if possible.
1176 (defmacro with-sane-io-syntax (&body forms)
1177 `(call-with-sane-io-syntax (lambda () ,@forms)))
1179 (defun call-with-sane-io-syntax (function)
1180 (declare (type function function))
1181 (macrolet ((true (sym)
1182 `(and (boundp ',sym) ,sym)))
1183 (let ((*print-readably* nil)
1184 (*print-level* (or (true *print-level*) 6))
1185 (*print-length* (or (true *print-length*) 12)))
1186 (funcall function))))