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 ;;; X may contain cycles -- a conservative approximation. This
131 ;;; occupies a somewhat uncomfortable niche between being fast for
132 ;;; common cases (we don't want to allocate a hash-table), and not
133 ;;; falling down to exponential behaviour for large trees (so we set
134 ;;; an arbitrady depth limit beyond which we punt).
135 (defun maybe-cyclic-p (x &optional (depth-limit 12))
137 (labels ((safe-cddr (cons)
138 (let ((cdr (cdr cons)))
141 (check-cycle (object seen depth)
142 (when (and (consp object)
143 (or (> depth depth-limit)
145 (circularp object seen depth)))
146 (return-from maybe-cyclic-p t)))
147 (circularp (list seen depth)
148 ;; Almost regular circular list detection, with a twist:
149 ;; we also check each element of the list for upward
150 ;; references using CHECK-CYCLE.
151 (do ((fast (cons (car list) (cdr list)) (safe-cddr fast))
152 (slow list (cdr slow)))
154 ;; Not CDR-circular, need to check remaining CARs yet
155 (do ((tail slow (and (cdr tail))))
158 (check-cycle (car tail) (cons tail seen) (1+ depth))))
159 (check-cycle (car slow) (cons slow seen) (1+ depth))
162 (circularp x (list x) 0))))
164 ;;; Is X a (possibly-improper) list of at least N elements?
165 (declaim (ftype (function (t index)) list-of-length-at-least-p))
166 (defun list-of-length-at-least-p (x n)
167 (or (zerop n) ; since anything can be considered an improper list of length 0
169 (list-of-length-at-least-p (cdr x) (1- n)))))
171 (declaim (inline singleton-p))
172 (defun singleton-p (list)
176 ;;; Is X is a positive prime integer?
177 (defun positive-primep (x)
178 ;; This happens to be called only from one place in sbcl-0.7.0, and
179 ;; only for fixnums, we can limit it to fixnums for efficiency. (And
180 ;; if we didn't limit it to fixnums, we should use a cleverer
181 ;; algorithm, since this one scales pretty badly for huge X.)
184 (and (>= x 2) (/= x 4))
186 (not (zerop (rem x 3)))
189 (inc 2 (logxor inc 6)) ;; 2,4,2,4...
191 ((or (= r 0) (> d q)) (/= r 0))
192 (declare (fixnum inc))
193 (multiple-value-setq (q r) (truncate x d))))))
195 ;;; Could this object contain other objects? (This is important to
196 ;;; the implementation of things like *PRINT-CIRCLE* and the dumper.)
197 (defun compound-object-p (x)
200 (typep x '(array t *))))
202 ;;;; the COLLECT macro
204 ;;;; comment from CMU CL: "the ultimate collection macro..."
206 ;;; helper functions for COLLECT, which become the expanders of the
207 ;;; MACROLET definitions created by COLLECT
209 ;;; COLLECT-NORMAL-EXPANDER handles normal collection macros.
211 ;;; COLLECT-LIST-EXPANDER handles the list collection case. N-TAIL
212 ;;; is the pointer to the current tail of the list, or NIL if the list
214 (eval-when (#-sb-xc :compile-toplevel :load-toplevel :execute)
215 (defun collect-normal-expander (n-value fun forms)
217 ,@(mapcar (lambda (form) `(setq ,n-value (,fun ,form ,n-value))) forms)
219 (defun collect-list-expander (n-value n-tail forms)
220 (let ((n-res (gensym)))
222 ,@(mapcar (lambda (form)
223 `(let ((,n-res (cons ,form nil)))
225 (setf (cdr ,n-tail) ,n-res)
226 (setq ,n-tail ,n-res))
228 (setq ,n-tail ,n-res ,n-value ,n-res)))))
232 ;;; Collect some values somehow. Each of the collections specifies a
233 ;;; bunch of things which collected during the evaluation of the body
234 ;;; of the form. The name of the collection is used to define a local
235 ;;; macro, a la MACROLET. Within the body, this macro will evaluate
236 ;;; each of its arguments and collect the result, returning the
237 ;;; current value after the collection is done. The body is evaluated
238 ;;; as a PROGN; to get the final values when you are done, just call
239 ;;; the collection macro with no arguments.
241 ;;; INITIAL-VALUE is the value that the collection starts out with,
242 ;;; which defaults to NIL. FUNCTION is the function which does the
243 ;;; collection. It is a function which will accept two arguments: the
244 ;;; value to be collected and the current collection. The result of
245 ;;; the function is made the new value for the collection. As a
246 ;;; totally magical special-case, FUNCTION may be COLLECT, which tells
247 ;;; us to build a list in forward order; this is the default. If an
248 ;;; INITIAL-VALUE is supplied for COLLECT, the stuff will be RPLACD'd
249 ;;; onto the end. Note that FUNCTION may be anything that can appear
250 ;;; in the functional position, including macros and lambdas.
251 (defmacro collect (collections &body body)
254 (dolist (spec collections)
255 (unless (proper-list-of-length-p spec 1 3)
256 (error "malformed collection specifier: ~S" spec))
257 (let* ((name (first spec))
258 (default (second spec))
259 (kind (or (third spec) 'collect))
260 (n-value (gensym (concatenate 'string
263 (push `(,n-value ,default) binds)
264 (if (eq kind 'collect)
265 (let ((n-tail (gensym (concatenate 'string
269 (push `(,n-tail (last ,n-value)) binds)
271 (push `(,name (&rest args)
272 (collect-list-expander ',n-value ',n-tail args))
274 (push `(,name (&rest args)
275 (collect-normal-expander ',n-value ',kind args))
277 `(macrolet ,macros (let* ,(nreverse binds) ,@body))))
279 ;;;; some old-fashioned functions. (They're not just for old-fashioned
280 ;;;; code, they're also used as optimized forms of the corresponding
281 ;;;; general functions when the compiler can prove that they're
284 ;;; like (MEMBER ITEM LIST :TEST #'EQ)
285 (defun memq (item list)
287 "Return tail of LIST beginning with first element EQ to ITEM."
288 ;; KLUDGE: These could be and probably should be defined as
289 ;; (MEMBER ITEM LIST :TEST #'EQ)),
290 ;; but when I try to cross-compile that, I get an error from
291 ;; LTN-ANALYZE-KNOWN-CALL, "Recursive known function definition". The
292 ;; comments for that error say it "is probably a botched interpreter stub".
293 ;; Rather than try to figure that out, I just rewrote this function from
294 ;; scratch. -- WHN 19990512
295 (do ((i list (cdr i)))
297 (when (eq (car i) item)
300 ;;; like (ASSOC ITEM ALIST :TEST #'EQ):
301 ;;; Return the first pair of ALIST where ITEM is EQ to the key of
303 (defun assq (item alist)
304 ;; KLUDGE: CMU CL defined this with
305 ;; (DECLARE (INLINE ASSOC))
306 ;; (ASSOC ITEM ALIST :TEST #'EQ))
307 ;; which is pretty, but which would have required adding awkward
308 ;; build order constraints on SBCL (or figuring out some way to make
309 ;; inline definitions installable at build-the-cross-compiler time,
310 ;; which was too ambitious for now). Rather than mess with that, we
311 ;; just define ASSQ explicitly in terms of more primitive
314 ;; though it may look more natural to write this as
315 ;; (AND PAIR (EQ (CAR PAIR) ITEM))
316 ;; the temptation to do so should be resisted, as pointed out by PFD
317 ;; sbcl-devel 2003-08-16, as NIL elements are rare in association
318 ;; lists. -- CSR, 2003-08-16
319 (when (and (eq (car pair) item) (not (null pair)))
322 ;;; like (DELETE .. :TEST #'EQ):
323 ;;; Delete all LIST entries EQ to ITEM (destructively modifying
324 ;;; LIST), and return the modified LIST.
325 (defun delq (item list)
327 (do ((x list (cdr x))
330 (cond ((eq item (car x))
333 (rplacd splice (cdr x))))
334 (t (setq splice x)))))) ; Move splice along to include element.
337 ;;; like (POSITION .. :TEST #'EQ):
338 ;;; Return the position of the first element EQ to ITEM.
339 (defun posq (item list)
340 (do ((i list (cdr i))
343 (when (eq (car i) item)
346 (declaim (inline neq))
350 ;;; not really an old-fashioned function, but what the calling
351 ;;; convention should've been: like NTH, but with the same argument
352 ;;; order as in all the other dereferencing functions, with the
353 ;;; collection first and the index second
354 (declaim (inline nth-but-with-sane-arg-order))
355 (declaim (ftype (function (list index) t) nth-but-with-sane-arg-order))
356 (defun nth-but-with-sane-arg-order (list index)
359 (defun adjust-list (list length initial-element)
360 (let ((old-length (length list)))
361 (cond ((< old-length length)
362 (append list (make-list (- length old-length)
363 :initial-element initial-element)))
364 ((> old-length length)
365 (subseq list 0 length))
368 ;;;; miscellaneous iteration extensions
370 ;;; "the ultimate iteration macro"
372 ;;; note for Schemers: This seems to be identical to Scheme's "named LET".
373 (defmacro named-let (name binds &body body)
376 (unless (proper-list-of-length-p x 2)
377 (error "malformed NAMED-LET variable spec: ~S" x)))
378 `(labels ((,name ,(mapcar #'first binds) ,@body))
379 (,name ,@(mapcar #'second binds))))
381 ;;; just like DOLIST, but with one-dimensional arrays
382 (defmacro dovector ((elt vector &optional result) &rest forms)
383 (let ((index (gensym))
386 `(let ((,vec ,vector))
387 (declare (type vector ,vec))
388 (do ((,index 0 (1+ ,index))
389 (,length (length ,vec)))
390 ((>= ,index ,length) ,result)
391 (let ((,elt (aref ,vec ,index)))
394 ;;; Iterate over the entries in a HASH-TABLE.
395 (defmacro dohash ((key-var value-var table &optional result) &body body)
396 (multiple-value-bind (forms decls) (parse-body body :doc-string-allowed nil)
399 `(with-hash-table-iterator (,gen ,table)
401 (multiple-value-bind (,n-more ,key-var ,value-var) (,gen)
403 (unless ,n-more (return ,result))
406 ;;;; hash cache utility
408 (eval-when (:compile-toplevel :load-toplevel :execute)
409 (defvar *profile-hash-cache* nil))
411 ;;; a flag for whether it's too early in cold init to use caches so
412 ;;; that we have a better chance of recovering so that we have a
413 ;;; better chance of getting the system running so that we have a
414 ;;; better chance of diagnosing the problem which caused us to use the
417 (defvar *hash-caches-initialized-p*)
419 ;;; Define a hash cache that associates some number of argument values
420 ;;; with a result value. The TEST-FUNCTION paired with each ARG-NAME
421 ;;; is used to compare the value for that arg in a cache entry with a
422 ;;; supplied arg. The TEST-FUNCTION must not error when passed NIL as
423 ;;; its first arg, but need not return any particular value.
424 ;;; TEST-FUNCTION may be any thing that can be placed in CAR position.
426 ;;; This code used to store all the arguments / return values directly
427 ;;; in the cache vector. This was both interrupt- and thread-unsafe, since
428 ;;; it was possible that *-CACHE-ENTER would scribble over a region of the
429 ;;; cache vector which *-CACHE-LOOKUP had only partially processed. Instead
430 ;;; we now store the contents of each cache bucket as a separate array, which
431 ;;; is stored in the appropriate cell in the cache vector. A new bucket array
432 ;;; is created every time *-CACHE-ENTER is called, and the old ones are never
433 ;;; modified. This means that *-CACHE-LOOKUP will always work with a set
434 ;;; of consistent data. The overhead caused by consing new buckets seems to
435 ;;; be insignificant on the grand scale of things. -- JES, 2006-11-02
437 ;;; NAME is used to define these functions:
438 ;;; <name>-CACHE-LOOKUP Arg*
439 ;;; See whether there is an entry for the specified ARGs in the
440 ;;; cache. If not present, the :DEFAULT keyword (default NIL)
441 ;;; determines the result(s).
442 ;;; <name>-CACHE-ENTER Arg* Value*
443 ;;; Encache the association of the specified args with VALUE.
444 ;;; <name>-CACHE-CLEAR
445 ;;; Reinitialize the cache, invalidating all entries and allowing
446 ;;; the arguments and result values to be GC'd.
448 ;;; These other keywords are defined:
450 ;;; The size of the cache as a power of 2.
451 ;;; :HASH-FUNCTION function
452 ;;; Some thing that can be placed in CAR position which will compute
453 ;;; a value between 0 and (1- (expt 2 <hash-bits>)).
455 ;;; the number of return values cached for each function call
456 ;;; :INIT-WRAPPER <name>
457 ;;; The code for initializing the cache is wrapped in a form with
458 ;;; the specified name. (:INIT-WRAPPER is set to COLD-INIT-FORMS
459 ;;; in type system definitions so that caches will be created
460 ;;; before top level forms run.)
461 (defmacro define-hash-cache (name args &key hash-function hash-bits default
462 (init-wrapper 'progn)
464 (let* ((var-name (symbolicate "*" name "-CACHE-VECTOR*"))
465 (nargs (length args))
466 (size (ash 1 hash-bits))
467 (default-values (if (and (consp default) (eq (car default) 'values))
470 (args-and-values (gensym))
471 (args-and-values-size (+ nargs values))
475 (unless (= (length default-values) values)
476 (error "The number of default values ~S differs from :VALUES ~W."
488 (let ((name (gensym)))
490 (values-refs `(svref ,args-and-values (+ ,nargs ,i)))
491 (sets `(setf (svref ,args-and-values (+ ,nargs ,i)) ,name))))
494 (unless (= (length arg) 2)
495 (error "bad argument spec: ~S" arg))
496 (let ((arg-name (first arg))
499 (tests `(,test (svref ,args-and-values ,n) ,arg-name))
500 (sets `(setf (svref ,args-and-values ,n) ,arg-name)))
503 (when *profile-hash-cache*
504 (let ((n-probe (symbolicate "*" name "-CACHE-PROBES*"))
505 (n-miss (symbolicate "*" name "-CACHE-MISSES*")))
506 (inits `(setq ,n-probe 0))
507 (inits `(setq ,n-miss 0))
508 (forms `(defvar ,n-probe))
509 (forms `(defvar ,n-miss))
510 (forms `(declaim (fixnum ,n-miss ,n-probe)))))
512 (let ((fun-name (symbolicate name "-CACHE-LOOKUP")))
515 `(defun ,fun-name ,(arg-vars)
516 ,@(when *profile-hash-cache*
517 `((incf ,(symbolicate "*" name "-CACHE-PROBES*"))))
518 (let* ((,n-index (,hash-function ,@(arg-vars)))
520 (,args-and-values (svref ,n-cache ,n-index)))
521 (cond ((and ,args-and-values
523 (values ,@(values-refs)))
525 ,@(when *profile-hash-cache*
526 `((incf ,(symbolicate "*" name "-CACHE-MISSES*"))))
529 (let ((fun-name (symbolicate name "-CACHE-ENTER")))
532 `(defun ,fun-name (,@(arg-vars) ,@(values-names))
533 (let ((,n-index (,hash-function ,@(arg-vars)))
535 (,args-and-values (make-array ,args-and-values-size)))
537 (setf (svref ,n-cache ,n-index) ,args-and-values))
540 (let ((fun-name (symbolicate name "-CACHE-CLEAR")))
543 (fill ,var-name nil)))
544 (forms `(,fun-name)))
546 (inits `(unless (boundp ',var-name)
547 (setq ,var-name (make-array ,size :initial-element nil))))
548 #!+sb-show (inits `(setq *hash-caches-initialized-p* t))
552 (declaim (type (simple-vector ,size) ,var-name))
553 #!-sb-fluid (declaim (inline ,@(inlines)))
554 (,init-wrapper ,@(inits))
558 ;;; some syntactic sugar for defining a function whose values are
559 ;;; cached by DEFINE-HASH-CACHE
560 (defmacro defun-cached ((name &rest options &key (values 1) default
562 args &body body-decls-doc)
563 (let ((default-values (if (and (consp default) (eq (car default) 'values))
566 (arg-names (mapcar #'car args)))
567 (collect ((values-names))
569 (values-names (gensym)))
570 (multiple-value-bind (body decls doc) (parse-body body-decls-doc)
572 (define-hash-cache ,name ,args ,@options)
573 (defun ,name ,arg-names
577 ((not (boundp '*hash-caches-initialized-p*))
578 ;; This shouldn't happen, but it did happen to me
579 ;; when revising the type system, and it's a lot
580 ;; easier to figure out what what's going on with
581 ;; that kind of problem if the system can be kept
582 ;; alive until cold boot is complete. The recovery
583 ;; mechanism should definitely be conditional on
584 ;; some debugging feature (e.g. SB-SHOW) because
585 ;; it's big, duplicating all the BODY code. -- WHN
586 (/show0 ,name " too early in cold init, uncached")
587 (/show0 ,(first arg-names) "=..")
588 (/hexstr ,(first arg-names))
591 (multiple-value-bind ,(values-names)
592 (,(symbolicate name "-CACHE-LOOKUP") ,@arg-names)
593 (if (and ,@(mapcar (lambda (val def)
595 (values-names) default-values))
596 (multiple-value-bind ,(values-names)
598 (,(symbolicate name "-CACHE-ENTER") ,@arg-names
600 (values ,@(values-names)))
601 (values ,@(values-names))))))))))))
603 (defmacro define-cached-synonym
604 (name &optional (original (symbolicate "%" name)))
605 (let ((cached-name (symbolicate "%%" name "-CACHED")))
607 (defun-cached (,cached-name :hash-bits 8
608 :hash-function (lambda (x)
609 (logand (sxhash x) #xff)))
611 (apply #',original args))
612 (defun ,name (&rest args)
613 (,cached-name args)))))
615 ;;; FIXME: maybe not the best place
617 ;;; FIXME: think of a better name -- not only does this not have the
618 ;;; CAR recursion of EQUAL, it also doesn't have the special treatment
619 ;;; of pathnames, bit-vectors and strings.
621 ;;; KLUDGE: This means that we will no longer cache specifiers of the
622 ;;; form '(INTEGER (0) 4). This is probably not a disaster.
624 ;;; A helper function for the type system, which is the main user of
625 ;;; these caches: we must be more conservative than EQUAL for some of
626 ;;; our equality tests, because MEMBER and friends refer to EQLity.
628 (defun equal-but-no-car-recursion (x y)
633 (eql (car x) (car y))
634 (equal-but-no-car-recursion (cdr x) (cdr y))))
639 ;;; Note: Almost always you want to use FIND-UNDELETED-PACKAGE-OR-LOSE
640 ;;; instead of this function. (The distinction only actually matters when
641 ;;; PACKAGE-DESIGNATOR is actually a deleted package, and in that case
642 ;;; you generally do want to signal an error instead of proceeding.)
643 (defun %find-package-or-lose (package-designator)
644 (or (find-package package-designator)
645 (error 'sb!kernel:simple-package-error
646 :package package-designator
647 :format-control "The name ~S does not designate any package."
648 :format-arguments (list package-designator))))
650 ;;; ANSI specifies (in the section for FIND-PACKAGE) that the
651 ;;; consequences of most operations on deleted packages are
652 ;;; unspecified. We try to signal errors in such cases.
653 (defun find-undeleted-package-or-lose (package-designator)
654 (let ((maybe-result (%find-package-or-lose package-designator)))
655 (if (package-name maybe-result) ; if not deleted
657 (error 'sb!kernel:simple-package-error
658 :package maybe-result
659 :format-control "The package ~S has been deleted."
660 :format-arguments (list maybe-result)))))
662 ;;;; various operations on names
664 ;;; Is NAME a legal function name?
665 (declaim (inline legal-fun-name-p))
666 (defun legal-fun-name-p (name)
667 (values (valid-function-name-p name)))
669 (deftype function-name () '(satisfies legal-fun-name-p))
671 ;;; Signal an error unless NAME is a legal function name.
672 (defun legal-fun-name-or-type-error (name)
673 (unless (legal-fun-name-p name)
674 (error 'simple-type-error
676 :expected-type 'function-name
677 :format-control "invalid function name: ~S"
678 :format-arguments (list name))))
680 ;;; Given a function name, return the symbol embedded in it.
682 ;;; The ordinary use for this operator (and the motivation for the
683 ;;; name of this operator) is to convert from a function name to the
684 ;;; name of the BLOCK which encloses its body.
686 ;;; Occasionally the operator is useful elsewhere, where the operator
687 ;;; name is less mnemonic. (Maybe it should be changed?)
688 (declaim (ftype (function ((or symbol cons)) symbol) fun-name-block-name))
689 (defun fun-name-block-name (fun-name)
690 (cond ((symbolp fun-name)
693 (multiple-value-bind (legalp block-name)
694 (valid-function-name-p fun-name)
697 (error "not legal as a function name: ~S" fun-name))))
699 (error "not legal as a function name: ~S" fun-name))))
701 (defun looks-like-name-of-special-var-p (x)
703 (let ((name (symbol-name x)))
704 (and (> (length name) 2) ; to exclude '* and '**
705 (char= #\* (aref name 0))
706 (char= #\* (aref name (1- (length name))))))))
708 ;;; Some symbols are defined by ANSI to be self-evaluating. Return
709 ;;; non-NIL for such symbols (and make the non-NIL value a traditional
710 ;;; message, for use in contexts where the user asks us to change such
712 (defun symbol-self-evaluating-p (symbol)
713 (declare (type symbol symbol))
715 "Veritas aeterna. (can't change T)")
717 "Nihil ex nihil. (can't change NIL)")
719 "Keyword values can't be changed.")
723 ;;; This function is to be called just before a change which would
724 ;;; affect the symbol value. (We don't absolutely have to call this
725 ;;; function before such changes, since such changes are given as
726 ;;; undefined behavior. In particular, we don't if the runtime cost
727 ;;; would be annoying. But otherwise it's nice to do so.)
728 (defun about-to-modify-symbol-value (symbol)
729 (declare (type symbol symbol))
730 (let ((reason (symbol-self-evaluating-p symbol)))
733 ;; (Note: Just because a value is CONSTANTP is not a good enough
734 ;; reason to complain here, because we want DEFCONSTANT to be able
735 ;; to use this function, and it's legal to DEFCONSTANT a constant as
736 ;; long as the new value is EQL to the old value.)
740 ;;; If COLD-FSET occurs not at top level, just treat it as an ordinary
741 ;;; assignment instead of doing cold static linking. That way things like
742 ;;; (FLET ((FROB (X) ..))
743 ;;; (DEFUN FOO (X Y) (FROB X) ..)
744 ;;; (DEFUN BAR (Z) (AND (FROB X) ..)))
745 ;;; can still "work" for cold init: they don't do magical static
746 ;;; linking the way that true toplevel DEFUNs do, but at least they do
747 ;;; the linking eventually, so as long as #'FOO and #'BAR aren't
748 ;;; needed until "cold toplevel forms" have executed, it's OK.
749 (defmacro cold-fset (name lambda)
751 "~@<COLD-FSET ~S not cross-compiled at top level: demoting to ~
752 (SETF FDEFINITION)~:@>"
754 ;; We convert the LAMBDA expression to the corresponding NAMED-LAMBDA
755 ;; expression so that the compiler can use NAME in debug names etc.
756 (destructuring-bind (lambda-symbol &rest lambda-rest) lambda
757 (assert (eql lambda-symbol 'lambda)) ; else dunno how to do conversion
758 `(setf (fdefinition ',name)
759 (named-lambda ,name ,@lambda-rest))))
763 ;;;; "The macro ONCE-ONLY has been around for a long time on various
764 ;;;; systems [..] if you can understand how to write and when to use
765 ;;;; ONCE-ONLY, then you truly understand macro." -- Peter Norvig,
766 ;;;; _Paradigms of Artificial Intelligence Programming: Case Studies
767 ;;;; in Common Lisp_, p. 853
769 ;;; ONCE-ONLY is a utility useful in writing source transforms and
770 ;;; macros. It provides a concise way to wrap a LET around some code
771 ;;; to ensure that some forms are only evaluated once.
773 ;;; Create a LET* which evaluates each value expression, binding a
774 ;;; temporary variable to the result, and wrapping the LET* around the
775 ;;; result of the evaluation of BODY. Within the body, each VAR is
776 ;;; bound to the corresponding temporary variable.
777 (defmacro once-only (specs &body body)
778 (named-let frob ((specs specs)
782 (let ((spec (first specs)))
783 ;; FIXME: should just be DESTRUCTURING-BIND of SPEC
784 (unless (proper-list-of-length-p spec 2)
785 (error "malformed ONCE-ONLY binding spec: ~S" spec))
786 (let* ((name (first spec))
787 (exp-temp (gensym (symbol-name name))))
788 `(let ((,exp-temp ,(second spec))
789 (,name (gensym "ONCE-ONLY-")))
790 `(let ((,,name ,,exp-temp))
791 ,,(frob (rest specs) body))))))))
793 ;;;; various error-checking utilities
795 ;;; This function can be used as the default value for keyword
796 ;;; arguments that must be always be supplied. Since it is known by
797 ;;; the compiler to never return, it will avoid any compile-time type
798 ;;; warnings that would result from a default value inconsistent with
799 ;;; the declared type. When this function is called, it signals an
800 ;;; error indicating that a required &KEY argument was not supplied.
801 ;;; This function is also useful for DEFSTRUCT slot defaults
802 ;;; corresponding to required arguments.
803 (declaim (ftype (function () nil) missing-arg))
804 (defun missing-arg ()
806 (/show0 "entering MISSING-ARG")
807 (error "A required &KEY or &OPTIONAL argument was not supplied."))
809 ;;; like CL:ASSERT and CL:CHECK-TYPE, but lighter-weight
811 ;;; (As of sbcl-0.6.11.20, we were using some 400 calls to CL:ASSERT.
812 ;;; The CL:ASSERT restarts and whatnot expand into a significant
813 ;;; amount of code when you multiply them by 400, so replacing them
814 ;;; with this should reduce the size of the system by enough to be
815 ;;; worthwhile. ENFORCE-TYPE is much less common, but might still be
816 ;;; worthwhile, and since I don't really like CERROR stuff deep in the
817 ;;; guts of complex systems anyway, I replaced it too.)
818 (defmacro aver (expr)
820 (%failed-aver ,(format nil "~A" expr))))
822 (defun %failed-aver (expr-as-string)
823 ;; hackish way to tell we're in a cold sbcl and output the
824 ;; message before signallign error, as it may be this is too
825 ;; early in the cold init.
826 (when (find-package "SB!C")
828 (write-line "failed AVER:")
829 (write-line expr-as-string)
831 (bug "~@<failed AVER: ~2I~_~S~:>" expr-as-string))
833 (defun bug (format-control &rest format-arguments)
835 :format-control format-control
836 :format-arguments format-arguments))
838 (defmacro enforce-type (value type)
839 (once-only ((value value))
840 `(unless (typep ,value ',type)
841 (%failed-enforce-type ,value ',type))))
843 (defun %failed-enforce-type (value type)
844 ;; maybe should be TYPE-BUG, subclass of BUG? If it is changed,
845 ;; check uses of it in user-facing code (e.g. WARN)
846 (error 'simple-type-error
849 :format-control "~@<~S ~_is not a ~_~S~:>"
850 :format-arguments (list value type)))
852 ;;; Return a function like FUN, but expecting its (two) arguments in
853 ;;; the opposite order that FUN does.
854 (declaim (inline swapped-args-fun))
855 (defun swapped-args-fun (fun)
856 (declare (type function fun))
860 ;;; Return the numeric value of a type bound, i.e. an interval bound
861 ;;; more or less in the format of bounds in ANSI's type specifiers,
862 ;;; where a bare numeric value is a closed bound and a list of a
863 ;;; single numeric value is an open bound.
865 ;;; The "more or less" bit is that the no-bound-at-all case is
866 ;;; represented by NIL (not by * as in ANSI type specifiers); and in
867 ;;; this case we return NIL.
868 (defun type-bound-number (x)
870 (destructuring-bind (result) x result)
873 ;;; some commonly-occuring CONSTANTLY forms
874 (macrolet ((def-constantly-fun (name constant-expr)
875 `(setf (symbol-function ',name)
876 (constantly ,constant-expr))))
877 (def-constantly-fun constantly-t t)
878 (def-constantly-fun constantly-nil nil)
879 (def-constantly-fun constantly-0 0))
881 ;;; If X is an atom, see whether it is present in *FEATURES*. Also
882 ;;; handle arbitrary combinations of atoms using NOT, AND, OR.
888 (error "too many subexpressions in feature expression: ~S" x)
889 (not (featurep (cadr x)))))
890 ((:and and) (every #'featurep (cdr x)))
891 ((:or or) (some #'featurep (cdr x)))
893 (error "unknown operator in feature expression: ~S." x)))
894 (not (null (memq x *features*)))))
896 ;;; Given a list of keyword substitutions `(,OLD ,NEW), and a
897 ;;; &KEY-argument-list-style list of alternating keywords and
898 ;;; arbitrary values, return a new &KEY-argument-list-style list with
899 ;;; all substitutions applied to it.
901 ;;; Note: If efficiency mattered, we could do less consing. (But if
902 ;;; efficiency mattered, why would we be using &KEY arguments at
903 ;;; all, much less renaming &KEY arguments?)
905 ;;; KLUDGE: It would probably be good to get rid of this. -- WHN 19991201
906 (defun rename-key-args (rename-list key-args)
907 (declare (type list rename-list key-args))
908 ;; Walk through RENAME-LIST modifying RESULT as per each element in
910 (do ((result (copy-list key-args))) ; may be modified below
911 ((null rename-list) result)
912 (destructuring-bind (old new) (pop rename-list)
913 ;; ANSI says &KEY arg names aren't necessarily KEYWORDs.
914 (declare (type symbol old new))
915 ;; Walk through RESULT renaming any OLD key argument to NEW.
916 (do ((in-result result (cddr in-result)))
918 (declare (type list in-result))
919 (when (eq (car in-result) old)
920 (setf (car in-result) new))))))
922 ;;; ANSI Common Lisp's READ-SEQUENCE function, unlike most of the
923 ;;; other ANSI input functions, is defined to communicate end of file
924 ;;; status with its return value, not by signalling. That is not the
925 ;;; behavior that we usually want. This function is a wrapper which
926 ;;; restores the behavior that we usually want, causing READ-SEQUENCE
927 ;;; to communicate end-of-file status by signalling.
928 (defun read-sequence-or-die (sequence stream &key start end)
929 ;; implementation using READ-SEQUENCE
930 #-no-ansi-read-sequence
931 (let ((read-end (read-sequence sequence
935 (unless (= read-end end)
936 (error 'end-of-file :stream stream))
938 ;; workaround for broken READ-SEQUENCE
939 #+no-ansi-read-sequence
941 (aver (<= start end))
942 (let ((etype (stream-element-type stream)))
943 (cond ((equal etype '(unsigned-byte 8))
944 (do ((i start (1+ i)))
947 (setf (aref sequence i)
948 (read-byte stream))))
949 (t (error "unsupported element type ~S" etype))))))
951 ;;;; utilities for two-VALUES predicates
953 (defmacro not/type (x)
954 (let ((val (gensym "VAL"))
955 (win (gensym "WIN")))
956 `(multiple-value-bind (,val ,win)
959 (values (not ,val) t)
962 (defmacro and/type (x y)
963 `(multiple-value-bind (val1 win1) ,x
964 (if (and (not val1) win1)
966 (multiple-value-bind (val2 win2) ,y
969 (values nil (and win2 (not val2))))))))
971 ;;; sort of like ANY and EVERY, except:
972 ;;; * We handle two-VALUES predicate functions, as SUBTYPEP does.
973 ;;; (And if the result is uncertain, then we return (VALUES NIL NIL),
974 ;;; as SUBTYPEP does.)
975 ;;; * THING is just an atom, and we apply OP (an arity-2 function)
976 ;;; successively to THING and each element of LIST.
977 (defun any/type (op thing list)
978 (declare (type function op))
980 (dolist (i list (values nil certain?))
981 (multiple-value-bind (sub-value sub-certain?) (funcall op thing i)
983 (when sub-value (return (values t t)))
984 (setf certain? nil))))))
985 (defun every/type (op thing list)
986 (declare (type function op))
988 (dolist (i list (if certain? (values t t) (values nil nil)))
989 (multiple-value-bind (sub-value sub-certain?) (funcall op thing i)
991 (unless sub-value (return (values nil t)))
992 (setf certain? nil))))))
996 ;;; These functions are called by the expansion of the DEFPRINTER
997 ;;; macro to do the actual printing.
998 (declaim (ftype (function (symbol t stream) (values))
999 defprinter-prin1 defprinter-princ))
1000 (defun defprinter-prin1 (name value stream)
1001 (defprinter-prinx #'prin1 name value stream))
1002 (defun defprinter-princ (name value stream)
1003 (defprinter-prinx #'princ name value stream))
1004 (defun defprinter-prinx (prinx name value stream)
1005 (declare (type function prinx))
1006 (when *print-pretty*
1007 (pprint-newline :linear stream))
1008 (format stream ":~A " name)
1009 (funcall prinx value stream)
1011 (defun defprinter-print-space (stream)
1012 (write-char #\space stream))
1014 ;;; Define some kind of reasonable PRINT-OBJECT method for a
1015 ;;; STRUCTURE-OBJECT class.
1017 ;;; NAME is the name of the structure class, and CONC-NAME is the same
1018 ;;; as in DEFSTRUCT.
1020 ;;; The SLOT-DESCS describe how each slot should be printed. Each
1021 ;;; SLOT-DESC can be a slot name, indicating that the slot should
1022 ;;; simply be printed. A SLOT-DESC may also be a list of a slot name
1023 ;;; and other stuff. The other stuff is composed of keywords followed
1024 ;;; by expressions. The expressions are evaluated with the variable
1025 ;;; which is the slot name bound to the value of the slot. These
1026 ;;; keywords are defined:
1028 ;;; :PRIN1 Print the value of the expression instead of the slot value.
1029 ;;; :PRINC Like :PRIN1, only PRINC the value
1030 ;;; :TEST Only print something if the test is true.
1032 ;;; If no printing thing is specified then the slot value is printed
1035 ;;; The structure being printed is bound to STRUCTURE and the stream
1036 ;;; is bound to STREAM.
1037 (defmacro defprinter ((name
1039 (conc-name (concatenate 'simple-string
1046 (reversed-prints nil)
1047 (stream (gensym "STREAM")))
1048 (flet ((sref (slot-name)
1049 `(,(symbolicate conc-name slot-name) structure)))
1050 (dolist (slot-desc slot-descs)
1052 (setf maybe-print-space nil
1054 (setf maybe-print-space `(defprinter-print-space ,stream)))
1055 (cond ((atom slot-desc)
1056 (push maybe-print-space reversed-prints)
1057 (push `(defprinter-prin1 ',slot-desc ,(sref slot-desc) ,stream)
1060 (let ((sname (first slot-desc))
1063 (do ((option (rest slot-desc) (cddr option)))
1065 (push `(let ((,sname ,(sref sname)))
1070 ',sname ,sname ,stream)))))
1072 (case (first option)
1074 (stuff `(defprinter-prin1
1075 ',sname ,(second option) ,stream)))
1077 (stuff `(defprinter-princ
1078 ',sname ,(second option) ,stream)))
1079 (:test (setq test (second option)))
1081 (error "bad option: ~S" (first option)))))))))))
1082 `(def!method print-object ((structure ,name) ,stream)
1083 (pprint-logical-block (,stream nil)
1084 (print-unreadable-object (structure
1087 :identity ,identity)
1088 ,@(nreverse reversed-prints))))))
1092 ;;; Given a pathname, return a corresponding physical pathname.
1093 (defun physicalize-pathname (possibly-logical-pathname)
1094 (if (typep possibly-logical-pathname 'logical-pathname)
1095 (translate-logical-pathname possibly-logical-pathname)
1096 possibly-logical-pathname))
1098 (defun deprecation-warning (bad-name &optional good-name)
1099 (warn "using deprecated ~S~@[, should use ~S instead~]"
1103 ;;; Anaphoric macros
1104 (defmacro awhen (test &body body)
1108 (defmacro acond (&rest clauses)
1111 (destructuring-bind ((test &body body) &rest rest) clauses
1112 (once-only ((test test))
1114 (let ((it ,test)) (declare (ignorable it)),@body)
1117 ;;; (binding* ({(names initial-value [flag])}*) body)
1118 ;;; FLAG may be NIL or :EXIT-IF-NULL
1120 ;;; This form unites LET*, MULTIPLE-VALUE-BIND and AWHEN.
1121 (defmacro binding* ((&rest bindings) &body body)
1122 (let ((bindings (reverse bindings)))
1123 (loop with form = `(progn ,@body)
1124 for binding in bindings
1125 do (destructuring-bind (names initial-value &optional flag)
1127 (multiple-value-bind (names declarations)
1130 (let ((name (gensym)))
1131 (values (list name) `((declare (ignorable ,name))))))
1133 (values (list names) nil))
1135 (collect ((new-names) (ignorable))
1136 (dolist (name names)
1138 (setq name (gensym))
1143 `((declare (ignorable ,@(ignorable)))))))))
1144 (setq form `(multiple-value-bind ,names
1150 `(when ,(first names) ,form)))))))
1151 finally (return form))))
1153 ;;; Delayed evaluation
1154 (defmacro delay (form)
1155 `(cons nil (lambda () ,form)))
1157 (defun force (promise)
1158 (cond ((not (consp promise)) promise)
1159 ((car promise) (cdr promise))
1160 (t (setf (car promise) t
1161 (cdr promise) (funcall (cdr promise))))))
1163 (defun promise-ready-p (promise)
1164 (or (not (consp promise))
1168 (defmacro with-rebound-io-syntax (&body body)
1169 `(%with-rebound-io-syntax (lambda () ,@body)))
1171 (defun %with-rebound-io-syntax (function)
1172 (declare (type function function))
1173 (let ((*package* *package*)
1174 (*print-array* *print-array*)
1175 (*print-base* *print-base*)
1176 (*print-case* *print-case*)
1177 (*print-circle* *print-circle*)
1178 (*print-escape* *print-escape*)
1179 (*print-gensym* *print-gensym*)
1180 (*print-length* *print-length*)
1181 (*print-level* *print-level*)
1182 (*print-lines* *print-lines*)
1183 (*print-miser-width* *print-miser-width*)
1184 (*print-pretty* *print-pretty*)
1185 (*print-radix* *print-radix*)
1186 (*print-readably* *print-readably*)
1187 (*print-right-margin* *print-right-margin*)
1188 (*read-base* *read-base*)
1189 (*read-default-float-format* *read-default-float-format*)
1190 (*read-eval* *read-eval*)
1191 (*read-suppress* *read-suppress*)
1192 (*readtable* *readtable*))
1193 (funcall function)))
1195 ;;; Bind a few "potentially dangerous" printer control variables to
1196 ;;; safe values, respecting current values if possible.
1197 (defmacro with-sane-io-syntax (&body forms)
1198 `(call-with-sane-io-syntax (lambda () ,@forms)))
1200 (defun call-with-sane-io-syntax (function)
1201 (declare (type function function))
1202 (macrolet ((true (sym)
1203 `(and (boundp ',sym) ,sym)))
1204 (let ((*print-readably* nil)
1205 (*print-level* (or (true *print-level*) 6))
1206 (*print-length* (or (true *print-length*) 12)))
1207 (funcall function))))
1209 ;;; Default evaluator mode (interpeter / compiler)
1211 (declaim (type (member :compile #!+sb-eval :interpret) *evaluator-mode*))
1212 (defparameter *evaluator-mode* :compile
1214 "Toggle between different evaluator implementations. If set to :COMPILE,
1215 an implementation of EVAL that calls the compiler will be used. If set
1216 to :INTERPRET, an interpreter will be used.")