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 ;;; NAME is used to define these functions:
427 ;;; <name>-CACHE-LOOKUP Arg*
428 ;;; See whether there is an entry for the specified ARGs in the
429 ;;; cache. If not present, the :DEFAULT keyword (default NIL)
430 ;;; determines the result(s).
431 ;;; <name>-CACHE-ENTER Arg* Value*
432 ;;; Encache the association of the specified args with VALUE.
433 ;;; <name>-CACHE-CLEAR
434 ;;; Reinitialize the cache, invalidating all entries and allowing
435 ;;; the arguments and result values to be GC'd.
437 ;;; These other keywords are defined:
439 ;;; The size of the cache as a power of 2.
440 ;;; :HASH-FUNCTION function
441 ;;; Some thing that can be placed in CAR position which will compute
442 ;;; a value between 0 and (1- (expt 2 <hash-bits>)).
444 ;;; the number of return values cached for each function call
445 ;;; :INIT-WRAPPER <name>
446 ;;; The code for initializing the cache is wrapped in a form with
447 ;;; the specified name. (:INIT-WRAPPER is set to COLD-INIT-FORMS
448 ;;; in type system definitions so that caches will be created
449 ;;; before top level forms run.)
450 (defmacro define-hash-cache (name args &key hash-function hash-bits default
451 (init-wrapper 'progn)
453 (let* ((var-name (symbolicate "*" name "-CACHE-VECTOR*"))
454 (nargs (length args))
455 (entry-size (+ nargs values))
456 (size (ash 1 hash-bits))
457 (total-size (* entry-size size))
458 (default-values (if (and (consp default) (eq (car default) 'values))
464 (unless (= (length default-values) values)
465 (error "The number of default values ~S differs from :VALUES ~W."
477 (values-indices `(+ ,n-index ,(+ nargs i)))
478 (values-names (gensym)))
481 (unless (= (length arg) 2)
482 (error "bad argument spec: ~S" arg))
483 (let ((arg-name (first arg))
486 (tests `(,test (svref ,n-cache (+ ,n-index ,n)) ,arg-name))
487 (sets `(setf (svref ,n-cache (+ ,n-index ,n)) ,arg-name)))
490 (when *profile-hash-cache*
491 (let ((n-probe (symbolicate "*" name "-CACHE-PROBES*"))
492 (n-miss (symbolicate "*" name "-CACHE-MISSES*")))
493 (inits `(setq ,n-probe 0))
494 (inits `(setq ,n-miss 0))
495 (forms `(defvar ,n-probe))
496 (forms `(defvar ,n-miss))
497 (forms `(declaim (fixnum ,n-miss ,n-probe)))))
499 (let ((fun-name (symbolicate name "-CACHE-LOOKUP")))
502 `(defun ,fun-name ,(arg-vars)
503 ,@(when *profile-hash-cache*
504 `((incf ,(symbolicate "*" name "-CACHE-PROBES*"))))
505 (let ((,n-index (* (,hash-function ,@(arg-vars)) ,entry-size))
506 (,n-cache ,var-name))
507 (declare (type fixnum ,n-index))
508 (cond ((and ,@(tests))
509 (values ,@(mapcar (lambda (x) `(svref ,n-cache ,x))
512 ,@(when *profile-hash-cache*
513 `((incf ,(symbolicate "*" name "-CACHE-MISSES*"))))
516 (let ((fun-name (symbolicate name "-CACHE-ENTER")))
519 `(defun ,fun-name (,@(arg-vars) ,@(values-names))
520 (let ((,n-index (* (,hash-function ,@(arg-vars)) ,entry-size))
521 (,n-cache ,var-name))
522 (declare (type fixnum ,n-index))
524 ,@(mapcar (lambda (i val)
525 `(setf (svref ,n-cache ,i) ,val))
530 (let ((fun-name (symbolicate name "-CACHE-CLEAR")))
533 (do ((,n-index ,(- total-size entry-size) (- ,n-index ,entry-size))
534 (,n-cache ,var-name))
536 (declare (type fixnum ,n-index))
537 ,@(collect ((arg-sets))
539 (arg-sets `(setf (svref ,n-cache (+ ,n-index ,i)) nil)))
541 ,@(mapcar (lambda (i val)
542 `(setf (svref ,n-cache ,i) ,val))
546 (forms `(,fun-name)))
548 (inits `(unless (boundp ',var-name)
549 (setq ,var-name (make-array ,total-size))))
550 #!+sb-show (inits `(setq *hash-caches-initialized-p* t))
554 (declaim (type (simple-vector ,total-size) ,var-name))
555 #!-sb-fluid (declaim (inline ,@(inlines)))
556 (,init-wrapper ,@(inits))
560 ;;; some syntactic sugar for defining a function whose values are
561 ;;; cached by DEFINE-HASH-CACHE
562 (defmacro defun-cached ((name &rest options &key (values 1) default
564 args &body body-decls-doc)
565 (let ((default-values (if (and (consp default) (eq (car default) 'values))
568 (arg-names (mapcar #'car args)))
569 (collect ((values-names))
571 (values-names (gensym)))
572 (multiple-value-bind (body decls doc) (parse-body body-decls-doc)
574 (define-hash-cache ,name ,args ,@options)
575 (defun ,name ,arg-names
579 ((not (boundp '*hash-caches-initialized-p*))
580 ;; This shouldn't happen, but it did happen to me
581 ;; when revising the type system, and it's a lot
582 ;; easier to figure out what what's going on with
583 ;; that kind of problem if the system can be kept
584 ;; alive until cold boot is complete. The recovery
585 ;; mechanism should definitely be conditional on
586 ;; some debugging feature (e.g. SB-SHOW) because
587 ;; it's big, duplicating all the BODY code. -- WHN
588 (/show0 ,name " too early in cold init, uncached")
589 (/show0 ,(first arg-names) "=..")
590 (/hexstr ,(first arg-names))
593 (multiple-value-bind ,(values-names)
594 (,(symbolicate name "-CACHE-LOOKUP") ,@arg-names)
595 (if (and ,@(mapcar (lambda (val def)
597 (values-names) default-values))
598 (multiple-value-bind ,(values-names)
600 (,(symbolicate name "-CACHE-ENTER") ,@arg-names
602 (values ,@(values-names)))
603 (values ,@(values-names))))))))))))
605 (defmacro define-cached-synonym
606 (name &optional (original (symbolicate "%" name)))
607 (let ((cached-name (symbolicate "%%" name "-CACHED")))
609 (defun-cached (,cached-name :hash-bits 8
610 :hash-function (lambda (x)
611 (logand (sxhash x) #xff)))
613 (apply #',original args))
614 (defun ,name (&rest args)
615 (,cached-name args)))))
617 ;;; FIXME: maybe not the best place
619 ;;; FIXME: think of a better name -- not only does this not have the
620 ;;; CAR recursion of EQUAL, it also doesn't have the special treatment
621 ;;; of pathnames, bit-vectors and strings.
623 ;;; KLUDGE: This means that we will no longer cache specifiers of the
624 ;;; form '(INTEGER (0) 4). This is probably not a disaster.
626 ;;; A helper function for the type system, which is the main user of
627 ;;; these caches: we must be more conservative than EQUAL for some of
628 ;;; our equality tests, because MEMBER and friends refer to EQLity.
630 (defun equal-but-no-car-recursion (x y)
635 (eql (car x) (car y))
636 (equal-but-no-car-recursion (cdr x) (cdr y))))
641 ;;; Note: Almost always you want to use FIND-UNDELETED-PACKAGE-OR-LOSE
642 ;;; instead of this function. (The distinction only actually matters when
643 ;;; PACKAGE-DESIGNATOR is actually a deleted package, and in that case
644 ;;; you generally do want to signal an error instead of proceeding.)
645 (defun %find-package-or-lose (package-designator)
646 (or (find-package package-designator)
647 (error 'sb!kernel:simple-package-error
648 :package package-designator
649 :format-control "The name ~S does not designate any package."
650 :format-arguments (list package-designator))))
652 ;;; ANSI specifies (in the section for FIND-PACKAGE) that the
653 ;;; consequences of most operations on deleted packages are
654 ;;; unspecified. We try to signal errors in such cases.
655 (defun find-undeleted-package-or-lose (package-designator)
656 (let ((maybe-result (%find-package-or-lose package-designator)))
657 (if (package-name maybe-result) ; if not deleted
659 (error 'sb!kernel:simple-package-error
660 :package maybe-result
661 :format-control "The package ~S has been deleted."
662 :format-arguments (list maybe-result)))))
664 ;;;; various operations on names
666 ;;; Is NAME a legal function name?
667 (declaim (inline legal-fun-name-p))
668 (defun legal-fun-name-p (name)
669 (values (valid-function-name-p name)))
671 (deftype function-name () '(satisfies legal-fun-name-p))
673 ;;; Signal an error unless NAME is a legal function name.
674 (defun legal-fun-name-or-type-error (name)
675 (unless (legal-fun-name-p name)
676 (error 'simple-type-error
678 :expected-type 'function-name
679 :format-control "invalid function name: ~S"
680 :format-arguments (list name))))
682 ;;; Given a function name, return the symbol embedded in it.
684 ;;; The ordinary use for this operator (and the motivation for the
685 ;;; name of this operator) is to convert from a function name to the
686 ;;; name of the BLOCK which encloses its body.
688 ;;; Occasionally the operator is useful elsewhere, where the operator
689 ;;; name is less mnemonic. (Maybe it should be changed?)
690 (declaim (ftype (function ((or symbol cons)) symbol) fun-name-block-name))
691 (defun fun-name-block-name (fun-name)
692 (cond ((symbolp fun-name)
695 (multiple-value-bind (legalp block-name)
696 (valid-function-name-p fun-name)
699 (error "not legal as a function name: ~S" fun-name))))
701 (error "not legal as a function name: ~S" fun-name))))
703 (defun looks-like-name-of-special-var-p (x)
705 (let ((name (symbol-name x)))
706 (and (> (length name) 2) ; to exclude '* and '**
707 (char= #\* (aref name 0))
708 (char= #\* (aref name (1- (length name))))))))
710 ;;; Some symbols are defined by ANSI to be self-evaluating. Return
711 ;;; non-NIL for such symbols (and make the non-NIL value a traditional
712 ;;; message, for use in contexts where the user asks us to change such
714 (defun symbol-self-evaluating-p (symbol)
715 (declare (type symbol symbol))
717 "Veritas aeterna. (can't change T)")
719 "Nihil ex nihil. (can't change NIL)")
721 "Keyword values can't be changed.")
725 ;;; This function is to be called just before a change which would
726 ;;; affect the symbol value. (We don't absolutely have to call this
727 ;;; function before such changes, since such changes are given as
728 ;;; undefined behavior. In particular, we don't if the runtime cost
729 ;;; would be annoying. But otherwise it's nice to do so.)
730 (defun about-to-modify-symbol-value (symbol)
731 (declare (type symbol symbol))
732 (let ((reason (symbol-self-evaluating-p symbol)))
735 ;; (Note: Just because a value is CONSTANTP is not a good enough
736 ;; reason to complain here, because we want DEFCONSTANT to be able
737 ;; to use this function, and it's legal to DEFCONSTANT a constant as
738 ;; long as the new value is EQL to the old value.)
742 ;;; If COLD-FSET occurs not at top level, just treat it as an ordinary
743 ;;; assignment instead of doing cold static linking. That way things like
744 ;;; (FLET ((FROB (X) ..))
745 ;;; (DEFUN FOO (X Y) (FROB X) ..)
746 ;;; (DEFUN BAR (Z) (AND (FROB X) ..)))
747 ;;; can still "work" for cold init: they don't do magical static
748 ;;; linking the way that true toplevel DEFUNs do, but at least they do
749 ;;; the linking eventually, so as long as #'FOO and #'BAR aren't
750 ;;; needed until "cold toplevel forms" have executed, it's OK.
751 (defmacro cold-fset (name lambda)
753 "~@<COLD-FSET ~S not cross-compiled at top level: demoting to ~
754 (SETF FDEFINITION)~:@>"
756 ;; We convert the LAMBDA expression to the corresponding NAMED-LAMBDA
757 ;; expression so that the compiler can use NAME in debug names etc.
758 (destructuring-bind (lambda-symbol &rest lambda-rest) lambda
759 (assert (eql lambda-symbol 'lambda)) ; else dunno how to do conversion
760 `(setf (fdefinition ',name)
761 (named-lambda ,name ,@lambda-rest))))
765 ;;;; "The macro ONCE-ONLY has been around for a long time on various
766 ;;;; systems [..] if you can understand how to write and when to use
767 ;;;; ONCE-ONLY, then you truly understand macro." -- Peter Norvig,
768 ;;;; _Paradigms of Artificial Intelligence Programming: Case Studies
769 ;;;; in Common Lisp_, p. 853
771 ;;; ONCE-ONLY is a utility useful in writing source transforms and
772 ;;; macros. It provides a concise way to wrap a LET around some code
773 ;;; to ensure that some forms are only evaluated once.
775 ;;; Create a LET* which evaluates each value expression, binding a
776 ;;; temporary variable to the result, and wrapping the LET* around the
777 ;;; result of the evaluation of BODY. Within the body, each VAR is
778 ;;; bound to the corresponding temporary variable.
779 (defmacro once-only (specs &body body)
780 (named-let frob ((specs specs)
784 (let ((spec (first specs)))
785 ;; FIXME: should just be DESTRUCTURING-BIND of SPEC
786 (unless (proper-list-of-length-p spec 2)
787 (error "malformed ONCE-ONLY binding spec: ~S" spec))
788 (let* ((name (first spec))
789 (exp-temp (gensym (symbol-name name))))
790 `(let ((,exp-temp ,(second spec))
791 (,name (gensym "ONCE-ONLY-")))
792 `(let ((,,name ,,exp-temp))
793 ,,(frob (rest specs) body))))))))
795 ;;;; various error-checking utilities
797 ;;; This function can be used as the default value for keyword
798 ;;; arguments that must be always be supplied. Since it is known by
799 ;;; the compiler to never return, it will avoid any compile-time type
800 ;;; warnings that would result from a default value inconsistent with
801 ;;; the declared type. When this function is called, it signals an
802 ;;; error indicating that a required &KEY argument was not supplied.
803 ;;; This function is also useful for DEFSTRUCT slot defaults
804 ;;; corresponding to required arguments.
805 (declaim (ftype (function () nil) missing-arg))
806 (defun missing-arg ()
808 (/show0 "entering MISSING-ARG")
809 (error "A required &KEY or &OPTIONAL argument was not supplied."))
811 ;;; like CL:ASSERT and CL:CHECK-TYPE, but lighter-weight
813 ;;; (As of sbcl-0.6.11.20, we were using some 400 calls to CL:ASSERT.
814 ;;; The CL:ASSERT restarts and whatnot expand into a significant
815 ;;; amount of code when you multiply them by 400, so replacing them
816 ;;; with this should reduce the size of the system by enough to be
817 ;;; worthwhile. ENFORCE-TYPE is much less common, but might still be
818 ;;; worthwhile, and since I don't really like CERROR stuff deep in the
819 ;;; guts of complex systems anyway, I replaced it too.)
820 (defmacro aver (expr)
822 (%failed-aver ,(format nil "~A" expr))))
824 (defun %failed-aver (expr-as-string)
825 ;; hackish way to tell we're in a cold sbcl and output the
826 ;; message before signallign error, as it may be this is too
827 ;; early in the cold init.
828 (when (find-package "SB!C")
830 (write-line "failed AVER:")
831 (write-line expr-as-string)
833 (bug "~@<failed AVER: ~2I~_~S~:>" expr-as-string))
835 (defun bug (format-control &rest format-arguments)
837 :format-control format-control
838 :format-arguments format-arguments))
840 (defmacro enforce-type (value type)
841 (once-only ((value value))
842 `(unless (typep ,value ',type)
843 (%failed-enforce-type ,value ',type))))
845 (defun %failed-enforce-type (value type)
846 ;; maybe should be TYPE-BUG, subclass of BUG? If it is changed,
847 ;; check uses of it in user-facing code (e.g. WARN)
848 (error 'simple-type-error
851 :format-control "~@<~S ~_is not a ~_~S~:>"
852 :format-arguments (list value type)))
854 ;;; Return a function like FUN, but expecting its (two) arguments in
855 ;;; the opposite order that FUN does.
856 (declaim (inline swapped-args-fun))
857 (defun swapped-args-fun (fun)
858 (declare (type function fun))
862 ;;; Return the numeric value of a type bound, i.e. an interval bound
863 ;;; more or less in the format of bounds in ANSI's type specifiers,
864 ;;; where a bare numeric value is a closed bound and a list of a
865 ;;; single numeric value is an open bound.
867 ;;; The "more or less" bit is that the no-bound-at-all case is
868 ;;; represented by NIL (not by * as in ANSI type specifiers); and in
869 ;;; this case we return NIL.
870 (defun type-bound-number (x)
872 (destructuring-bind (result) x result)
875 ;;; some commonly-occuring CONSTANTLY forms
876 (macrolet ((def-constantly-fun (name constant-expr)
877 `(setf (symbol-function ',name)
878 (constantly ,constant-expr))))
879 (def-constantly-fun constantly-t t)
880 (def-constantly-fun constantly-nil nil)
881 (def-constantly-fun constantly-0 0))
883 ;;; If X is an atom, see whether it is present in *FEATURES*. Also
884 ;;; handle arbitrary combinations of atoms using NOT, AND, OR.
890 (error "too many subexpressions in feature expression: ~S" x)
891 (not (featurep (cadr x)))))
892 ((:and and) (every #'featurep (cdr x)))
893 ((:or or) (some #'featurep (cdr x)))
895 (error "unknown operator in feature expression: ~S." x)))
896 (not (null (memq x *features*)))))
898 ;;; Given a list of keyword substitutions `(,OLD ,NEW), and a
899 ;;; &KEY-argument-list-style list of alternating keywords and
900 ;;; arbitrary values, return a new &KEY-argument-list-style list with
901 ;;; all substitutions applied to it.
903 ;;; Note: If efficiency mattered, we could do less consing. (But if
904 ;;; efficiency mattered, why would we be using &KEY arguments at
905 ;;; all, much less renaming &KEY arguments?)
907 ;;; KLUDGE: It would probably be good to get rid of this. -- WHN 19991201
908 (defun rename-key-args (rename-list key-args)
909 (declare (type list rename-list key-args))
910 ;; Walk through RENAME-LIST modifying RESULT as per each element in
912 (do ((result (copy-list key-args))) ; may be modified below
913 ((null rename-list) result)
914 (destructuring-bind (old new) (pop rename-list)
915 ;; ANSI says &KEY arg names aren't necessarily KEYWORDs.
916 (declare (type symbol old new))
917 ;; Walk through RESULT renaming any OLD key argument to NEW.
918 (do ((in-result result (cddr in-result)))
920 (declare (type list in-result))
921 (when (eq (car in-result) old)
922 (setf (car in-result) new))))))
924 ;;; ANSI Common Lisp's READ-SEQUENCE function, unlike most of the
925 ;;; other ANSI input functions, is defined to communicate end of file
926 ;;; status with its return value, not by signalling. That is not the
927 ;;; behavior that we usually want. This function is a wrapper which
928 ;;; restores the behavior that we usually want, causing READ-SEQUENCE
929 ;;; to communicate end-of-file status by signalling.
930 (defun read-sequence-or-die (sequence stream &key start end)
931 ;; implementation using READ-SEQUENCE
932 #-no-ansi-read-sequence
933 (let ((read-end (read-sequence sequence
937 (unless (= read-end end)
938 (error 'end-of-file :stream stream))
940 ;; workaround for broken READ-SEQUENCE
941 #+no-ansi-read-sequence
943 (aver (<= start end))
944 (let ((etype (stream-element-type stream)))
945 (cond ((equal etype '(unsigned-byte 8))
946 (do ((i start (1+ i)))
949 (setf (aref sequence i)
950 (read-byte stream))))
951 (t (error "unsupported element type ~S" etype))))))
953 ;;;; utilities for two-VALUES predicates
955 (defmacro not/type (x)
956 (let ((val (gensym "VAL"))
957 (win (gensym "WIN")))
958 `(multiple-value-bind (,val ,win)
961 (values (not ,val) t)
964 (defmacro and/type (x y)
965 `(multiple-value-bind (val1 win1) ,x
966 (if (and (not val1) win1)
968 (multiple-value-bind (val2 win2) ,y
971 (values nil (and win2 (not val2))))))))
973 ;;; sort of like ANY and EVERY, except:
974 ;;; * We handle two-VALUES predicate functions, as SUBTYPEP does.
975 ;;; (And if the result is uncertain, then we return (VALUES NIL NIL),
976 ;;; as SUBTYPEP does.)
977 ;;; * THING is just an atom, and we apply OP (an arity-2 function)
978 ;;; successively to THING and each element of LIST.
979 (defun any/type (op thing list)
980 (declare (type function op))
982 (dolist (i list (values nil certain?))
983 (multiple-value-bind (sub-value sub-certain?) (funcall op thing i)
985 (when sub-value (return (values t t)))
986 (setf certain? nil))))))
987 (defun every/type (op thing list)
988 (declare (type function op))
990 (dolist (i list (if certain? (values t t) (values nil nil)))
991 (multiple-value-bind (sub-value sub-certain?) (funcall op thing i)
993 (unless sub-value (return (values nil t)))
994 (setf certain? nil))))))
998 ;;; These functions are called by the expansion of the DEFPRINTER
999 ;;; macro to do the actual printing.
1000 (declaim (ftype (function (symbol t stream) (values))
1001 defprinter-prin1 defprinter-princ))
1002 (defun defprinter-prin1 (name value stream)
1003 (defprinter-prinx #'prin1 name value stream))
1004 (defun defprinter-princ (name value stream)
1005 (defprinter-prinx #'princ name value stream))
1006 (defun defprinter-prinx (prinx name value stream)
1007 (declare (type function prinx))
1008 (when *print-pretty*
1009 (pprint-newline :linear stream))
1010 (format stream ":~A " name)
1011 (funcall prinx value stream)
1013 (defun defprinter-print-space (stream)
1014 (write-char #\space stream))
1016 ;;; Define some kind of reasonable PRINT-OBJECT method for a
1017 ;;; STRUCTURE-OBJECT class.
1019 ;;; NAME is the name of the structure class, and CONC-NAME is the same
1020 ;;; as in DEFSTRUCT.
1022 ;;; The SLOT-DESCS describe how each slot should be printed. Each
1023 ;;; SLOT-DESC can be a slot name, indicating that the slot should
1024 ;;; simply be printed. A SLOT-DESC may also be a list of a slot name
1025 ;;; and other stuff. The other stuff is composed of keywords followed
1026 ;;; by expressions. The expressions are evaluated with the variable
1027 ;;; which is the slot name bound to the value of the slot. These
1028 ;;; keywords are defined:
1030 ;;; :PRIN1 Print the value of the expression instead of the slot value.
1031 ;;; :PRINC Like :PRIN1, only PRINC the value
1032 ;;; :TEST Only print something if the test is true.
1034 ;;; If no printing thing is specified then the slot value is printed
1037 ;;; The structure being printed is bound to STRUCTURE and the stream
1038 ;;; is bound to STREAM.
1039 (defmacro defprinter ((name
1041 (conc-name (concatenate 'simple-string
1048 (reversed-prints nil)
1049 (stream (gensym "STREAM")))
1050 (flet ((sref (slot-name)
1051 `(,(symbolicate conc-name slot-name) structure)))
1052 (dolist (slot-desc slot-descs)
1054 (setf maybe-print-space nil
1056 (setf maybe-print-space `(defprinter-print-space ,stream)))
1057 (cond ((atom slot-desc)
1058 (push maybe-print-space reversed-prints)
1059 (push `(defprinter-prin1 ',slot-desc ,(sref slot-desc) ,stream)
1062 (let ((sname (first slot-desc))
1065 (do ((option (rest slot-desc) (cddr option)))
1067 (push `(let ((,sname ,(sref sname)))
1072 ',sname ,sname ,stream)))))
1074 (case (first option)
1076 (stuff `(defprinter-prin1
1077 ',sname ,(second option) ,stream)))
1079 (stuff `(defprinter-princ
1080 ',sname ,(second option) ,stream)))
1081 (:test (setq test (second option)))
1083 (error "bad option: ~S" (first option)))))))))))
1084 `(def!method print-object ((structure ,name) ,stream)
1085 (pprint-logical-block (,stream nil)
1086 (print-unreadable-object (structure
1089 :identity ,identity)
1090 ,@(nreverse reversed-prints))))))
1094 ;;; Given a pathname, return a corresponding physical pathname.
1095 (defun physicalize-pathname (possibly-logical-pathname)
1096 (if (typep possibly-logical-pathname 'logical-pathname)
1097 (translate-logical-pathname possibly-logical-pathname)
1098 possibly-logical-pathname))
1100 (defun deprecation-warning (bad-name &optional good-name)
1101 (warn "using deprecated ~S~@[, should use ~S instead~]"
1105 ;;; Anaphoric macros
1106 (defmacro awhen (test &body body)
1110 (defmacro acond (&rest clauses)
1113 (destructuring-bind ((test &body body) &rest rest) clauses
1114 (once-only ((test test))
1116 (let ((it ,test)) (declare (ignorable it)),@body)
1119 ;;; (binding* ({(names initial-value [flag])}*) body)
1120 ;;; FLAG may be NIL or :EXIT-IF-NULL
1122 ;;; This form unites LET*, MULTIPLE-VALUE-BIND and AWHEN.
1123 (defmacro binding* ((&rest bindings) &body body)
1124 (let ((bindings (reverse bindings)))
1125 (loop with form = `(progn ,@body)
1126 for binding in bindings
1127 do (destructuring-bind (names initial-value &optional flag)
1129 (multiple-value-bind (names declarations)
1132 (let ((name (gensym)))
1133 (values (list name) `((declare (ignorable ,name))))))
1135 (values (list names) nil))
1137 (collect ((new-names) (ignorable))
1138 (dolist (name names)
1140 (setq name (gensym))
1145 `((declare (ignorable ,@(ignorable)))))))))
1146 (setq form `(multiple-value-bind ,names
1152 `(when ,(first names) ,form)))))))
1153 finally (return form))))
1155 ;;; Delayed evaluation
1156 (defmacro delay (form)
1157 `(cons nil (lambda () ,form)))
1159 (defun force (promise)
1160 (cond ((not (consp promise)) promise)
1161 ((car promise) (cdr promise))
1162 (t (setf (car promise) t
1163 (cdr promise) (funcall (cdr promise))))))
1165 (defun promise-ready-p (promise)
1166 (or (not (consp promise))
1170 (defmacro with-rebound-io-syntax (&body body)
1171 `(%with-rebound-io-syntax (lambda () ,@body)))
1173 (defun %with-rebound-io-syntax (function)
1174 (declare (type function function))
1175 (let ((*package* *package*)
1176 (*print-array* *print-array*)
1177 (*print-base* *print-base*)
1178 (*print-case* *print-case*)
1179 (*print-circle* *print-circle*)
1180 (*print-escape* *print-escape*)
1181 (*print-gensym* *print-gensym*)
1182 (*print-length* *print-length*)
1183 (*print-level* *print-level*)
1184 (*print-lines* *print-lines*)
1185 (*print-miser-width* *print-miser-width*)
1186 (*print-pretty* *print-pretty*)
1187 (*print-radix* *print-radix*)
1188 (*print-readably* *print-readably*)
1189 (*print-right-margin* *print-right-margin*)
1190 (*read-base* *read-base*)
1191 (*read-default-float-format* *read-default-float-format*)
1192 (*read-eval* *read-eval*)
1193 (*read-suppress* *read-suppress*)
1194 (*readtable* *readtable*))
1195 (funcall function)))
1197 ;;; Bind a few "potentially dangerous" printer control variables to
1198 ;;; safe values, respecting current values if possible.
1199 (defmacro with-sane-io-syntax (&body forms)
1200 `(call-with-sane-io-syntax (lambda () ,@forms)))
1202 (defun call-with-sane-io-syntax (function)
1203 (declare (type function function))
1204 (macrolet ((true (sym)
1205 `(and (boundp ',sym) ,sym)))
1206 (let ((*print-readably* nil)
1207 (*print-level* (or (true *print-level*) 6))
1208 (*print-length* (or (true *print-length*) 12)))
1209 (funcall function))))
1211 ;;; Default evaluator mode (interpeter / compiler)
1213 (declaim (type (member :compile #!+sb-eval :interpret) *evaluator-mode*))
1214 (defparameter *evaluator-mode* :compile
1216 "Toggle between different evaluator implementations. If set to :COMPILE,
1217 an implementation of EVAL that calls the compiler will be used. If set
1218 to :INTERPRET, an interpreter will be used.")