0.9.9.29
[sbcl.git] / src / code / late-type.lisp
1 ;;;; This file contains the definition of non-CLASS types (e.g.
2 ;;;; subtypes of interesting BUILT-IN-CLASSes) and the interfaces to
3 ;;;; the type system. Common Lisp type specifiers are parsed into a
4 ;;;; somewhat canonical internal type representation that supports
5 ;;;; type union, intersection, etc. (Except that ALIEN types have
6 ;;;; moved out..)
7
8 ;;;; This software is part of the SBCL system. See the README file for
9 ;;;; more information.
10 ;;;;
11 ;;;; This software is derived from the CMU CL system, which was
12 ;;;; written at Carnegie Mellon University and released into the
13 ;;;; public domain. The software is in the public domain and is
14 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
15 ;;;; files for more information.
16
17 (in-package "SB!KERNEL")
18
19 (/show0 "late-type.lisp 19")
20
21 (!begin-collecting-cold-init-forms)
22
23 ;;; ### Remaining incorrectnesses:
24 ;;;
25 ;;; There are all sorts of nasty problems with open bounds on FLOAT
26 ;;; types (and probably FLOAT types in general.)
27
28 ;;; This condition is signalled whenever we make a UNKNOWN-TYPE so that
29 ;;; compiler warnings can be emitted as appropriate.
30 (define-condition parse-unknown-type (condition)
31   ((specifier :reader parse-unknown-type-specifier :initarg :specifier)))
32
33 ;;; FIXME: This really should go away. Alas, it doesn't seem to be so
34 ;;; simple to make it go away.. (See bug 123 in BUGS file.)
35 (defvar *use-implementation-types* t ; actually initialized in cold init
36   #!+sb-doc
37   "*USE-IMPLEMENTATION-TYPES* is a semi-public flag which determines how
38    restrictive we are in determining type membership. If two types are the
39    same in the implementation, then we will consider them them the same when
40    this switch is on. When it is off, we try to be as restrictive as the
41    language allows, allowing us to detect more errors. Currently, this only
42    affects array types.")
43 (!cold-init-forms (setq *use-implementation-types* t))
44
45 ;;; These functions are used as method for types which need a complex
46 ;;; subtypep method to handle some superclasses, but cover a subtree
47 ;;; of the type graph (i.e. there is no simple way for any other type
48 ;;; class to be a subtype.) There are always still complex ways,
49 ;;; namely UNION and MEMBER types, so we must give TYPE1's method a
50 ;;; chance to run, instead of immediately returning NIL, T.
51 (defun delegate-complex-subtypep-arg2 (type1 type2)
52   (let ((subtypep-arg1
53          (type-class-complex-subtypep-arg1
54           (type-class-info type1))))
55     (if subtypep-arg1
56         (funcall subtypep-arg1 type1 type2)
57         (values nil t))))
58 (defun delegate-complex-intersection2 (type1 type2)
59   (let ((method (type-class-complex-intersection2 (type-class-info type1))))
60     (if (and method (not (eq method #'delegate-complex-intersection2)))
61         (funcall method type2 type1)
62         (hierarchical-intersection2 type1 type2))))
63
64 ;;; This is used by !DEFINE-SUPERCLASSES to define the SUBTYPE-ARG1
65 ;;; method. INFO is a list of conses
66 ;;;   (SUPERCLASS-CLASS . {GUARD-TYPE-SPECIFIER | NIL}).
67 (defun !has-superclasses-complex-subtypep-arg1 (type1 type2 info)
68   ;; If TYPE2 might be concealing something related to our class
69   ;; hierarchy
70   (if (type-might-contain-other-types-p type2)
71       ;; too confusing, gotta punt
72       (values nil nil)
73       ;; ordinary case expected by old CMU CL code, where the taxonomy
74       ;; of TYPE2's representation accurately reflects the taxonomy of
75       ;; the underlying set
76       (values
77        ;; FIXME: This old CMU CL code probably deserves a comment
78        ;; explaining to us mere mortals how it works...
79        (and (sb!xc:typep type2 'classoid)
80             (dolist (x info nil)
81               (when (or (not (cdr x))
82                         (csubtypep type1 (specifier-type (cdr x))))
83                 (return
84                  (or (eq type2 (car x))
85                      (let ((inherits (layout-inherits
86                                       (classoid-layout (car x)))))
87                        (dotimes (i (length inherits) nil)
88                          (when (eq type2 (layout-classoid (svref inherits i)))
89                            (return t)))))))))
90        t)))
91
92 ;;; This function takes a list of specs, each of the form
93 ;;;    (SUPERCLASS-NAME &OPTIONAL GUARD).
94 ;;; Consider one spec (with no guard): any instance of the named
95 ;;; TYPE-CLASS is also a subtype of the named superclass and of any of
96 ;;; its superclasses. If there are multiple specs, then some will have
97 ;;; guards. We choose the first spec whose guard is a supertype of
98 ;;; TYPE1 and use its superclass. In effect, a sequence of guards
99 ;;;    G0, G1, G2
100 ;;; is actually
101 ;;;    G0,(and G1 (not G0)), (and G2 (not (or G0 G1))).
102 ;;;
103 ;;; WHEN controls when the forms are executed.
104 (defmacro !define-superclasses (type-class-name specs when)
105   (with-unique-names (type-class info)
106     `(,when
107        (let ((,type-class (type-class-or-lose ',type-class-name))
108              (,info (mapcar (lambda (spec)
109                               (destructuring-bind
110                                   (super &optional guard)
111                                   spec
112                                 (cons (find-classoid super) guard)))
113                             ',specs)))
114          (setf (type-class-complex-subtypep-arg1 ,type-class)
115                (lambda (type1 type2)
116                  (!has-superclasses-complex-subtypep-arg1 type1 type2 ,info)))
117          (setf (type-class-complex-subtypep-arg2 ,type-class)
118                #'delegate-complex-subtypep-arg2)
119          (setf (type-class-complex-intersection2 ,type-class)
120                #'delegate-complex-intersection2)))))
121 \f
122 ;;;; FUNCTION and VALUES types
123 ;;;;
124 ;;;; Pretty much all of the general type operations are illegal on
125 ;;;; VALUES types, since we can't discriminate using them, do
126 ;;;; SUBTYPEP, etc. FUNCTION types are acceptable to the normal type
127 ;;;; operations, but are generally considered to be equivalent to
128 ;;;; FUNCTION. These really aren't true types in any type theoretic
129 ;;;; sense, but we still parse them into CTYPE structures for two
130 ;;;; reasons:
131
132 ;;;; -- Parsing and unparsing work the same way, and indeed we can't
133 ;;;;    tell whether a type is a function or values type without
134 ;;;;    parsing it.
135 ;;;; -- Many of the places that can be annotated with real types can
136 ;;;;    also be annotated with function or values types.
137
138 ;;; the description of a &KEY argument
139 (defstruct (key-info #-sb-xc-host (:pure t)
140                      (:copier nil))
141   ;; the key (not necessarily a keyword in ANSI Common Lisp)
142   (name (missing-arg) :type symbol)
143   ;; the type of the argument value
144   (type (missing-arg) :type ctype))
145
146 (!define-type-method (values :simple-subtypep :complex-subtypep-arg1)
147                      (type1 type2)
148   (declare (ignore type2))
149   ;; FIXME: should be TYPE-ERROR, here and in next method
150   (error "SUBTYPEP is illegal on this type:~%  ~S" (type-specifier type1)))
151
152 (!define-type-method (values :complex-subtypep-arg2)
153                      (type1 type2)
154   (declare (ignore type1))
155   (error "SUBTYPEP is illegal on this type:~%  ~S" (type-specifier type2)))
156
157 (!define-type-method (values :negate) (type)
158   (error "NOT VALUES too confusing on ~S" (type-specifier type)))
159
160 (!define-type-method (values :unparse) (type)
161   (cons 'values
162         (let ((unparsed (unparse-args-types type)))
163           (if (or (values-type-optional type)
164                   (values-type-rest type)
165                   (values-type-allowp type))
166               unparsed
167               (nconc unparsed '(&optional))))))
168
169 ;;; Return true if LIST1 and LIST2 have the same elements in the same
170 ;;; positions according to TYPE=. We return NIL, NIL if there is an
171 ;;; uncertain comparison.
172 (defun type=-list (list1 list2)
173   (declare (list list1 list2))
174   (do ((types1 list1 (cdr types1))
175        (types2 list2 (cdr types2)))
176       ((or (null types1) (null types2))
177        (if (or types1 types2)
178            (values nil t)
179            (values t t)))
180     (multiple-value-bind (val win)
181         (type= (first types1) (first types2))
182       (unless win
183         (return (values nil nil)))
184       (unless val
185         (return (values nil t))))))
186
187 (!define-type-method (values :simple-=) (type1 type2)
188   (type=-args type1 type2))
189
190 (!define-type-class function)
191
192 ;;; a flag that we can bind to cause complex function types to be
193 ;;; unparsed as FUNCTION. This is useful when we want a type that we
194 ;;; can pass to TYPEP.
195 (defvar *unparse-fun-type-simplify*)
196 (!cold-init-forms (setq *unparse-fun-type-simplify* nil))
197
198 (!define-type-method (function :negate) (type)
199   (make-negation-type :type type))
200
201 (!define-type-method (function :unparse) (type)
202   (if *unparse-fun-type-simplify*
203       'function
204       (list 'function
205             (if (fun-type-wild-args type)
206                 '*
207                 (unparse-args-types type))
208             (type-specifier
209              (fun-type-returns type)))))
210
211 ;;; The meaning of this is a little confused. On the one hand, all
212 ;;; function objects are represented the same way regardless of the
213 ;;; arglists and return values, and apps don't get to ask things like
214 ;;; (TYPEP #'FOO (FUNCTION (FIXNUM) *)) in any meaningful way. On the
215 ;;; other hand, Python wants to reason about function types. So...
216 (!define-type-method (function :simple-subtypep) (type1 type2)
217  (flet ((fun-type-simple-p (type)
218           (not (or (fun-type-rest type)
219                    (fun-type-keyp type))))
220         (every-csubtypep (types1 types2)
221           (loop
222              for a1 in types1
223              for a2 in types2
224              do (multiple-value-bind (res sure-p)
225                     (csubtypep a1 a2)
226                   (unless res (return (values res sure-p))))
227              finally (return (values t t)))))
228    (and/type (values-subtypep (fun-type-returns type1)
229                               (fun-type-returns type2))
230              (cond ((fun-type-wild-args type2) (values t t))
231                    ((fun-type-wild-args type1)
232                     (cond ((fun-type-keyp type2) (values nil nil))
233                           ((not (fun-type-rest type2)) (values nil t))
234                           ((not (null (fun-type-required type2)))
235                            (values nil t))
236                           (t (and/type (type= *universal-type*
237                                               (fun-type-rest type2))
238                                        (every/type #'type=
239                                                    *universal-type*
240                                                    (fun-type-optional
241                                                     type2))))))
242                    ((not (and (fun-type-simple-p type1)
243                               (fun-type-simple-p type2)))
244                     (values nil nil))
245                    (t (multiple-value-bind (min1 max1) (fun-type-nargs type1)
246                         (multiple-value-bind (min2 max2) (fun-type-nargs type2)
247                           (cond ((or (> max1 max2) (< min1 min2))
248                                  (values nil t))
249                                 ((and (= min1 min2) (= max1 max2))
250                                  (and/type (every-csubtypep
251                                             (fun-type-required type1)
252                                             (fun-type-required type2))
253                                            (every-csubtypep
254                                             (fun-type-optional type1)
255                                             (fun-type-optional type2))))
256                                 (t (every-csubtypep
257                                     (concatenate 'list
258                                                  (fun-type-required type1)
259                                                  (fun-type-optional type1))
260                                     (concatenate 'list
261                                                  (fun-type-required type2)
262                                                  (fun-type-optional type2))))))))))))
263
264 (!define-superclasses function ((function)) !cold-init-forms)
265
266 ;;; The union or intersection of two FUNCTION types is FUNCTION.
267 (!define-type-method (function :simple-union2) (type1 type2)
268   (declare (ignore type1 type2))
269   (specifier-type 'function))
270 (!define-type-method (function :simple-intersection2) (type1 type2)
271   (let ((ftype (specifier-type 'function)))
272     (cond ((eq type1 ftype) type2)
273           ((eq type2 ftype) type1)
274           (t (let ((rtype (values-type-intersection (fun-type-returns type1)
275                                                     (fun-type-returns type2))))
276                (flet ((change-returns (ftype rtype)
277                         (declare (type fun-type ftype) (type ctype rtype))
278                         (make-fun-type :required (fun-type-required ftype)
279                                        :optional (fun-type-optional ftype)
280                                        :keyp (fun-type-keyp ftype)
281                                        :keywords (fun-type-keywords ftype)
282                                        :allowp (fun-type-allowp ftype)
283                                        :returns rtype)))
284                (cond
285                  ((fun-type-wild-args type1)
286                   (if (fun-type-wild-args type2)
287                       (make-fun-type :wild-args t
288                                      :returns rtype)
289                       (change-returns type2 rtype)))
290                  ((fun-type-wild-args type2)
291                   (change-returns type1 rtype))
292                  (t (multiple-value-bind (req opt rest)
293                         (args-type-op type1 type2 #'type-intersection #'max)
294                       (make-fun-type :required req
295                                      :optional opt
296                                      :rest rest
297                                      ;; FIXME: :keys
298                                      :allowp (and (fun-type-allowp type1)
299                                                   (fun-type-allowp type2))
300                                      :returns rtype))))))))))
301
302 ;;; The union or intersection of a subclass of FUNCTION with a
303 ;;; FUNCTION type is somewhat complicated.
304 (!define-type-method (function :complex-intersection2) (type1 type2)
305   (cond
306     ((type= type1 (specifier-type 'function)) type2)
307     ((csubtypep type1 (specifier-type 'function)) nil)
308     (t :call-other-method)))
309 (!define-type-method (function :complex-union2) (type1 type2)
310   (declare (ignore type2))
311   ;; TYPE2 is a FUNCTION type.  If TYPE1 is a classoid type naming
312   ;; FUNCTION, then it is the union of the two; otherwise, there is no
313   ;; special union.
314   (cond
315     ((type= type1 (specifier-type 'function)) type1)
316     (t nil)))
317
318 (!define-type-method (function :simple-=) (type1 type2)
319   (macrolet ((compare (comparator field)
320                (let ((reader (symbolicate '#:fun-type- field)))
321                  `(,comparator (,reader type1) (,reader type2)))))
322     (and/type (compare type= returns)
323               (cond ((neq (fun-type-wild-args type1) (fun-type-wild-args type2))
324                      (values nil t))
325                     ((eq (fun-type-wild-args type1) t)
326                      (values t t))
327                     (t (type=-args type1 type2))))))
328
329 (!define-type-class constant :inherits values)
330
331 (!define-type-method (constant :negate) (type)
332   (error "NOT CONSTANT too confusing on ~S" (type-specifier type)))
333
334 (!define-type-method (constant :unparse) (type)
335   `(constant-arg ,(type-specifier (constant-type-type type))))
336
337 (!define-type-method (constant :simple-=) (type1 type2)
338   (type= (constant-type-type type1) (constant-type-type type2)))
339
340 (!def-type-translator constant-arg (type)
341   (make-constant-type :type (single-value-specifier-type type)))
342
343 ;;; Return the lambda-list-like type specification corresponding
344 ;;; to an ARGS-TYPE.
345 (declaim (ftype (function (args-type) list) unparse-args-types))
346 (defun unparse-args-types (type)
347   (collect ((result))
348
349     (dolist (arg (args-type-required type))
350       (result (type-specifier arg)))
351
352     (when (args-type-optional type)
353       (result '&optional)
354       (dolist (arg (args-type-optional type))
355         (result (type-specifier arg))))
356
357     (when (args-type-rest type)
358       (result '&rest)
359       (result (type-specifier (args-type-rest type))))
360
361     (when (args-type-keyp type)
362       (result '&key)
363       (dolist (key (args-type-keywords type))
364         (result (list (key-info-name key)
365                       (type-specifier (key-info-type key))))))
366
367     (when (args-type-allowp type)
368       (result '&allow-other-keys))
369
370     (result)))
371
372 (!def-type-translator function (&optional (args '*) (result '*))
373   (make-fun-type :args args
374                  :returns (coerce-to-values (values-specifier-type result))))
375
376 (!def-type-translator values (&rest values)
377   (make-values-type :args values))
378 \f
379 ;;;; VALUES types interfaces
380 ;;;;
381 ;;;; We provide a few special operations that can be meaningfully used
382 ;;;; on VALUES types (as well as on any other type).
383
384 (defun type-single-value-p (type)
385   (and (values-type-p type)
386        (not (values-type-rest type))
387        (null (values-type-optional type))
388        (singleton-p (values-type-required type))))
389
390 ;;; Return the type of the first value indicated by TYPE. This is used
391 ;;; by people who don't want to have to deal with VALUES types.
392 #!-sb-fluid (declaim (freeze-type values-type))
393 ; (inline single-value-type))
394 (defun single-value-type (type)
395   (declare (type ctype type))
396   (cond ((eq type *wild-type*)
397          *universal-type*)
398         ((eq type *empty-type*)
399          *empty-type*)
400         ((not (values-type-p type))
401          type)
402         (t (or (car (args-type-required type))
403                (car (args-type-optional type))
404                (args-type-rest type)
405                (specifier-type 'null)))))
406
407 ;;; Return the minimum number of arguments that a function can be
408 ;;; called with, and the maximum number or NIL. If not a function
409 ;;; type, return NIL, NIL.
410 (defun fun-type-nargs (type)
411   (declare (type ctype type))
412   (if (and (fun-type-p type) (not (fun-type-wild-args type)))
413       (let ((fixed (length (args-type-required type))))
414         (if (or (args-type-rest type)
415                 (args-type-keyp type)
416                 (args-type-allowp type))
417             (values fixed nil)
418             (values fixed (+ fixed (length (args-type-optional type))))))
419       (values nil nil)))
420
421 ;;; Determine whether TYPE corresponds to a definite number of values.
422 ;;; The first value is a list of the types for each value, and the
423 ;;; second value is the number of values. If the number of values is
424 ;;; not fixed, then return NIL and :UNKNOWN.
425 (defun values-types (type)
426   (declare (type ctype type))
427   (cond ((or (eq type *wild-type*) (eq type *empty-type*))
428          (values nil :unknown))
429         ((or (args-type-optional type)
430              (args-type-rest type))
431          (values nil :unknown))
432         (t
433          (let ((req (args-type-required type)))
434            (values req (length req))))))
435
436 ;;; Return two values:
437 ;;; 1. A list of all the positional (fixed and optional) types.
438 ;;; 2. The &REST type (if any). If no &REST, then the DEFAULT-TYPE.
439 (defun values-type-types (type &optional (default-type *empty-type*))
440   (declare (type ctype type))
441   (if (eq type *wild-type*)
442       (values nil *universal-type*)
443       (values (append (args-type-required type)
444                       (args-type-optional type))
445               (cond ((args-type-rest type))
446                     (t default-type)))))
447
448 ;;; types of values in (the <type> (values o_1 ... o_n))
449 (defun values-type-out (type count)
450   (declare (type ctype type) (type unsigned-byte count))
451   (if (eq type *wild-type*)
452       (make-list count :initial-element *universal-type*)
453       (collect ((res))
454         (flet ((process-types (types)
455                  (loop for type in types
456                        while (plusp count)
457                        do (decf count)
458                        do (res type))))
459           (process-types (values-type-required type))
460           (process-types (values-type-optional type))
461           (when (plusp count)
462             (loop with rest = (the ctype (values-type-rest type))
463                   repeat count
464                   do (res rest))))
465         (res))))
466
467 ;;; types of variable in (m-v-bind (v_1 ... v_n) (the <type> ...
468 (defun values-type-in (type count)
469   (declare (type ctype type) (type unsigned-byte count))
470   (if (eq type *wild-type*)
471       (make-list count :initial-element *universal-type*)
472       (collect ((res))
473         (let ((null-type (specifier-type 'null)))
474           (loop for type in (values-type-required type)
475              while (plusp count)
476              do (decf count)
477              do (res type))
478           (loop for type in (values-type-optional type)
479              while (plusp count)
480              do (decf count)
481              do (res (type-union type null-type)))
482           (when (plusp count)
483             (loop with rest = (acond ((values-type-rest type)
484                                       (type-union it null-type))
485                                      (t null-type))
486                repeat count
487                do (res rest))))
488         (res))))
489
490 ;;; Return a list of OPERATION applied to the types in TYPES1 and
491 ;;; TYPES2, padding with REST2 as needed. TYPES1 must not be shorter
492 ;;; than TYPES2. The second value is T if OPERATION always returned a
493 ;;; true second value.
494 (defun fixed-values-op (types1 types2 rest2 operation)
495   (declare (list types1 types2) (type ctype rest2) (type function operation))
496   (let ((exact t))
497     (values (mapcar (lambda (t1 t2)
498                       (multiple-value-bind (res win)
499                           (funcall operation t1 t2)
500                         (unless win
501                           (setq exact nil))
502                         res))
503                     types1
504                     (append types2
505                             (make-list (- (length types1) (length types2))
506                                        :initial-element rest2)))
507             exact)))
508
509 ;;; If TYPE isn't a values type, then make it into one.
510 (defun-cached (%coerce-to-values
511                :hash-bits 8
512                :hash-function (lambda (type)
513                                 (logand (type-hash-value type)
514                                         #xff)))
515     ((type eq))
516   (cond ((multiple-value-bind (res sure)
517              (csubtypep (specifier-type 'null) type)
518            (and (not res) sure))
519          ;; FIXME: What should we do with (NOT SURE)?
520          (make-values-type :required (list type) :rest *universal-type*))
521         (t
522          (make-values-type :optional (list type) :rest *universal-type*))))
523
524 (defun coerce-to-values (type)
525   (declare (type ctype type))
526   (cond ((or (eq type *universal-type*)
527              (eq type *wild-type*))
528          *wild-type*)
529         ((values-type-p type)
530          type)
531         (t (%coerce-to-values type))))
532
533 ;;; Return type, corresponding to ANSI short form of VALUES type
534 ;;; specifier.
535 (defun make-short-values-type (types)
536   (declare (list types))
537   (let ((last-required (position-if
538                         (lambda (type)
539                           (not/type (csubtypep (specifier-type 'null) type)))
540                         types
541                         :from-end t)))
542     (if last-required
543         (make-values-type :required (subseq types 0 (1+ last-required))
544                           :optional (subseq types (1+ last-required))
545                           :rest *universal-type*)
546         (make-values-type :optional types :rest *universal-type*))))
547
548 (defun make-single-value-type (type)
549   (make-values-type :required (list type)))
550
551 ;;; Do the specified OPERATION on TYPE1 and TYPE2, which may be any
552 ;;; type, including VALUES types. With VALUES types such as:
553 ;;;    (VALUES a0 a1)
554 ;;;    (VALUES b0 b1)
555 ;;; we compute the more useful result
556 ;;;    (VALUES (<operation> a0 b0) (<operation> a1 b1))
557 ;;; rather than the precise result
558 ;;;    (<operation> (values a0 a1) (values b0 b1))
559 ;;; This has the virtue of always keeping the VALUES type specifier
560 ;;; outermost, and retains all of the information that is really
561 ;;; useful for static type analysis. We want to know what is always
562 ;;; true of each value independently. It is worthless to know that if
563 ;;; the first value is B0 then the second will be B1.
564 ;;;
565 ;;; If the VALUES count signatures differ, then we produce a result with
566 ;;; the required VALUE count chosen by NREQ when applied to the number
567 ;;; of required values in TYPE1 and TYPE2. Any &KEY values become
568 ;;; &REST T (anyone who uses keyword values deserves to lose.)
569 ;;;
570 ;;; The second value is true if the result is definitely empty or if
571 ;;; OPERATION returned true as its second value each time we called
572 ;;; it. Since we approximate the intersection of VALUES types, the
573 ;;; second value being true doesn't mean the result is exact.
574 (defun args-type-op (type1 type2 operation nreq)
575   (declare (type ctype type1 type2)
576            (type function operation nreq))
577   (when (eq type1 type2)
578     (values type1 t))
579   (multiple-value-bind (types1 rest1)
580       (values-type-types type1)
581     (multiple-value-bind (types2 rest2)
582         (values-type-types type2)
583       (multiple-value-bind (rest rest-exact)
584           (funcall operation rest1 rest2)
585         (multiple-value-bind (res res-exact)
586             (if (< (length types1) (length types2))
587                 (fixed-values-op types2 types1 rest1 operation)
588                 (fixed-values-op types1 types2 rest2 operation))
589           (let* ((req (funcall nreq
590                                (length (args-type-required type1))
591                                (length (args-type-required type2))))
592                  (required (subseq res 0 req))
593                  (opt (subseq res req)))
594             (values required opt rest
595                     (and rest-exact res-exact))))))))
596
597 (defun values-type-op (type1 type2 operation nreq)
598   (multiple-value-bind (required optional rest exactp)
599       (args-type-op type1 type2 operation nreq)
600     (values (make-values-type :required required
601                               :optional optional
602                               :rest rest)
603             exactp)))
604
605 (defun type=-args (type1 type2)
606   (macrolet ((compare (comparator field)
607                (let ((reader (symbolicate '#:args-type- field)))
608                  `(,comparator (,reader type1) (,reader type2)))))
609     (and/type
610      (cond ((null (args-type-rest type1))
611             (values (null (args-type-rest type2)) t))
612            ((null (args-type-rest type2))
613             (values nil t))
614            (t
615             (compare type= rest)))
616      (and/type (and/type (compare type=-list required)
617                          (compare type=-list optional))
618                (if (or (args-type-keyp type1) (args-type-keyp type2))
619                    (values nil nil)
620                    (values t t))))))
621
622 ;;; Do a union or intersection operation on types that might be values
623 ;;; types. The result is optimized for utility rather than exactness,
624 ;;; but it is guaranteed that it will be no smaller (more restrictive)
625 ;;; than the precise result.
626 ;;;
627 ;;; The return convention seems to be analogous to
628 ;;; TYPES-EQUAL-OR-INTERSECT. -- WHN 19990910.
629 (defun-cached (values-type-union :hash-function type-cache-hash
630                                  :hash-bits 8
631                                  :default nil
632                                  :init-wrapper !cold-init-forms)
633     ((type1 eq) (type2 eq))
634   (declare (type ctype type1 type2))
635   (cond ((or (eq type1 *wild-type*) (eq type2 *wild-type*)) *wild-type*)
636         ((eq type1 *empty-type*) type2)
637         ((eq type2 *empty-type*) type1)
638         (t
639          (values (values-type-op type1 type2 #'type-union #'min)))))
640
641 (defun-cached (values-type-intersection :hash-function type-cache-hash
642                                         :hash-bits 8
643                                         :default (values nil)
644                                         :init-wrapper !cold-init-forms)
645     ((type1 eq) (type2 eq))
646   (declare (type ctype type1 type2))
647   (cond ((eq type1 *wild-type*)
648          (coerce-to-values type2))
649         ((or (eq type2 *wild-type*) (eq type2 *universal-type*))
650          type1)
651         ((or (eq type1 *empty-type*) (eq type2 *empty-type*))
652          *empty-type*)
653         ((and (not (values-type-p type2))
654               (values-type-required type1))
655          (let ((req1 (values-type-required type1)))
656            (make-values-type :required (cons (type-intersection (first req1) type2)
657                                              (rest req1))
658                              :optional (values-type-optional type1)
659                              :rest (values-type-rest type1)
660                              :allowp (values-type-allowp type1))))
661         (t
662          (values (values-type-op type1 (coerce-to-values type2)
663                                  #'type-intersection
664                                  #'max)))))
665
666 ;;; This is like TYPES-EQUAL-OR-INTERSECT, except that it sort of
667 ;;; works on VALUES types. Note that due to the semantics of
668 ;;; VALUES-TYPE-INTERSECTION, this might return (VALUES T T) when
669 ;;; there isn't really any intersection.
670 (defun values-types-equal-or-intersect (type1 type2)
671   (cond ((or (eq type1 *empty-type*) (eq type2 *empty-type*))
672          (values t t))
673         ((or (eq type1 *wild-type*) (eq type2 *wild-type*))
674          (values t t))
675         (t
676          (let ((res (values-type-intersection type1 type2)))
677            (values (not (eq res *empty-type*))
678                    t)))))
679
680 ;;; a SUBTYPEP-like operation that can be used on any types, including
681 ;;; VALUES types
682 (defun-cached (values-subtypep :hash-function type-cache-hash
683                                :hash-bits 8
684                                :values 2
685                                :default (values nil :empty)
686                                :init-wrapper !cold-init-forms)
687     ((type1 eq) (type2 eq))
688   (declare (type ctype type1 type2))
689   (cond ((or (eq type2 *wild-type*) (eq type2 *universal-type*)
690              (eq type1 *empty-type*))
691          (values t t))
692         ((eq type1 *wild-type*)
693          (values (eq type2 *wild-type*) t))
694         ((or (eq type2 *empty-type*)
695              (not (values-types-equal-or-intersect type1 type2)))
696          (values nil t))
697         ((and (not (values-type-p type2))
698               (values-type-required type1))
699          (csubtypep (first (values-type-required type1))
700                     type2))
701         (t (setq type2 (coerce-to-values type2))
702            (multiple-value-bind (types1 rest1) (values-type-types type1)
703              (multiple-value-bind (types2 rest2) (values-type-types type2)
704                (cond ((< (length (values-type-required type1))
705                          (length (values-type-required type2)))
706                       (values nil t))
707                      ((< (length types1) (length types2))
708                       (values nil nil))
709                      (t
710                       (do ((t1 types1 (rest t1))
711                            (t2 types2 (rest t2)))
712                           ((null t2)
713                            (csubtypep rest1 rest2))
714                         (multiple-value-bind (res win-p)
715                             (csubtypep (first t1) (first t2))
716                           (unless win-p
717                             (return (values nil nil)))
718                           (unless res
719                             (return (values nil t))))))))))))
720 \f
721 ;;;; type method interfaces
722
723 ;;; like SUBTYPEP, only works on CTYPE structures
724 (defun-cached (csubtypep :hash-function type-cache-hash
725                          :hash-bits 8
726                          :values 2
727                          :default (values nil :empty)
728                          :init-wrapper !cold-init-forms)
729               ((type1 eq) (type2 eq))
730   (declare (type ctype type1 type2))
731   (cond ((or (eq type1 type2)
732              (eq type1 *empty-type*)
733              (eq type2 *universal-type*))
734          (values t t))
735         #+nil
736         ((eq type1 *universal-type*)
737          (values nil t))
738         (t
739          (!invoke-type-method :simple-subtypep :complex-subtypep-arg2
740                               type1 type2
741                               :complex-arg1 :complex-subtypep-arg1))))
742
743 ;;; Just parse the type specifiers and call CSUBTYPE.
744 (defun sb!xc:subtypep (type1 type2 &optional environment)
745   #!+sb-doc
746   "Return two values indicating the relationship between type1 and type2.
747   If values are T and T, type1 definitely is a subtype of type2.
748   If values are NIL and T, type1 definitely is not a subtype of type2.
749   If values are NIL and NIL, it couldn't be determined."
750   (declare (ignore environment))
751   (csubtypep (specifier-type type1) (specifier-type type2)))
752
753 ;;; If two types are definitely equivalent, return true. The second
754 ;;; value indicates whether the first value is definitely correct.
755 ;;; This should only fail in the presence of HAIRY types.
756 (defun-cached (type= :hash-function type-cache-hash
757                      :hash-bits 8
758                      :values 2
759                      :default (values nil :empty)
760                      :init-wrapper !cold-init-forms)
761               ((type1 eq) (type2 eq))
762   (declare (type ctype type1 type2))
763   (if (eq type1 type2)
764       (values t t)
765       (!invoke-type-method :simple-= :complex-= type1 type2)))
766
767 ;;; Not exactly the negation of TYPE=, since when the relationship is
768 ;;; uncertain, we still return NIL, NIL. This is useful in cases where
769 ;;; the conservative assumption is =.
770 (defun type/= (type1 type2)
771   (declare (type ctype type1 type2))
772   (multiple-value-bind (res win) (type= type1 type2)
773     (if win
774         (values (not res) t)
775         (values nil nil))))
776
777 ;;; the type method dispatch case of TYPE-UNION2
778 (defun %type-union2 (type1 type2)
779   ;; As in %TYPE-INTERSECTION2, it seems to be a good idea to give
780   ;; both argument orders a chance at COMPLEX-INTERSECTION2. Unlike
781   ;; %TYPE-INTERSECTION2, though, I don't have a specific case which
782   ;; demonstrates this is actually necessary. Also unlike
783   ;; %TYPE-INTERSECTION2, there seems to be no need to distinguish
784   ;; between not finding a method and having a method return NIL.
785   (flet ((1way (x y)
786            (!invoke-type-method :simple-union2 :complex-union2
787                                 x y
788                                 :default nil)))
789     (declare (inline 1way))
790     (or (1way type1 type2)
791         (1way type2 type1))))
792
793 ;;; Find a type which includes both types. Any inexactness is
794 ;;; represented by the fuzzy element types; we return a single value
795 ;;; that is precise to the best of our knowledge. This result is
796 ;;; simplified into the canonical form, thus is not a UNION-TYPE
797 ;;; unless we find no other way to represent the result.
798 (defun-cached (type-union2 :hash-function type-cache-hash
799                            :hash-bits 8
800                            :init-wrapper !cold-init-forms)
801               ((type1 eq) (type2 eq))
802   ;; KLUDGE: This was generated from TYPE-INTERSECTION2 by Ye Olde Cut And
803   ;; Paste technique of programming. If it stays around (as opposed to
804   ;; e.g. fading away in favor of some CLOS solution) the shared logic
805   ;; should probably become shared code. -- WHN 2001-03-16
806   (declare (type ctype type1 type2))
807   (cond ((eq type1 type2)
808          type1)
809         ((csubtypep type1 type2) type2)
810         ((csubtypep type2 type1) type1)
811         ((or (union-type-p type1)
812              (union-type-p type2))
813          ;; Unions of UNION-TYPE should have the UNION-TYPE-TYPES
814          ;; values broken out and united separately. The full TYPE-UNION
815          ;; function knows how to do this, so let it handle it.
816          (type-union type1 type2))
817         (t
818          ;; the ordinary case: we dispatch to type methods
819          (%type-union2 type1 type2))))
820
821 ;;; the type method dispatch case of TYPE-INTERSECTION2
822 (defun %type-intersection2 (type1 type2)
823   ;; We want to give both argument orders a chance at
824   ;; COMPLEX-INTERSECTION2. Without that, the old CMU CL type
825   ;; methods could give noncommutative results, e.g.
826   ;;   (TYPE-INTERSECTION2 *EMPTY-TYPE* SOME-HAIRY-TYPE)
827   ;;     => NIL, NIL
828   ;;   (TYPE-INTERSECTION2 SOME-HAIRY-TYPE *EMPTY-TYPE*)
829   ;;     => #<NAMED-TYPE NIL>, T
830   ;; We also need to distinguish between the case where we found a
831   ;; type method, and it returned NIL, and the case where we fell
832   ;; through without finding any type method. An example of the first
833   ;; case is the intersection of a HAIRY-TYPE with some ordinary type.
834   ;; An example of the second case is the intersection of two
835   ;; completely-unrelated types, e.g. CONS and NUMBER, or SYMBOL and
836   ;; ARRAY.
837   ;;
838   ;; (Why yes, CLOS probably *would* be nicer..)
839   (flet ((1way (x y)
840            (!invoke-type-method :simple-intersection2 :complex-intersection2
841                                 x y
842                                 :default :call-other-method)))
843     (declare (inline 1way))
844     (let ((xy (1way type1 type2)))
845       (or (and (not (eql xy :call-other-method)) xy)
846           (let ((yx (1way type2 type1)))
847             (or (and (not (eql yx :call-other-method)) yx)
848                 (cond ((and (eql xy :call-other-method)
849                             (eql yx :call-other-method))
850                        *empty-type*)
851                       (t
852                        nil))))))))
853
854 (defun-cached (type-intersection2 :hash-function type-cache-hash
855                                   :hash-bits 8
856                                   :values 1
857                                   :default nil
858                                   :init-wrapper !cold-init-forms)
859               ((type1 eq) (type2 eq))
860   (declare (type ctype type1 type2))
861   (cond ((eq type1 type2)
862          ;; FIXME: For some reason, this doesn't catch e.g. type1 =
863          ;; type2 = (SPECIFIER-TYPE
864          ;; 'SOME-UNKNOWN-TYPE). Investigate. - CSR, 2002-04-10
865          type1)
866         ((or (intersection-type-p type1)
867              (intersection-type-p type2))
868          ;; Intersections of INTERSECTION-TYPE should have the
869          ;; INTERSECTION-TYPE-TYPES values broken out and intersected
870          ;; separately. The full TYPE-INTERSECTION function knows how
871          ;; to do that, so let it handle it.
872          (type-intersection type1 type2))
873         (t
874          ;; the ordinary case: we dispatch to type methods
875          (%type-intersection2 type1 type2))))
876
877 ;;; Return as restrictive and simple a type as we can discover that is
878 ;;; no more restrictive than the intersection of TYPE1 and TYPE2. At
879 ;;; worst, we arbitrarily return one of the arguments as the first
880 ;;; value (trying not to return a hairy type).
881 (defun type-approx-intersection2 (type1 type2)
882   (cond ((type-intersection2 type1 type2))
883         ((hairy-type-p type1) type2)
884         (t type1)))
885
886 ;;; a test useful for checking whether a derived type matches a
887 ;;; declared type
888 ;;;
889 ;;; The first value is true unless the types don't intersect and
890 ;;; aren't equal. The second value is true if the first value is
891 ;;; definitely correct. NIL is considered to intersect with any type.
892 ;;; If T is a subtype of either type, then we also return T, T. This
893 ;;; way we recognize that hairy types might intersect with T.
894 (defun types-equal-or-intersect (type1 type2)
895   (declare (type ctype type1 type2))
896   (if (or (eq type1 *empty-type*) (eq type2 *empty-type*))
897       (values t t)
898       (let ((intersection2 (type-intersection2 type1 type2)))
899         (cond ((not intersection2)
900                (if (or (csubtypep *universal-type* type1)
901                        (csubtypep *universal-type* type2))
902                    (values t t)
903                    (values t nil)))
904               ((eq intersection2 *empty-type*) (values nil t))
905               (t (values t t))))))
906
907 ;;; Return a Common Lisp type specifier corresponding to the TYPE
908 ;;; object.
909 (defun type-specifier (type)
910   (declare (type ctype type))
911   (funcall (type-class-unparse (type-class-info type)) type))
912
913 (defun-cached (type-negation :hash-function (lambda (type)
914                                               (logand (type-hash-value type)
915                                                       #xff))
916                              :hash-bits 8
917                              :values 1
918                              :default nil
919                              :init-wrapper !cold-init-forms)
920               ((type eq))
921   (declare (type ctype type))
922   (funcall (type-class-negate (type-class-info type)) type))
923
924 ;;; (VALUES-SPECIFIER-TYPE and SPECIFIER-TYPE moved from here to
925 ;;; early-type.lisp by WHN ca. 19990201.)
926
927 ;;; Take a list of type specifiers, computing the translation of each
928 ;;; specifier and defining it as a builtin type.
929 (declaim (ftype (function (list) (values)) precompute-types))
930 (defun precompute-types (specs)
931   (dolist (spec specs)
932     (let ((res (specifier-type spec)))
933       (unless (unknown-type-p res)
934         (setf (info :type :builtin spec) res)
935         ;; KLUDGE: the three copies of this idiom in this file (and
936         ;; the one in class.lisp as at sbcl-0.7.4.1x) should be
937         ;; coalesced, or perhaps the error-detecting code that
938         ;; disallows redefinition of :PRIMITIVE types should be
939         ;; rewritten to use *TYPE-SYSTEM-FINALIZED* (rather than
940         ;; *TYPE-SYSTEM-INITIALIZED*). The effect of this is not to
941         ;; cause redefinition errors when precompute-types is called
942         ;; for a second time while building the target compiler using
943         ;; the cross-compiler. -- CSR, trying to explain why this
944         ;; isn't completely wrong, 2002-06-07
945         (setf (info :type :kind spec) #+sb-xc-host :defined #-sb-xc-host :primitive))))
946   (values))
947 \f
948 ;;;; general TYPE-UNION and TYPE-INTERSECTION operations
949 ;;;;
950 ;;;; These are fully general operations on CTYPEs: they'll always
951 ;;;; return a CTYPE representing the result.
952
953 ;;; shared logic for unions and intersections: Return a list of
954 ;;; types representing the same types as INPUT-TYPES, but with
955 ;;; COMPOUND-TYPEs satisfying %COMPOUND-TYPE-P broken up into their
956 ;;; component types, and with any SIMPLY2 simplifications applied.
957 (macrolet
958     ((def (name compound-type-p simplify2)
959          `(defun ,name (types)
960             (when types
961               (multiple-value-bind (first rest)
962                   (if (,compound-type-p (car types))
963                       (values (car (compound-type-types (car types)))
964                               (append (cdr (compound-type-types (car types)))
965                                       (cdr types)))
966                       (values (car types) (cdr types)))
967                 (let ((rest (,name rest)) u)
968                   (dolist (r rest (cons first rest))
969                     (when (setq u (,simplify2 first r))
970                       (return (,name (nsubstitute u r rest)))))))))))
971   (def simplify-intersections intersection-type-p type-intersection2)
972   (def simplify-unions union-type-p type-union2))
973
974 (defun maybe-distribute-one-union (union-type types)
975   (let* ((intersection (apply #'type-intersection types))
976          (union (mapcar (lambda (x) (type-intersection x intersection))
977                         (union-type-types union-type))))
978     (if (notany (lambda (x) (or (hairy-type-p x)
979                                 (intersection-type-p x)))
980                 union)
981         union
982         nil)))
983
984 (defun type-intersection (&rest input-types)
985   (%type-intersection input-types))
986 (defun-cached (%type-intersection :hash-bits 8
987                                   :hash-function (lambda (x)
988                                                    (logand (sxhash x) #xff)))
989     ((input-types equal))
990   (let ((simplified-types (simplify-intersections input-types)))
991     (declare (type list simplified-types))
992     ;; We want to have a canonical representation of types (or failing
993     ;; that, punt to HAIRY-TYPE). Canonical representation would have
994     ;; intersections inside unions but not vice versa, since you can
995     ;; always achieve that by the distributive rule. But we don't want
996     ;; to just apply the distributive rule, since it would be too easy
997     ;; to end up with unreasonably huge type expressions. So instead
998     ;; we try to generate a simple type by distributing the union; if
999     ;; the type can't be made simple, we punt to HAIRY-TYPE.
1000     (if (and (cdr simplified-types) (some #'union-type-p simplified-types))
1001         (let* ((first-union (find-if #'union-type-p simplified-types))
1002                (other-types (coerce (remove first-union simplified-types)
1003                                     'list))
1004                (distributed (maybe-distribute-one-union first-union
1005                                                         other-types)))
1006           (if distributed
1007               (apply #'type-union distributed)
1008               (make-hairy-type
1009                :specifier `(and ,@(map 'list
1010                                        #'type-specifier
1011                                        simplified-types)))))
1012         (cond
1013           ((null simplified-types) *universal-type*)
1014           ((null (cdr simplified-types)) (car simplified-types))
1015           (t (%make-intersection-type
1016               (some #'type-enumerable simplified-types)
1017               simplified-types))))))
1018
1019 (defun type-union (&rest input-types)
1020   (%type-union input-types))
1021 (defun-cached (%type-union :hash-bits 8
1022                            :hash-function (lambda (x)
1023                                             (logand (sxhash x) #xff)))
1024     ((input-types equal))
1025   (let ((simplified-types (simplify-unions input-types)))
1026     (cond
1027       ((null simplified-types) *empty-type*)
1028       ((null (cdr simplified-types)) (car simplified-types))
1029       (t (make-union-type
1030           (every #'type-enumerable simplified-types)
1031           simplified-types)))))
1032 \f
1033 ;;;; built-in types
1034
1035 (!define-type-class named)
1036
1037 (!cold-init-forms
1038  (macrolet ((frob (name var)
1039               `(progn
1040                  (setq ,var (make-named-type :name ',name))
1041                  (setf (info :type :kind ',name)
1042                        #+sb-xc-host :defined #-sb-xc-host :primitive)
1043                  (setf (info :type :builtin ',name) ,var))))
1044    ;; KLUDGE: In ANSI, * isn't really the name of a type, it's just a
1045    ;; special symbol which can be stuck in some places where an
1046    ;; ordinary type can go, e.g. (ARRAY * 1) instead of (ARRAY T 1).
1047    ;; In SBCL it also used to denote universal VALUES type.
1048    (frob * *wild-type*)
1049    (frob nil *empty-type*)
1050    (frob t *universal-type*)
1051    ;; new in sbcl-0.9.5: these used to be CLASSOID types, but that
1052    ;; view of them was incompatible with requirements on the MOP
1053    ;; metaobject class hierarchy: the INSTANCE and
1054    ;; FUNCALLABLE-INSTANCE types are disjoint (instances have
1055    ;; instance-pointer-lowtag; funcallable-instances have
1056    ;; fun-pointer-lowtag), while FUNCALLABLE-STANDARD-OBJECT is
1057    ;; required to be a subclass of STANDARD-OBJECT.  -- CSR,
1058    ;; 2005-09-09
1059    (frob instance *instance-type*)
1060    (frob funcallable-instance *funcallable-instance-type*))
1061  (setf *universal-fun-type*
1062        (make-fun-type :wild-args t
1063                       :returns *wild-type*)))
1064
1065 (!define-type-method (named :simple-=) (type1 type2)
1066   ;;(aver (not (eq type1 *wild-type*))) ; * isn't really a type.
1067   (values (eq type1 type2) t))
1068
1069 (defun cons-type-might-be-empty-type (type)
1070   (declare (type cons-type type))
1071   (let ((car-type (cons-type-car-type type))
1072         (cdr-type (cons-type-cdr-type type)))
1073     (or
1074      (if (cons-type-p car-type)
1075          (cons-type-might-be-empty-type car-type)
1076          (multiple-value-bind (yes surep)
1077              (type= car-type *empty-type*)
1078            (aver (not yes))
1079            (not surep)))
1080      (if (cons-type-p cdr-type)
1081          (cons-type-might-be-empty-type cdr-type)
1082          (multiple-value-bind (yes surep)
1083              (type= cdr-type *empty-type*)
1084            (aver (not yes))
1085            (not surep))))))
1086
1087 (!define-type-method (named :complex-=) (type1 type2)
1088   (cond
1089     ((and (eq type2 *empty-type*)
1090           (or (and (intersection-type-p type1)
1091                    ;; not allowed to be unsure on these... FIXME: keep
1092                    ;; the list of CL types that are intersection types
1093                    ;; once and only once.
1094                    (not (or (type= type1 (specifier-type 'ratio))
1095                             (type= type1 (specifier-type 'keyword)))))
1096               (and (cons-type-p type1)
1097                    (cons-type-might-be-empty-type type1))))
1098      ;; things like (AND (EQL 0) (SATISFIES ODDP)) or (AND FUNCTION
1099      ;; STREAM) can get here.  In general, we can't really tell
1100      ;; whether these are equal to NIL or not, so
1101      (values nil nil))
1102     ((type-might-contain-other-types-p type1)
1103      (invoke-complex-=-other-method type1 type2))
1104     (t (values nil t))))
1105
1106 (!define-type-method (named :simple-subtypep) (type1 type2)
1107   (aver (not (eq type1 *wild-type*))) ; * isn't really a type.
1108   (aver (not (eq type1 type2)))
1109   (values (or (eq type1 *empty-type*)
1110               (eq type2 *wild-type*)
1111               (eq type2 *universal-type*)) t))
1112
1113 (!define-type-method (named :complex-subtypep-arg1) (type1 type2)
1114   ;; This AVER causes problems if we write accurate methods for the
1115   ;; union (and possibly intersection) types which then delegate to
1116   ;; us; while a user shouldn't get here, because of the odd status of
1117   ;; *wild-type* a type-intersection executed by the compiler can. -
1118   ;; CSR, 2002-04-10
1119   ;;
1120   ;; (aver (not (eq type1 *wild-type*))) ; * isn't really a type.
1121   (cond ((eq type1 *empty-type*)
1122          t)
1123         (;; When TYPE2 might be the universal type in disguise
1124          (type-might-contain-other-types-p type2)
1125          ;; Now that the UNION and HAIRY COMPLEX-SUBTYPEP-ARG2 methods
1126          ;; can delegate to us (more or less as CALL-NEXT-METHOD) when
1127          ;; they're uncertain, we can't just barf on COMPOUND-TYPE and
1128          ;; HAIRY-TYPEs as we used to. Instead we deal with the
1129          ;; problem (where at least part of the problem is cases like
1130          ;;   (SUBTYPEP T '(SATISFIES FOO))
1131          ;; or
1132          ;;   (SUBTYPEP T '(AND (SATISFIES FOO) (SATISFIES BAR)))
1133          ;; where the second type is a hairy type like SATISFIES, or
1134          ;; is a compound type which might contain a hairy type) by
1135          ;; returning uncertainty.
1136          (values nil nil))
1137         ((eq type1 *funcallable-instance-type*)
1138          (values (eq type2 (specifier-type 'function)) t))
1139         (t
1140          ;; This case would have been picked off by the SIMPLE-SUBTYPEP
1141          ;; method, and so shouldn't appear here.
1142          (aver (not (named-type-p type2)))
1143          ;; Since TYPE2 is not EQ *UNIVERSAL-TYPE* and is not another
1144          ;; named type in disguise, TYPE2 is not a superset of TYPE1.
1145          (values nil t))))
1146
1147 (!define-type-method (named :complex-subtypep-arg2) (type1 type2)
1148   (aver (not (eq type2 *wild-type*))) ; * isn't really a type.
1149   (cond ((eq type2 *universal-type*)
1150          (values t t))
1151         ((or (type-might-contain-other-types-p type1)
1152              ;; some CONS types can conceal danger
1153              (and (cons-type-p type1)
1154                   (cons-type-might-be-empty-type type1)))
1155          ;; those types can be other types in disguise.  So we'd
1156          ;; better delegate.
1157          (invoke-complex-subtypep-arg1-method type1 type2))
1158         ((and (eq type2 *instance-type*) (classoid-p type1))
1159          (if (member type1 *non-instance-classoid-types* :key #'find-classoid)
1160              (values nil t)
1161              (let* ((layout (classoid-layout type1))
1162                     (inherits (layout-inherits layout))
1163                     (functionp (find (classoid-layout (find-classoid 'function))
1164                                      inherits)))
1165                (cond
1166                  (functionp
1167                   (values nil t))
1168                  ((eq type1 (find-classoid 'function))
1169                   (values nil t))
1170                  ((or (basic-structure-classoid-p type1)
1171                       #+nil
1172                       (condition-classoid-p type1))
1173                   (values t t))
1174                  (t (values nil nil))))))
1175         ((and (eq type2 *funcallable-instance-type*) (classoid-p type1))
1176          (if (member type1 *non-instance-classoid-types* :key #'find-classoid)
1177              (values nil t)
1178              (let* ((layout (classoid-layout type1))
1179                     (inherits (layout-inherits layout))
1180                     (functionp (find (classoid-layout (find-classoid 'function))
1181                                      inherits)))
1182                (values (if functionp t nil) t))))
1183         (t
1184          ;; FIXME: This seems to rely on there only being 4 or 5
1185          ;; NAMED-TYPE values, and the exclusion of various
1186          ;; possibilities above. It would be good to explain it and/or
1187          ;; rewrite it so that it's clearer.
1188          (values nil t))))
1189
1190 (!define-type-method (named :complex-intersection2) (type1 type2)
1191   ;; FIXME: This assertion failed when I added it in sbcl-0.6.11.13.
1192   ;; Perhaps when bug 85 is fixed it can be reenabled.
1193   ;;(aver (not (eq type2 *wild-type*))) ; * isn't really a type.
1194   (cond
1195     ((eq type2 *instance-type*)
1196      (if (classoid-p type1)
1197          (if (and (not (member type1 *non-instance-classoid-types*
1198                                :key #'find-classoid))
1199                   (not (find (classoid-layout (find-classoid 'function))
1200                              (layout-inherits (classoid-layout type1)))))
1201              type1
1202              *empty-type*)
1203          (if (type-might-contain-other-types-p type1)
1204              nil
1205              *empty-type*)))
1206     ((eq type2 *funcallable-instance-type*)
1207      (if (classoid-p type1)
1208          (if (and (not (member type1 *non-instance-classoid-types*
1209                                :key #'find-classoid))
1210                   (find (classoid-layout (find-classoid 'function))
1211                         (layout-inherits (classoid-layout type1))))
1212              type1
1213              (if (type= type1 (find-classoid 'function))
1214                  type1
1215                  nil))
1216          (if (fun-type-p type1)
1217              nil
1218              (if (type-might-contain-other-types-p type1)
1219                  nil
1220                  *empty-type*))))
1221     (t (hierarchical-intersection2 type1 type2))))
1222
1223 (!define-type-method (named :complex-union2) (type1 type2)
1224   ;; Perhaps when bug 85 is fixed this can be reenabled.
1225   ;;(aver (not (eq type2 *wild-type*))) ; * isn't really a type.
1226   (cond
1227     ((eq type2 *instance-type*)
1228      (if (classoid-p type1)
1229          (if (or (member type1 *non-instance-classoid-types*
1230                          :key #'find-classoid)
1231                  (find (classoid-layout (find-classoid 'function))
1232                        (layout-inherits (classoid-layout type1))))
1233              nil
1234              type2)
1235          nil))
1236     ((eq type2 *funcallable-instance-type*)
1237      (if (classoid-p type1)
1238          (if (or (member type1 *non-instance-classoid-types*
1239                          :key #'find-classoid)
1240                  (not (find (classoid-layout (find-classoid 'function))
1241                             (layout-inherits (classoid-layout type1)))))
1242              nil
1243              (if (eq type1 (specifier-type 'function))
1244                  type1
1245                  type2))
1246          nil))
1247     (t (hierarchical-union2 type1 type2))))
1248
1249 (!define-type-method (named :negate) (x)
1250   (aver (not (eq x *wild-type*)))
1251   (cond
1252     ((eq x *universal-type*) *empty-type*)
1253     ((eq x *empty-type*) *universal-type*)
1254     ((or (eq x *instance-type*)
1255          (eq x *funcallable-instance-type*))
1256      (make-negation-type :type x))
1257     (t (bug "NAMED type unexpected: ~S" x))))
1258
1259 (!define-type-method (named :unparse) (x)
1260   (named-type-name x))
1261 \f
1262 ;;;; hairy and unknown types
1263
1264 (!define-type-method (hairy :negate) (x)
1265   (make-negation-type :type x))
1266
1267 (!define-type-method (hairy :unparse) (x)
1268   (hairy-type-specifier x))
1269
1270 (!define-type-method (hairy :simple-subtypep) (type1 type2)
1271   (let ((hairy-spec1 (hairy-type-specifier type1))
1272         (hairy-spec2 (hairy-type-specifier type2)))
1273     (cond ((equal-but-no-car-recursion hairy-spec1 hairy-spec2)
1274            (values t t))
1275           (t
1276            (values nil nil)))))
1277
1278 (!define-type-method (hairy :complex-subtypep-arg2) (type1 type2)
1279   (invoke-complex-subtypep-arg1-method type1 type2))
1280
1281 (!define-type-method (hairy :complex-subtypep-arg1) (type1 type2)
1282   (declare (ignore type1 type2))
1283   (values nil nil))
1284
1285 (!define-type-method (hairy :complex-=) (type1 type2)
1286   (if (and (unknown-type-p type2)
1287            (let* ((specifier2 (unknown-type-specifier type2))
1288                   (name2 (if (consp specifier2)
1289                              (car specifier2)
1290                              specifier2)))
1291              (info :type :kind name2)))
1292       (let ((type2 (specifier-type (unknown-type-specifier type2))))
1293         (if (unknown-type-p type2)
1294             (values nil nil)
1295             (type= type1 type2)))
1296   (values nil nil)))
1297
1298 (!define-type-method (hairy :simple-intersection2 :complex-intersection2)
1299                      (type1 type2)
1300   (if (type= type1 type2)
1301       type1
1302       nil))
1303
1304 (!define-type-method (hairy :simple-union2)
1305                      (type1 type2)
1306   (if (type= type1 type2)
1307       type1
1308       nil))
1309
1310 (!define-type-method (hairy :simple-=) (type1 type2)
1311   (if (equal-but-no-car-recursion (hairy-type-specifier type1)
1312                                   (hairy-type-specifier type2))
1313       (values t t)
1314       (values nil nil)))
1315
1316 (!def-type-translator satisfies (&whole whole fun)
1317   (declare (ignore fun))
1318   ;; Check legality of arguments.
1319   (destructuring-bind (satisfies predicate-name) whole
1320     (declare (ignore satisfies))
1321     (unless (symbolp predicate-name)
1322       (error 'simple-type-error
1323              :datum predicate-name
1324              :expected-type 'symbol
1325              :format-control "The SATISFIES predicate name is not a symbol: ~S"
1326              :format-arguments (list predicate-name))))
1327   ;; Create object.
1328   (make-hairy-type :specifier whole))
1329 \f
1330 ;;;; negation types
1331
1332 (!define-type-method (negation :negate) (x)
1333   (negation-type-type x))
1334
1335 (!define-type-method (negation :unparse) (x)
1336   (if (type= (negation-type-type x) (specifier-type 'cons))
1337       'atom
1338       `(not ,(type-specifier (negation-type-type x)))))
1339
1340 (!define-type-method (negation :simple-subtypep) (type1 type2)
1341   (csubtypep (negation-type-type type2) (negation-type-type type1)))
1342
1343 (!define-type-method (negation :complex-subtypep-arg2) (type1 type2)
1344   (let* ((complement-type2 (negation-type-type type2))
1345          (intersection2 (type-intersection2 type1
1346                                             complement-type2)))
1347     (if intersection2
1348         ;; FIXME: if uncertain, maybe try arg1?
1349         (type= intersection2 *empty-type*)
1350         (invoke-complex-subtypep-arg1-method type1 type2))))
1351
1352 (!define-type-method (negation :complex-subtypep-arg1) (type1 type2)
1353   ;; "Incrementally extended heuristic algorithms tend inexorably toward the
1354   ;; incomprehensible." -- http://www.unlambda.com/~james/lambda/lambda.txt
1355   ;;
1356   ;; You may not believe this. I couldn't either. But then I sat down
1357   ;; and drew lots of Venn diagrams. Comments involving a and b refer
1358   ;; to the call (subtypep '(not a) 'b) -- CSR, 2002-02-27.
1359   (block nil
1360     ;; (Several logical truths in this block are true as long as
1361     ;; b/=T. As of sbcl-0.7.1.28, it seems impossible to construct a
1362     ;; case with b=T where we actually reach this type method, but
1363     ;; we'll test for and exclude this case anyway, since future
1364     ;; maintenance might make it possible for it to end up in this
1365     ;; code.)
1366     (multiple-value-bind (equal certain)
1367         (type= type2 *universal-type*)
1368       (unless certain
1369         (return (values nil nil)))
1370       (when equal
1371         (return (values t t))))
1372     (let ((complement-type1 (negation-type-type type1)))
1373       ;; Do the special cases first, in order to give us a chance if
1374       ;; subtype/supertype relationships are hairy.
1375       (multiple-value-bind (equal certain)
1376           (type= complement-type1 type2)
1377         ;; If a = b, ~a is not a subtype of b (unless b=T, which was
1378         ;; excluded above).
1379         (unless certain
1380           (return (values nil nil)))
1381         (when equal
1382           (return (values nil t))))
1383       ;; KLUDGE: ANSI requires that the SUBTYPEP result between any
1384       ;; two built-in atomic type specifiers never be uncertain. This
1385       ;; is hard to do cleanly for the built-in types whose
1386       ;; definitions include (NOT FOO), i.e. CONS and RATIO. However,
1387       ;; we can do it with this hack, which uses our global knowledge
1388       ;; that our implementation of the type system uses disjoint
1389       ;; implementation types to represent disjoint sets (except when
1390       ;; types are contained in other types).  (This is a KLUDGE
1391       ;; because it's fragile. Various changes in internal
1392       ;; representation in the type system could make it start
1393       ;; confidently returning incorrect results.) -- WHN 2002-03-08
1394       (unless (or (type-might-contain-other-types-p complement-type1)
1395                   (type-might-contain-other-types-p type2))
1396         ;; Because of the way our types which don't contain other
1397         ;; types are disjoint subsets of the space of possible values,
1398         ;; (SUBTYPEP '(NOT AA) 'B)=NIL when AA and B are simple (and B
1399         ;; is not T, as checked above).
1400         (return (values nil t)))
1401       ;; The old (TYPE= TYPE1 TYPE2) branch would never be taken, as
1402       ;; TYPE1 and TYPE2 will only be equal if they're both NOT types,
1403       ;; and then the :SIMPLE-SUBTYPEP method would be used instead.
1404       ;; But a CSUBTYPEP relationship might still hold:
1405       (multiple-value-bind (equal certain)
1406           (csubtypep complement-type1 type2)
1407         ;; If a is a subtype of b, ~a is not a subtype of b (unless
1408         ;; b=T, which was excluded above).
1409         (unless certain
1410           (return (values nil nil)))
1411         (when equal
1412           (return (values nil t))))
1413       (multiple-value-bind (equal certain)
1414           (csubtypep type2 complement-type1)
1415         ;; If b is a subtype of a, ~a is not a subtype of b.  (FIXME:
1416         ;; That's not true if a=T. Do we know at this point that a is
1417         ;; not T?)
1418         (unless certain
1419           (return (values nil nil)))
1420         (when equal
1421           (return (values nil t))))
1422       ;; old CSR comment ca. 0.7.2, now obsoleted by the SIMPLE-CTYPE?
1423       ;; KLUDGE case above: Other cases here would rely on being able
1424       ;; to catch all possible cases, which the fragility of this type
1425       ;; system doesn't inspire me; for instance, if a is type= to ~b,
1426       ;; then we want T, T; if this is not the case and the types are
1427       ;; disjoint (have an intersection of *empty-type*) then we want
1428       ;; NIL, T; else if the union of a and b is the *universal-type*
1429       ;; then we want T, T. So currently we still claim to be unsure
1430       ;; about e.g. (subtypep '(not fixnum) 'single-float).
1431       ;;
1432       ;; OTOH we might still get here:
1433       (values nil nil))))
1434
1435 (!define-type-method (negation :complex-=) (type1 type2)
1436   ;; (NOT FOO) isn't equivalent to anything that's not a negation
1437   ;; type, except possibly a type that might contain it in disguise.
1438   (declare (ignore type2))
1439   (if (type-might-contain-other-types-p type1)
1440       (values nil nil)
1441       (values nil t)))
1442
1443 (!define-type-method (negation :simple-intersection2) (type1 type2)
1444   (let ((not1 (negation-type-type type1))
1445         (not2 (negation-type-type type2)))
1446     (cond
1447       ((csubtypep not1 not2) type2)
1448       ((csubtypep not2 not1) type1)
1449       ;; Why no analagous clause to the disjoint in the SIMPLE-UNION2
1450       ;; method, below?  The clause would read
1451       ;;
1452       ;; ((EQ (TYPE-UNION NOT1 NOT2) *UNIVERSAL-TYPE*) *EMPTY-TYPE*)
1453       ;;
1454       ;; but with proper canonicalization of negation types, there's
1455       ;; no way of constructing two negation types with union of their
1456       ;; negations being the universal type.
1457       (t
1458        (aver (not (eq (type-union not1 not2) *universal-type*)))
1459        nil))))
1460
1461 (!define-type-method (negation :complex-intersection2) (type1 type2)
1462   (cond
1463     ((csubtypep type1 (negation-type-type type2)) *empty-type*)
1464     ((eq (type-intersection type1 (negation-type-type type2)) *empty-type*)
1465      type1)
1466     (t nil)))
1467
1468 (!define-type-method (negation :simple-union2) (type1 type2)
1469   (let ((not1 (negation-type-type type1))
1470         (not2 (negation-type-type type2)))
1471     (cond
1472       ((csubtypep not1 not2) type1)
1473       ((csubtypep not2 not1) type2)
1474       ((eq (type-intersection not1 not2) *empty-type*)
1475        *universal-type*)
1476       (t nil))))
1477
1478 (!define-type-method (negation :complex-union2) (type1 type2)
1479   (cond
1480     ((csubtypep (negation-type-type type2) type1) *universal-type*)
1481     ((eq (type-intersection type1 (negation-type-type type2)) *empty-type*)
1482      type2)
1483     (t nil)))
1484
1485 (!define-type-method (negation :simple-=) (type1 type2)
1486   (type= (negation-type-type type1) (negation-type-type type2)))
1487
1488 (!def-type-translator not (typespec)
1489   (type-negation (specifier-type typespec)))
1490 \f
1491 ;;;; numeric types
1492
1493 (!define-type-class number)
1494
1495 (declaim (inline numeric-type-equal))
1496 (defun numeric-type-equal (type1 type2)
1497   (and (eq (numeric-type-class type1) (numeric-type-class type2))
1498        (eq (numeric-type-format type1) (numeric-type-format type2))
1499        (eq (numeric-type-complexp type1) (numeric-type-complexp type2))))
1500
1501 (!define-type-method (number :simple-=) (type1 type2)
1502   (values
1503    (and (numeric-type-equal type1 type2)
1504         (equalp (numeric-type-low type1) (numeric-type-low type2))
1505         (equalp (numeric-type-high type1) (numeric-type-high type2)))
1506    t))
1507
1508 (!define-type-method (number :negate) (type)
1509   (if (and (null (numeric-type-low type)) (null (numeric-type-high type)))
1510       (make-negation-type :type type)
1511       (type-union
1512        (make-negation-type
1513         :type (modified-numeric-type type :low nil :high nil))
1514        (cond
1515          ((null (numeric-type-low type))
1516           (modified-numeric-type
1517            type
1518            :low (let ((h (numeric-type-high type)))
1519                   (if (consp h) (car h) (list h)))
1520            :high nil))
1521          ((null (numeric-type-high type))
1522           (modified-numeric-type
1523            type
1524            :low nil
1525            :high (let ((l (numeric-type-low type)))
1526                    (if (consp l) (car l) (list l)))))
1527          (t (type-union
1528              (modified-numeric-type
1529               type
1530               :low nil
1531               :high (let ((l (numeric-type-low type)))
1532                       (if (consp l) (car l) (list l))))
1533              (modified-numeric-type
1534               type
1535               :low (let ((h (numeric-type-high type)))
1536                      (if (consp h) (car h) (list h)))
1537               :high nil)))))))
1538
1539 (!define-type-method (number :unparse) (type)
1540   (let* ((complexp (numeric-type-complexp type))
1541          (low (numeric-type-low type))
1542          (high (numeric-type-high type))
1543          (base (case (numeric-type-class type)
1544                  (integer 'integer)
1545                  (rational 'rational)
1546                  (float (or (numeric-type-format type) 'float))
1547                  (t 'real))))
1548     (let ((base+bounds
1549            (cond ((and (eq base 'integer) high low)
1550                   (let ((high-count (logcount high))
1551                         (high-length (integer-length high)))
1552                     (cond ((= low 0)
1553                            (cond ((= high 0) '(integer 0 0))
1554                                  ((= high 1) 'bit)
1555                                  ((and (= high-count high-length)
1556                                        (plusp high-length))
1557                                   `(unsigned-byte ,high-length))
1558                                  (t
1559                                   `(mod ,(1+ high)))))
1560                           ((and (= low sb!xc:most-negative-fixnum)
1561                                 (= high sb!xc:most-positive-fixnum))
1562                            'fixnum)
1563                           ((and (= low (lognot high))
1564                                 (= high-count high-length)
1565                                 (> high-count 0))
1566                            `(signed-byte ,(1+ high-length)))
1567                           (t
1568                            `(integer ,low ,high)))))
1569                  (high `(,base ,(or low '*) ,high))
1570                  (low
1571                   (if (and (eq base 'integer) (= low 0))
1572                       'unsigned-byte
1573                       `(,base ,low)))
1574                  (t base))))
1575       (ecase complexp
1576         (:real
1577          base+bounds)
1578         (:complex
1579          (aver (neq base+bounds 'real))
1580          `(complex ,base+bounds))
1581         ((nil)
1582          (aver (eq base+bounds 'real))
1583          'number)))))
1584
1585 ;;; Return true if X is "less than or equal" to Y, taking open bounds
1586 ;;; into consideration. CLOSED is the predicate used to test the bound
1587 ;;; on a closed interval (e.g. <=), and OPEN is the predicate used on
1588 ;;; open bounds (e.g. <). Y is considered to be the outside bound, in
1589 ;;; the sense that if it is infinite (NIL), then the test succeeds,
1590 ;;; whereas if X is infinite, then the test fails (unless Y is also
1591 ;;; infinite).
1592 ;;;
1593 ;;; This is for comparing bounds of the same kind, e.g. upper and
1594 ;;; upper. Use NUMERIC-BOUND-TEST* for different kinds of bounds.
1595 (defmacro numeric-bound-test (x y closed open)
1596   `(cond ((not ,y) t)
1597          ((not ,x) nil)
1598          ((consp ,x)
1599           (if (consp ,y)
1600               (,closed (car ,x) (car ,y))
1601               (,closed (car ,x) ,y)))
1602          (t
1603           (if (consp ,y)
1604               (,open ,x (car ,y))
1605               (,closed ,x ,y)))))
1606
1607 ;;; This is used to compare upper and lower bounds. This is different
1608 ;;; from the same-bound case:
1609 ;;; -- Since X = NIL is -infinity, whereas y = NIL is +infinity, we
1610 ;;;    return true if *either* arg is NIL.
1611 ;;; -- an open inner bound is "greater" and also squeezes the interval,
1612 ;;;    causing us to use the OPEN test for those cases as well.
1613 (defmacro numeric-bound-test* (x y closed open)
1614   `(cond ((not ,y) t)
1615          ((not ,x) t)
1616          ((consp ,x)
1617           (if (consp ,y)
1618               (,open (car ,x) (car ,y))
1619               (,open (car ,x) ,y)))
1620          (t
1621           (if (consp ,y)
1622               (,open ,x (car ,y))
1623               (,closed ,x ,y)))))
1624
1625 ;;; Return whichever of the numeric bounds X and Y is "maximal"
1626 ;;; according to the predicates CLOSED (e.g. >=) and OPEN (e.g. >).
1627 ;;; This is only meaningful for maximizing like bounds, i.e. upper and
1628 ;;; upper. If MAX-P is true, then we return NIL if X or Y is NIL,
1629 ;;; otherwise we return the other arg.
1630 (defmacro numeric-bound-max (x y closed open max-p)
1631   (once-only ((n-x x)
1632               (n-y y))
1633     `(cond ((not ,n-x) ,(if max-p nil n-y))
1634            ((not ,n-y) ,(if max-p nil n-x))
1635            ((consp ,n-x)
1636             (if (consp ,n-y)
1637                 (if (,closed (car ,n-x) (car ,n-y)) ,n-x ,n-y)
1638                 (if (,open (car ,n-x) ,n-y) ,n-x ,n-y)))
1639            (t
1640             (if (consp ,n-y)
1641                 (if (,open (car ,n-y) ,n-x) ,n-y ,n-x)
1642                 (if (,closed ,n-y ,n-x) ,n-y ,n-x))))))
1643
1644 (!define-type-method (number :simple-subtypep) (type1 type2)
1645   (let ((class1 (numeric-type-class type1))
1646         (class2 (numeric-type-class type2))
1647         (complexp2 (numeric-type-complexp type2))
1648         (format2 (numeric-type-format type2))
1649         (low1 (numeric-type-low type1))
1650         (high1 (numeric-type-high type1))
1651         (low2 (numeric-type-low type2))
1652         (high2 (numeric-type-high type2)))
1653     ;; If one is complex and the other isn't, they are disjoint.
1654     (cond ((not (or (eq (numeric-type-complexp type1) complexp2)
1655                     (null complexp2)))
1656            (values nil t))
1657           ;; If the classes are specified and different, the types are
1658           ;; disjoint unless type2 is RATIONAL and type1 is INTEGER.
1659           ;; [ or type1 is INTEGER and type2 is of the form (RATIONAL
1660           ;; X X) for integral X, but this is dealt with in the
1661           ;; canonicalization inside MAKE-NUMERIC-TYPE ]
1662           ((not (or (eq class1 class2)
1663                     (null class2)
1664                     (and (eq class1 'integer) (eq class2 'rational))))
1665            (values nil t))
1666           ;; If the float formats are specified and different, the types
1667           ;; are disjoint.
1668           ((not (or (eq (numeric-type-format type1) format2)
1669                     (null format2)))
1670            (values nil t))
1671           ;; Check the bounds.
1672           ((and (numeric-bound-test low1 low2 >= >)
1673                 (numeric-bound-test high1 high2 <= <))
1674            (values t t))
1675           (t
1676            (values nil t)))))
1677
1678 (!define-superclasses number ((number)) !cold-init-forms)
1679
1680 ;;; If the high bound of LOW is adjacent to the low bound of HIGH,
1681 ;;; then return true, otherwise NIL.
1682 (defun numeric-types-adjacent (low high)
1683   (let ((low-bound (numeric-type-high low))
1684         (high-bound (numeric-type-low high)))
1685     (cond ((not (and low-bound high-bound)) nil)
1686           ((and (consp low-bound) (consp high-bound)) nil)
1687           ((consp low-bound)
1688            (let ((low-value (car low-bound)))
1689              (or (eql low-value high-bound)
1690                  (and (eql low-value
1691                            (load-time-value (make-unportable-float
1692                                              :single-float-negative-zero)))
1693                       (eql high-bound 0f0))
1694                  (and (eql low-value 0f0)
1695                       (eql high-bound
1696                            (load-time-value (make-unportable-float
1697                                              :single-float-negative-zero))))
1698                  (and (eql low-value
1699                            (load-time-value (make-unportable-float
1700                                              :double-float-negative-zero)))
1701                       (eql high-bound 0d0))
1702                  (and (eql low-value 0d0)
1703                       (eql high-bound
1704                            (load-time-value (make-unportable-float
1705                                              :double-float-negative-zero)))))))
1706           ((consp high-bound)
1707            (let ((high-value (car high-bound)))
1708              (or (eql high-value low-bound)
1709                  (and (eql high-value
1710                            (load-time-value (make-unportable-float
1711                                              :single-float-negative-zero)))
1712                       (eql low-bound 0f0))
1713                  (and (eql high-value 0f0)
1714                       (eql low-bound
1715                            (load-time-value (make-unportable-float
1716                                              :single-float-negative-zero))))
1717                  (and (eql high-value
1718                            (load-time-value (make-unportable-float
1719                                              :double-float-negative-zero)))
1720                       (eql low-bound 0d0))
1721                  (and (eql high-value 0d0)
1722                       (eql low-bound
1723                            (load-time-value (make-unportable-float
1724                                              :double-float-negative-zero)))))))
1725           ((and (eq (numeric-type-class low) 'integer)
1726                 (eq (numeric-type-class high) 'integer))
1727            (eql (1+ low-bound) high-bound))
1728           (t
1729            nil))))
1730
1731 ;;; Return a numeric type that is a supertype for both TYPE1 and TYPE2.
1732 ;;;
1733 ;;; Old comment, probably no longer applicable:
1734 ;;;
1735 ;;;   ### Note: we give up early to keep from dropping lots of
1736 ;;;   information on the floor by returning overly general types.
1737 (!define-type-method (number :simple-union2) (type1 type2)
1738   (declare (type numeric-type type1 type2))
1739   (cond ((csubtypep type1 type2) type2)
1740         ((csubtypep type2 type1) type1)
1741         (t
1742          (let ((class1 (numeric-type-class type1))
1743                (format1 (numeric-type-format type1))
1744                (complexp1 (numeric-type-complexp type1))
1745                (class2 (numeric-type-class type2))
1746                (format2 (numeric-type-format type2))
1747                (complexp2 (numeric-type-complexp type2)))
1748            (cond
1749              ((and (eq class1 class2)
1750                    (eq format1 format2)
1751                    (eq complexp1 complexp2)
1752                    (or (numeric-types-intersect type1 type2)
1753                        (numeric-types-adjacent type1 type2)
1754                        (numeric-types-adjacent type2 type1)))
1755               (make-numeric-type
1756                :class class1
1757                :format format1
1758                :complexp complexp1
1759                :low (numeric-bound-max (numeric-type-low type1)
1760                                        (numeric-type-low type2)
1761                                        <= < t)
1762                :high (numeric-bound-max (numeric-type-high type1)
1763                                         (numeric-type-high type2)
1764                                         >= > t)))
1765              ;; FIXME: These two clauses are almost identical, and the
1766              ;; consequents are in fact identical in every respect.
1767              ((and (eq class1 'rational)
1768                    (eq class2 'integer)
1769                    (eq format1 format2)
1770                    (eq complexp1 complexp2)
1771                    (integerp (numeric-type-low type2))
1772                    (integerp (numeric-type-high type2))
1773                    (= (numeric-type-low type2) (numeric-type-high type2))
1774                    (or (numeric-types-adjacent type1 type2)
1775                        (numeric-types-adjacent type2 type1)))
1776               (make-numeric-type
1777                :class 'rational
1778                :format format1
1779                :complexp complexp1
1780                :low (numeric-bound-max (numeric-type-low type1)
1781                                        (numeric-type-low type2)
1782                                        <= < t)
1783                :high (numeric-bound-max (numeric-type-high type1)
1784                                         (numeric-type-high type2)
1785                                         >= > t)))
1786              ((and (eq class1 'integer)
1787                    (eq class2 'rational)
1788                    (eq format1 format2)
1789                    (eq complexp1 complexp2)
1790                    (integerp (numeric-type-low type1))
1791                    (integerp (numeric-type-high type1))
1792                    (= (numeric-type-low type1) (numeric-type-high type1))
1793                    (or (numeric-types-adjacent type1 type2)
1794                        (numeric-types-adjacent type2 type1)))
1795               (make-numeric-type
1796                :class 'rational
1797                :format format1
1798                :complexp complexp1
1799                :low (numeric-bound-max (numeric-type-low type1)
1800                                        (numeric-type-low type2)
1801                                        <= < t)
1802                :high (numeric-bound-max (numeric-type-high type1)
1803                                         (numeric-type-high type2)
1804                                         >= > t)))
1805              (t nil))))))
1806
1807
1808 (!cold-init-forms
1809   (setf (info :type :kind 'number)
1810         #+sb-xc-host :defined #-sb-xc-host :primitive)
1811   (setf (info :type :builtin 'number)
1812         (make-numeric-type :complexp nil)))
1813
1814 (!def-type-translator complex (&optional (typespec '*))
1815   (if (eq typespec '*)
1816       (specifier-type '(complex real))
1817       (labels ((not-numeric ()
1818                  (error "The component type for COMPLEX is not numeric: ~S"
1819                         typespec))
1820                (not-real ()
1821                  (error "The component type for COMPLEX is not a subtype of REAL: ~S"
1822                         typespec))
1823                (complex1 (component-type)
1824                  (unless (numeric-type-p component-type)
1825                    (not-numeric))
1826                  (when (eq (numeric-type-complexp component-type) :complex)
1827                    (not-real))
1828                  (if (csubtypep component-type (specifier-type '(eql 0)))
1829                      *empty-type*
1830                      (modified-numeric-type component-type
1831                                             :complexp :complex)))
1832                (do-complex (ctype)
1833                  (cond
1834                    ((eq ctype *empty-type*) *empty-type*)
1835                    ((eq ctype *universal-type*) (not-real))
1836                    ((typep ctype 'numeric-type) (complex1 ctype))
1837                    ((typep ctype 'union-type)
1838                     (apply #'type-union
1839                            (mapcar #'do-complex (union-type-types ctype))))
1840                    ((typep ctype 'member-type)
1841                     (apply #'type-union
1842                            (mapcar (lambda (x) (do-complex (ctype-of x)))
1843                                    (member-type-members ctype))))
1844                    ((and (typep ctype 'intersection-type)
1845                          ;; FIXME: This is very much a
1846                          ;; not-quite-worst-effort, but we are required to do
1847                          ;; something here because of our representation of
1848                          ;; RATIO as (AND RATIONAL (NOT INTEGER)): we must
1849                          ;; allow users to ask about (COMPLEX RATIO).  This
1850                          ;; will of course fail to work right on such types
1851                          ;; as (AND INTEGER (SATISFIES ZEROP))...
1852                          (let ((numbers (remove-if-not
1853                                          #'numeric-type-p
1854                                          (intersection-type-types ctype))))
1855                            (and (car numbers)
1856                                 (null (cdr numbers))
1857                                 (eq (numeric-type-complexp (car numbers)) :real)
1858                                 (complex1 (car numbers))))))
1859                    (t
1860                     (multiple-value-bind (subtypep certainly)
1861                         (csubtypep ctype (specifier-type 'real))
1862                       (if (and (not subtypep) certainly)
1863                           (not-real)
1864                           ;; ANSI just says that TYPESPEC is any subtype of
1865                           ;; type REAL, not necessarily a NUMERIC-TYPE. In
1866                           ;; particular, at this point TYPESPEC could legally
1867                           ;; be a hairy type like (AND NUMBER (SATISFIES
1868                           ;; REALP) (SATISFIES ZEROP)), in which case we fall
1869                           ;; through the logic above and end up here,
1870                           ;; stumped.
1871                           (bug "~@<(known bug #145): The type ~S is too hairy to be ~
1872 used for a COMPLEX component.~:@>"
1873                                typespec)))))))
1874         (let ((ctype (specifier-type typespec)))
1875           (do-complex ctype)))))
1876
1877 ;;; If X is *, return NIL, otherwise return the bound, which must be a
1878 ;;; member of TYPE or a one-element list of a member of TYPE.
1879 #!-sb-fluid (declaim (inline canonicalized-bound))
1880 (defun canonicalized-bound (bound type)
1881   (cond ((eq bound '*) nil)
1882         ((or (sb!xc:typep bound type)
1883              (and (consp bound)
1884                   (sb!xc:typep (car bound) type)
1885                   (null (cdr bound))))
1886           bound)
1887         (t
1888          (error "Bound is not ~S, a ~S or a list of a ~S: ~S"
1889                 '*
1890                 type
1891                 type
1892                 bound))))
1893
1894 (!def-type-translator integer (&optional (low '*) (high '*))
1895   (let* ((l (canonicalized-bound low 'integer))
1896          (lb (if (consp l) (1+ (car l)) l))
1897          (h (canonicalized-bound high 'integer))
1898          (hb (if (consp h) (1- (car h)) h)))
1899     (if (and hb lb (< hb lb))
1900         *empty-type*
1901       (make-numeric-type :class 'integer
1902                          :complexp :real
1903                          :enumerable (not (null (and l h)))
1904                          :low lb
1905                          :high hb))))
1906
1907 (defmacro !def-bounded-type (type class format)
1908   `(!def-type-translator ,type (&optional (low '*) (high '*))
1909      (let ((lb (canonicalized-bound low ',type))
1910            (hb (canonicalized-bound high ',type)))
1911        (if (not (numeric-bound-test* lb hb <= <))
1912            *empty-type*
1913          (make-numeric-type :class ',class
1914                             :format ',format
1915                             :low lb
1916                             :high hb)))))
1917
1918 (!def-bounded-type rational rational nil)
1919
1920 ;;; Unlike CMU CL, we represent the types FLOAT and REAL as
1921 ;;; UNION-TYPEs of more primitive types, in order to make
1922 ;;; type representation more unique, avoiding problems in the
1923 ;;; simplification of things like
1924 ;;;   (subtypep '(or (single-float -1.0 1.0) (single-float 0.1))
1925 ;;;             '(or (real -1 7) (single-float 0.1) (single-float -1.0 1.0)))
1926 ;;; When we allowed REAL to remain as a separate NUMERIC-TYPE,
1927 ;;; it was too easy for the first argument to be simplified to
1928 ;;; '(SINGLE-FLOAT -1.0), and for the second argument to be simplified
1929 ;;; to '(OR (REAL -1 7) (SINGLE-FLOAT 0.1)) and then for the
1930 ;;; SUBTYPEP to fail (returning NIL,T instead of T,T) because
1931 ;;; the first argument can't be seen to be a subtype of any of the
1932 ;;; terms in the second argument.
1933 ;;;
1934 ;;; The old CMU CL way was:
1935 ;;;   (!def-bounded-type float float nil)
1936 ;;;   (!def-bounded-type real nil nil)
1937 ;;;
1938 ;;; FIXME: If this new way works for a while with no weird new
1939 ;;; problems, we can go back and rip out support for separate FLOAT
1940 ;;; and REAL flavors of NUMERIC-TYPE. The new way was added in
1941 ;;; sbcl-0.6.11.22, 2001-03-21.
1942 ;;;
1943 ;;; FIXME: It's probably necessary to do something to fix the
1944 ;;; analogous problem with INTEGER and RATIONAL types. Perhaps
1945 ;;; bounded RATIONAL types should be represented as (OR RATIO INTEGER).
1946 (defun coerce-bound (bound type upperp inner-coerce-bound-fun)
1947   (declare (type function inner-coerce-bound-fun))
1948   (if (eql bound '*)
1949       bound
1950       (funcall inner-coerce-bound-fun bound type upperp)))
1951 (defun inner-coerce-real-bound (bound type upperp)
1952   #+sb-xc-host (declare (ignore upperp))
1953   (let #+sb-xc-host ()
1954        #-sb-xc-host
1955        ((nl (load-time-value (symbol-value 'sb!xc:most-negative-long-float)))
1956         (pl (load-time-value (symbol-value 'sb!xc:most-positive-long-float))))
1957     (let ((nbound (if (consp bound) (car bound) bound))
1958           (consp (consp bound)))
1959       (ecase type
1960         (rational
1961          (if consp
1962              (list (rational nbound))
1963              (rational nbound)))
1964         (float
1965          (cond
1966            ((floatp nbound) bound)
1967            (t
1968             ;; Coerce to the widest float format available, to avoid
1969             ;; unnecessary loss of precision, but don't coerce
1970             ;; unrepresentable numbers, except on the host where we
1971             ;; shouldn't be making these types (but KLUDGE: can't even
1972             ;; assert portably that we're not).
1973             #-sb-xc-host
1974             (ecase upperp
1975               ((nil)
1976                (when (< nbound nl) (return-from inner-coerce-real-bound nl)))
1977               ((t)
1978                (when (> nbound pl) (return-from inner-coerce-real-bound pl))))
1979             (let ((result (coerce nbound 'long-float)))
1980               (if consp (list result) result)))))))))
1981 (defun inner-coerce-float-bound (bound type upperp)
1982   #+sb-xc-host (declare (ignore upperp))
1983   (let #+sb-xc-host ()
1984        #-sb-xc-host
1985        ((nd (load-time-value (symbol-value 'sb!xc:most-negative-double-float)))
1986         (pd (load-time-value (symbol-value 'sb!xc:most-positive-double-float)))
1987         (ns (load-time-value (symbol-value 'sb!xc:most-negative-single-float)))
1988         (ps (load-time-value
1989              (symbol-value 'sb!xc:most-positive-single-float))))
1990     (let ((nbound (if (consp bound) (car bound) bound))
1991           (consp (consp bound)))
1992       (ecase type
1993         (single-float
1994          (cond
1995            ((typep nbound 'single-float) bound)
1996            (t
1997             #-sb-xc-host
1998             (ecase upperp
1999               ((nil)
2000                (when (< nbound ns) (return-from inner-coerce-float-bound ns)))
2001               ((t)
2002                (when (> nbound ps) (return-from inner-coerce-float-bound ps))))
2003             (let ((result (coerce nbound 'single-float)))
2004               (if consp (list result) result)))))
2005         (double-float
2006          (cond
2007            ((typep nbound 'double-float) bound)
2008            (t
2009             #-sb-xc-host
2010             (ecase upperp
2011               ((nil)
2012                (when (< nbound nd) (return-from inner-coerce-float-bound nd)))
2013               ((t)
2014                (when (> nbound pd) (return-from inner-coerce-float-bound pd))))
2015             (let ((result (coerce nbound 'double-float)))
2016               (if consp (list result) result)))))))))
2017 (defun coerced-real-bound (bound type upperp)
2018   (coerce-bound bound type upperp #'inner-coerce-real-bound))
2019 (defun coerced-float-bound (bound type upperp)
2020   (coerce-bound bound type upperp #'inner-coerce-float-bound))
2021 (!def-type-translator real (&optional (low '*) (high '*))
2022   (specifier-type `(or (float ,(coerced-real-bound  low 'float nil)
2023                               ,(coerced-real-bound high 'float t))
2024                        (rational ,(coerced-real-bound  low 'rational nil)
2025                                  ,(coerced-real-bound high 'rational t)))))
2026 (!def-type-translator float (&optional (low '*) (high '*))
2027   (specifier-type
2028    `(or (single-float ,(coerced-float-bound  low 'single-float nil)
2029                       ,(coerced-float-bound high 'single-float t))
2030         (double-float ,(coerced-float-bound  low 'double-float nil)
2031                       ,(coerced-float-bound high 'double-float t))
2032         #!+long-float ,(error "stub: no long float support yet"))))
2033
2034 (defmacro !define-float-format (f)
2035   `(!def-bounded-type ,f float ,f))
2036
2037 (!define-float-format short-float)
2038 (!define-float-format single-float)
2039 (!define-float-format double-float)
2040 (!define-float-format long-float)
2041
2042 (defun numeric-types-intersect (type1 type2)
2043   (declare (type numeric-type type1 type2))
2044   (let* ((class1 (numeric-type-class type1))
2045          (class2 (numeric-type-class type2))
2046          (complexp1 (numeric-type-complexp type1))
2047          (complexp2 (numeric-type-complexp type2))
2048          (format1 (numeric-type-format type1))
2049          (format2 (numeric-type-format type2))
2050          (low1 (numeric-type-low type1))
2051          (high1 (numeric-type-high type1))
2052          (low2 (numeric-type-low type2))
2053          (high2 (numeric-type-high type2)))
2054     ;; If one is complex and the other isn't, then they are disjoint.
2055     (cond ((not (or (eq complexp1 complexp2)
2056                     (null complexp1) (null complexp2)))
2057            nil)
2058           ;; If either type is a float, then the other must either be
2059           ;; specified to be a float or unspecified. Otherwise, they
2060           ;; are disjoint.
2061           ((and (eq class1 'float)
2062                 (not (member class2 '(float nil)))) nil)
2063           ((and (eq class2 'float)
2064                 (not (member class1 '(float nil)))) nil)
2065           ;; If the float formats are specified and different, the
2066           ;; types are disjoint.
2067           ((not (or (eq format1 format2) (null format1) (null format2)))
2068            nil)
2069           (t
2070            ;; Check the bounds. This is a bit odd because we must
2071            ;; always have the outer bound of the interval as the
2072            ;; second arg.
2073            (if (numeric-bound-test high1 high2 <= <)
2074                (or (and (numeric-bound-test low1 low2 >= >)
2075                         (numeric-bound-test* low1 high2 <= <))
2076                    (and (numeric-bound-test low2 low1 >= >)
2077                         (numeric-bound-test* low2 high1 <= <)))
2078                (or (and (numeric-bound-test* low2 high1 <= <)
2079                         (numeric-bound-test low2 low1 >= >))
2080                    (and (numeric-bound-test high2 high1 <= <)
2081                         (numeric-bound-test* high2 low1 >= >))))))))
2082
2083 ;;; Take the numeric bound X and convert it into something that can be
2084 ;;; used as a bound in a numeric type with the specified CLASS and
2085 ;;; FORMAT. If UP-P is true, then we round up as needed, otherwise we
2086 ;;; round down. UP-P true implies that X is a lower bound, i.e. (N) > N.
2087 ;;;
2088 ;;; This is used by NUMERIC-TYPE-INTERSECTION to mash the bound into
2089 ;;; the appropriate type number. X may only be a float when CLASS is
2090 ;;; FLOAT.
2091 ;;;
2092 ;;; ### Note: it is possible for the coercion to a float to overflow
2093 ;;; or underflow. This happens when the bound doesn't fit in the
2094 ;;; specified format. In this case, we should really return the
2095 ;;; appropriate {Most | Least}-{Positive | Negative}-XXX-Float float
2096 ;;; of desired format. But these conditions aren't currently signalled
2097 ;;; in any useful way.
2098 ;;;
2099 ;;; Also, when converting an open rational bound into a float we
2100 ;;; should probably convert it to a closed bound of the closest float
2101 ;;; in the specified format. KLUDGE: In general, open float bounds are
2102 ;;; screwed up. -- (comment from original CMU CL)
2103 (defun round-numeric-bound (x class format up-p)
2104   (if x
2105       (let ((cx (if (consp x) (car x) x)))
2106         (ecase class
2107           ((nil rational) x)
2108           (integer
2109            (if (and (consp x) (integerp cx))
2110                (if up-p (1+ cx) (1- cx))
2111                (if up-p (ceiling cx) (floor cx))))
2112           (float
2113            (let ((res
2114                   (cond
2115                     ((and format (subtypep format 'double-float))
2116                      (if (<= most-negative-double-float cx most-positive-double-float)
2117                          (coerce cx format)
2118                          nil))
2119                     (t
2120                      (if (<= most-negative-single-float cx most-positive-single-float)
2121                          ;; FIXME: bug #389
2122                          (coerce cx (or format 'single-float))
2123                          nil)))))
2124              (if (consp x) (list res) res)))))
2125       nil))
2126
2127 ;;; Handle the case of type intersection on two numeric types. We use
2128 ;;; TYPES-EQUAL-OR-INTERSECT to throw out the case of types with no
2129 ;;; intersection. If an attribute in TYPE1 is unspecified, then we use
2130 ;;; TYPE2's attribute, which must be at least as restrictive. If the
2131 ;;; types intersect, then the only attributes that can be specified
2132 ;;; and different are the class and the bounds.
2133 ;;;
2134 ;;; When the class differs, we use the more restrictive class. The
2135 ;;; only interesting case is RATIONAL/INTEGER, since RATIONAL includes
2136 ;;; INTEGER.
2137 ;;;
2138 ;;; We make the result lower (upper) bound the maximum (minimum) of
2139 ;;; the argument lower (upper) bounds. We convert the bounds into the
2140 ;;; appropriate numeric type before maximizing. This avoids possible
2141 ;;; confusion due to mixed-type comparisons (but I think the result is
2142 ;;; the same).
2143 (!define-type-method (number :simple-intersection2) (type1 type2)
2144   (declare (type numeric-type type1 type2))
2145   (if (numeric-types-intersect type1 type2)
2146       (let* ((class1 (numeric-type-class type1))
2147              (class2 (numeric-type-class type2))
2148              (class (ecase class1
2149                       ((nil) class2)
2150                       ((integer float) class1)
2151                       (rational (if (eq class2 'integer)
2152                                        'integer
2153                                        'rational))))
2154              (format (or (numeric-type-format type1)
2155                          (numeric-type-format type2))))
2156         (make-numeric-type
2157          :class class
2158          :format format
2159          :complexp (or (numeric-type-complexp type1)
2160                        (numeric-type-complexp type2))
2161          :low (numeric-bound-max
2162                (round-numeric-bound (numeric-type-low type1)
2163                                     class format t)
2164                (round-numeric-bound (numeric-type-low type2)
2165                                     class format t)
2166                > >= nil)
2167          :high (numeric-bound-max
2168                 (round-numeric-bound (numeric-type-high type1)
2169                                      class format nil)
2170                 (round-numeric-bound (numeric-type-high type2)
2171                                      class format nil)
2172                 < <= nil)))
2173       *empty-type*))
2174
2175 ;;; Given two float formats, return the one with more precision. If
2176 ;;; either one is null, return NIL.
2177 (defun float-format-max (f1 f2)
2178   (when (and f1 f2)
2179     (dolist (f *float-formats* (error "bad float format: ~S" f1))
2180       (when (or (eq f f1) (eq f f2))
2181         (return f)))))
2182
2183 ;;; Return the result of an operation on TYPE1 and TYPE2 according to
2184 ;;; the rules of numeric contagion. This is always NUMBER, some float
2185 ;;; format (possibly complex) or RATIONAL. Due to rational
2186 ;;; canonicalization, there isn't much we can do here with integers or
2187 ;;; rational complex numbers.
2188 ;;;
2189 ;;; If either argument is not a NUMERIC-TYPE, then return NUMBER. This
2190 ;;; is useful mainly for allowing types that are technically numbers,
2191 ;;; but not a NUMERIC-TYPE.
2192 (defun numeric-contagion (type1 type2)
2193   (if (and (numeric-type-p type1) (numeric-type-p type2))
2194       (let ((class1 (numeric-type-class type1))
2195             (class2 (numeric-type-class type2))
2196             (format1 (numeric-type-format type1))
2197             (format2 (numeric-type-format type2))
2198             (complexp1 (numeric-type-complexp type1))
2199             (complexp2 (numeric-type-complexp type2)))
2200         (cond ((or (null complexp1)
2201                    (null complexp2))
2202                (specifier-type 'number))
2203               ((eq class1 'float)
2204                (make-numeric-type
2205                 :class 'float
2206                 :format (ecase class2
2207                           (float (float-format-max format1 format2))
2208                           ((integer rational) format1)
2209                           ((nil)
2210                            ;; A double-float with any real number is a
2211                            ;; double-float.
2212                            #!-long-float
2213                            (if (eq format1 'double-float)
2214                              'double-float
2215                              nil)
2216                            ;; A long-float with any real number is a
2217                            ;; long-float.
2218                            #!+long-float
2219                            (if (eq format1 'long-float)
2220                              'long-float
2221                              nil)))
2222                 :complexp (if (or (eq complexp1 :complex)
2223                                   (eq complexp2 :complex))
2224                               :complex
2225                               :real)))
2226               ((eq class2 'float) (numeric-contagion type2 type1))
2227               ((and (eq complexp1 :real) (eq complexp2 :real))
2228                (make-numeric-type
2229                 :class (and class1 class2 'rational)
2230                 :complexp :real))
2231               (t
2232                (specifier-type 'number))))
2233       (specifier-type 'number)))
2234 \f
2235 ;;;; array types
2236
2237 (!define-type-class array)
2238
2239 ;;; What this does depends on the setting of the
2240 ;;; *USE-IMPLEMENTATION-TYPES* switch. If true, return the specialized
2241 ;;; element type, otherwise return the original element type.
2242 (defun specialized-element-type-maybe (type)
2243   (declare (type array-type type))
2244   (if *use-implementation-types*
2245       (array-type-specialized-element-type type)
2246       (array-type-element-type type)))
2247
2248 (!define-type-method (array :simple-=) (type1 type2)
2249   (cond ((not (and (equal (array-type-dimensions type1)
2250                           (array-type-dimensions type2))
2251                    (eq (array-type-complexp type1)
2252                        (array-type-complexp type2))))
2253          (values nil t))
2254         ((or (unknown-type-p (array-type-element-type type1))
2255              (unknown-type-p (array-type-element-type type2)))
2256          (multiple-value-bind (equalp certainp)
2257              (type= (array-type-element-type type1)
2258                     (array-type-element-type type2))
2259            ;; By its nature, the call to TYPE= should never return
2260            ;; NIL, T, as we don't know what the UNKNOWN-TYPE will grow
2261            ;; up to be.  -- CSR, 2002-08-19
2262            (aver (not (and (not equalp) certainp)))
2263            (values equalp certainp)))
2264         (t
2265          (values (type= (specialized-element-type-maybe type1)
2266                         (specialized-element-type-maybe type2))
2267                  t))))
2268
2269 (!define-type-method (array :negate) (type)
2270   ;; FIXME (and hint to PFD): we're vulnerable here to attacks of the
2271   ;; form "are (AND ARRAY (NOT (ARRAY T))) and (OR (ARRAY BIT) (ARRAY
2272   ;; NIL) (ARRAY CHAR) ...) equivalent?" -- CSR, 2003-12-10
2273   (make-negation-type :type type))
2274
2275 (!define-type-method (array :unparse) (type)
2276   (let ((dims (array-type-dimensions type))
2277         (eltype (type-specifier (array-type-element-type type)))
2278         (complexp (array-type-complexp type)))
2279     (cond ((eq dims '*)
2280            (if (eq eltype '*)
2281                (if complexp 'array 'simple-array)
2282                (if complexp `(array ,eltype) `(simple-array ,eltype))))
2283           ((= (length dims) 1)
2284            (if complexp
2285                (if (eq (car dims) '*)
2286                    (case eltype
2287                      (bit 'bit-vector)
2288                      ((base-char #!-sb-unicode character) 'base-string)
2289                      (* 'vector)
2290                      (t `(vector ,eltype)))
2291                    (case eltype
2292                      (bit `(bit-vector ,(car dims)))
2293                      ((base-char #!-sb-unicode character)
2294                       `(base-string ,(car dims)))
2295                      (t `(vector ,eltype ,(car dims)))))
2296                (if (eq (car dims) '*)
2297                    (case eltype
2298                      (bit 'simple-bit-vector)
2299                      ((base-char #!-sb-unicode character) 'simple-base-string)
2300                      ((t) 'simple-vector)
2301                      (t `(simple-array ,eltype (*))))
2302                    (case eltype
2303                      (bit `(simple-bit-vector ,(car dims)))
2304                      ((base-char #!-sb-unicode character)
2305                       `(simple-base-string ,(car dims)))
2306                      ((t) `(simple-vector ,(car dims)))
2307                      (t `(simple-array ,eltype ,dims))))))
2308           (t
2309            (if complexp
2310                `(array ,eltype ,dims)
2311                `(simple-array ,eltype ,dims))))))
2312
2313 (!define-type-method (array :simple-subtypep) (type1 type2)
2314   (let ((dims1 (array-type-dimensions type1))
2315         (dims2 (array-type-dimensions type2))
2316         (complexp2 (array-type-complexp type2)))
2317     (cond (;; not subtypep unless dimensions are compatible
2318            (not (or (eq dims2 '*)
2319                     (and (not (eq dims1 '*))
2320                          ;; (sbcl-0.6.4 has trouble figuring out that
2321                          ;; DIMS1 and DIMS2 must be lists at this
2322                          ;; point, and knowing that is important to
2323                          ;; compiling EVERY efficiently.)
2324                          (= (length (the list dims1))
2325                             (length (the list dims2)))
2326                          (every (lambda (x y)
2327                                   (or (eq y '*) (eql x y)))
2328                                 (the list dims1)
2329                                 (the list dims2)))))
2330            (values nil t))
2331           ;; not subtypep unless complexness is compatible
2332           ((not (or (eq complexp2 :maybe)
2333                     (eq (array-type-complexp type1) complexp2)))
2334            (values nil t))
2335           ;; Since we didn't fail any of the tests above, we win
2336           ;; if the TYPE2 element type is wild.
2337           ((eq (array-type-element-type type2) *wild-type*)
2338            (values t t))
2339           (;; Since we didn't match any of the special cases above, if
2340            ;; either element type is unknown we can only give a good
2341            ;; answer if they are the same.
2342            (or (unknown-type-p (array-type-element-type type1))
2343                (unknown-type-p (array-type-element-type type2)))
2344            (if (type= (array-type-element-type type1)
2345                       (array-type-element-type type2))
2346                (values t t)
2347                (values nil nil)))
2348           (;; Otherwise, the subtype relationship holds iff the
2349            ;; types are equal, and they're equal iff the specialized
2350            ;; element types are identical.
2351            t
2352            (values (type= (specialized-element-type-maybe type1)
2353                           (specialized-element-type-maybe type2))
2354                    t)))))
2355
2356 ;;; FIXME: is this dead?
2357 (!define-superclasses array
2358   ((base-string base-string)
2359    (vector vector)
2360    (array))
2361   !cold-init-forms)
2362
2363 (defun array-types-intersect (type1 type2)
2364   (declare (type array-type type1 type2))
2365   (let ((dims1 (array-type-dimensions type1))
2366         (dims2 (array-type-dimensions type2))
2367         (complexp1 (array-type-complexp type1))
2368         (complexp2 (array-type-complexp type2)))
2369     ;; See whether dimensions are compatible.
2370     (cond ((not (or (eq dims1 '*) (eq dims2 '*)
2371                     (and (= (length dims1) (length dims2))
2372                          (every (lambda (x y)
2373                                   (or (eq x '*) (eq y '*) (= x y)))
2374                                 dims1 dims2))))
2375            (values nil t))
2376           ;; See whether complexpness is compatible.
2377           ((not (or (eq complexp1 :maybe)
2378                     (eq complexp2 :maybe)
2379                     (eq complexp1 complexp2)))
2380            (values nil t))
2381           ;; Old comment:
2382           ;;
2383           ;;   If either element type is wild, then they intersect.
2384           ;;   Otherwise, the types must be identical.
2385           ;;
2386           ;; FIXME: There seems to have been a fair amount of
2387           ;; confusion about the distinction between requested element
2388           ;; type and specialized element type; here is one of
2389           ;; them. If we request an array to hold objects of an
2390           ;; unknown type, we can do no better than represent that
2391           ;; type as an array specialized on wild-type.  We keep the
2392           ;; requested element-type in the -ELEMENT-TYPE slot, and
2393           ;; *WILD-TYPE* in the -SPECIALIZED-ELEMENT-TYPE.  So, here,
2394           ;; we must test for the SPECIALIZED slot being *WILD-TYPE*,
2395           ;; not just the ELEMENT-TYPE slot.  Maybe the return value
2396           ;; in that specific case should be T, NIL?  Or maybe this
2397           ;; function should really be called
2398           ;; ARRAY-TYPES-COULD-POSSIBLY-INTERSECT?  In any case, this
2399           ;; was responsible for bug #123, and this whole issue could
2400           ;; do with a rethink and/or a rewrite.  -- CSR, 2002-08-21
2401           ((or (eq (array-type-specialized-element-type type1) *wild-type*)
2402                (eq (array-type-specialized-element-type type2) *wild-type*)
2403                (type= (specialized-element-type-maybe type1)
2404                       (specialized-element-type-maybe type2)))
2405
2406            (values t t))
2407           (t
2408            (values nil t)))))
2409
2410 (!define-type-method (array :simple-intersection2) (type1 type2)
2411   (declare (type array-type type1 type2))
2412   (if (array-types-intersect type1 type2)
2413       (let ((dims1 (array-type-dimensions type1))
2414             (dims2 (array-type-dimensions type2))
2415             (complexp1 (array-type-complexp type1))
2416             (complexp2 (array-type-complexp type2))
2417             (eltype1 (array-type-element-type type1))
2418             (eltype2 (array-type-element-type type2)))
2419         (specialize-array-type
2420          (make-array-type
2421           :dimensions (cond ((eq dims1 '*) dims2)
2422                             ((eq dims2 '*) dims1)
2423                             (t
2424                              (mapcar (lambda (x y) (if (eq x '*) y x))
2425                                      dims1 dims2)))
2426           :complexp (if (eq complexp1 :maybe) complexp2 complexp1)
2427           :element-type (cond
2428                           ((eq eltype1 *wild-type*) eltype2)
2429                           ((eq eltype2 *wild-type*) eltype1)
2430                           (t (type-intersection eltype1 eltype2))))))
2431       *empty-type*))
2432
2433 ;;; Check a supplied dimension list to determine whether it is legal,
2434 ;;; and return it in canonical form (as either '* or a list).
2435 (defun canonical-array-dimensions (dims)
2436   (typecase dims
2437     ((member *) dims)
2438     (integer
2439      (when (minusp dims)
2440        (error "Arrays can't have a negative number of dimensions: ~S" dims))
2441      (when (>= dims sb!xc:array-rank-limit)
2442        (error "array type with too many dimensions: ~S" dims))
2443      (make-list dims :initial-element '*))
2444     (list
2445      (when (>= (length dims) sb!xc:array-rank-limit)
2446        (error "array type with too many dimensions: ~S" dims))
2447      (dolist (dim dims)
2448        (unless (eq dim '*)
2449          (unless (and (integerp dim)
2450                       (>= dim 0)
2451                       (< dim sb!xc:array-dimension-limit))
2452            (error "bad dimension in array type: ~S" dim))))
2453      dims)
2454     (t
2455      (error "Array dimensions is not a list, integer or *:~%  ~S" dims))))
2456 \f
2457 ;;;; MEMBER types
2458
2459 (!define-type-class member)
2460
2461 (!define-type-method (member :negate) (type)
2462   (let ((members (member-type-members type)))
2463     (if (some #'floatp members)
2464         (let (floats)
2465           (dolist (pair `((0.0f0 . ,(load-time-value (make-unportable-float :single-float-negative-zero)))
2466                           (0.0d0 . ,(load-time-value (make-unportable-float :double-float-negative-zero)))
2467                           #!+long-float
2468                           (0.0l0 . ,(load-time-value (make-unportable-float :long-float-negative-zero)))))
2469             (when (member (car pair) members)
2470               (aver (not (member (cdr pair) members)))
2471               (push (cdr pair) floats)
2472               (setf members (remove (car pair) members)))
2473             (when (member (cdr pair) members)
2474               (aver (not (member (car pair) members)))
2475               (push (car pair) floats)
2476               (setf members (remove (cdr pair) members))))
2477           (apply #'type-intersection
2478                  (if (null members)
2479                      *universal-type*
2480                      (make-negation-type
2481                       :type (make-member-type :members members)))
2482                  (mapcar
2483                   (lambda (x)
2484                     (let ((type (ctype-of x)))
2485                       (type-union
2486                        (make-negation-type
2487                         :type (modified-numeric-type type
2488                                                      :low nil :high nil))
2489                        (modified-numeric-type type
2490                                               :low nil :high (list x))
2491                        (make-member-type :members (list x))
2492                        (modified-numeric-type type
2493                                               :low (list x) :high nil))))
2494                   floats)))
2495         (make-negation-type :type type))))
2496
2497 (!define-type-method (member :unparse) (type)
2498   (let ((members (member-type-members type)))
2499     (cond
2500       ((equal members '(nil)) 'null)
2501       ((type= type (specifier-type 'standard-char)) 'standard-char)
2502       (t `(member ,@members)))))
2503
2504 (!define-type-method (member :simple-subtypep) (type1 type2)
2505   (values (subsetp (member-type-members type1) (member-type-members type2))
2506           t))
2507
2508 (!define-type-method (member :complex-subtypep-arg1) (type1 type2)
2509   (every/type (swapped-args-fun #'ctypep)
2510               type2
2511               (member-type-members type1)))
2512
2513 ;;; We punt if the odd type is enumerable and intersects with the
2514 ;;; MEMBER type. If not enumerable, then it is definitely not a
2515 ;;; subtype of the MEMBER type.
2516 (!define-type-method (member :complex-subtypep-arg2) (type1 type2)
2517   (cond ((not (type-enumerable type1)) (values nil t))
2518         ((types-equal-or-intersect type1 type2)
2519          (invoke-complex-subtypep-arg1-method type1 type2))
2520         (t (values nil t))))
2521
2522 (!define-type-method (member :simple-intersection2) (type1 type2)
2523   (let ((mem1 (member-type-members type1))
2524         (mem2 (member-type-members type2)))
2525     (cond ((subsetp mem1 mem2) type1)
2526           ((subsetp mem2 mem1) type2)
2527           (t
2528            (let ((res (intersection mem1 mem2)))
2529              (if res
2530                  (make-member-type :members res)
2531                  *empty-type*))))))
2532
2533 (!define-type-method (member :complex-intersection2) (type1 type2)
2534   (block punt
2535     (collect ((members))
2536       (let ((mem2 (member-type-members type2)))
2537         (dolist (member mem2)
2538           (multiple-value-bind (val win) (ctypep member type1)
2539             (unless win
2540               (return-from punt nil))
2541             (when val (members member))))
2542         (cond ((subsetp mem2 (members)) type2)
2543               ((null (members)) *empty-type*)
2544               (t
2545                (make-member-type :members (members))))))))
2546
2547 ;;; We don't need a :COMPLEX-UNION2, since the only interesting case is
2548 ;;; a union type, and the member/union interaction is handled by the
2549 ;;; union type method.
2550 (!define-type-method (member :simple-union2) (type1 type2)
2551   (let ((mem1 (member-type-members type1))
2552         (mem2 (member-type-members type2)))
2553     (cond ((subsetp mem1 mem2) type2)
2554           ((subsetp mem2 mem1) type1)
2555           (t
2556            (make-member-type :members (union mem1 mem2))))))
2557
2558 (!define-type-method (member :simple-=) (type1 type2)
2559   (let ((mem1 (member-type-members type1))
2560         (mem2 (member-type-members type2)))
2561     (values (and (subsetp mem1 mem2)
2562                  (subsetp mem2 mem1))
2563             t)))
2564
2565 (!define-type-method (member :complex-=) (type1 type2)
2566   (if (type-enumerable type1)
2567       (multiple-value-bind (val win) (csubtypep type2 type1)
2568         (if (or val (not win))
2569             (values nil nil)
2570             (values nil t)))
2571       (values nil t)))
2572
2573 (!def-type-translator member (&rest members)
2574   (if members
2575       (let (ms numbers char-codes)
2576         (dolist (m (remove-duplicates members))
2577           (typecase m
2578             (float (if (zerop m)
2579                        (push m ms)
2580                        (push (ctype-of m) numbers)))
2581             (real (push (ctype-of m) numbers))
2582            (character (push (sb!xc:char-code m) char-codes))
2583             (t (push m ms))))
2584         (apply #'type-union
2585                (if ms
2586                    (make-member-type :members ms)
2587                    *empty-type*)
2588               (if char-codes
2589                   (make-character-set-type
2590                    :pairs (mapcar (lambda (x) (cons x x))
2591                                   (sort char-codes #'<)))
2592                   *empty-type*)
2593                (nreverse numbers)))
2594       *empty-type*))
2595 \f
2596 ;;;; intersection types
2597 ;;;;
2598 ;;;; Until version 0.6.10.6, SBCL followed the original CMU CL approach
2599 ;;;; of punting on all AND types, not just the unreasonably complicated
2600 ;;;; ones. The change was motivated by trying to get the KEYWORD type
2601 ;;;; to behave sensibly:
2602 ;;;;    ;; reasonable definition
2603 ;;;;    (DEFTYPE KEYWORD () '(AND SYMBOL (SATISFIES KEYWORDP)))
2604 ;;;;    ;; reasonable behavior
2605 ;;;;    (AVER (SUBTYPEP 'KEYWORD 'SYMBOL))
2606 ;;;; Without understanding a little about the semantics of AND, we'd
2607 ;;;; get (SUBTYPEP 'KEYWORD 'SYMBOL)=>NIL,NIL and, for entirely
2608 ;;;; parallel reasons, (SUBTYPEP 'RATIO 'NUMBER)=>NIL,NIL. That's
2609 ;;;; not so good..)
2610 ;;;;
2611 ;;;; We still follow the example of CMU CL to some extent, by punting
2612 ;;;; (to the opaque HAIRY-TYPE) on sufficiently complicated types
2613 ;;;; involving AND.
2614
2615 (!define-type-class intersection)
2616
2617 (!define-type-method (intersection :negate) (type)
2618   (apply #'type-union
2619          (mapcar #'type-negation (intersection-type-types type))))
2620
2621 ;;; A few intersection types have special names. The others just get
2622 ;;; mechanically unparsed.
2623 (!define-type-method (intersection :unparse) (type)
2624   (declare (type ctype type))
2625   (or (find type '(ratio keyword) :key #'specifier-type :test #'type=)
2626       `(and ,@(mapcar #'type-specifier (intersection-type-types type)))))
2627
2628 ;;; shared machinery for type equality: true if every type in the set
2629 ;;; TYPES1 matches a type in the set TYPES2 and vice versa
2630 (defun type=-set (types1 types2)
2631   (flet ((type<=-set (x y)
2632            (declare (type list x y))
2633            (every/type (lambda (x y-element)
2634                          (any/type #'type= y-element x))
2635                        x y)))
2636     (and/type (type<=-set types1 types2)
2637               (type<=-set types2 types1))))
2638
2639 ;;; Two intersection types are equal if their subtypes are equal sets.
2640 ;;;
2641 ;;; FIXME: Might it be better to use
2642 ;;;   (AND (SUBTYPEP X Y) (SUBTYPEP Y X))
2643 ;;; instead, since SUBTYPEP is the usual relationship that we care
2644 ;;; most about, so it would be good to leverage any ingenuity there
2645 ;;; in this more obscure method?
2646 (!define-type-method (intersection :simple-=) (type1 type2)
2647   (type=-set (intersection-type-types type1)
2648              (intersection-type-types type2)))
2649
2650 (defun %intersection-complex-subtypep-arg1 (type1 type2)
2651   (type= type1 (type-intersection type1 type2)))
2652
2653 (defun %intersection-simple-subtypep (type1 type2)
2654   (every/type #'%intersection-complex-subtypep-arg1
2655               type1
2656               (intersection-type-types type2)))
2657
2658 (!define-type-method (intersection :simple-subtypep) (type1 type2)
2659   (%intersection-simple-subtypep type1 type2))
2660
2661 (!define-type-method (intersection :complex-subtypep-arg1) (type1 type2)
2662   (%intersection-complex-subtypep-arg1 type1 type2))
2663
2664 (defun %intersection-complex-subtypep-arg2 (type1 type2)
2665   (every/type #'csubtypep type1 (intersection-type-types type2)))
2666
2667 (!define-type-method (intersection :complex-subtypep-arg2) (type1 type2)
2668   (%intersection-complex-subtypep-arg2 type1 type2))
2669
2670 ;;; FIXME: This will look eeriely familiar to readers of the UNION
2671 ;;; :SIMPLE-INTERSECTION2 :COMPLEX-INTERSECTION2 method.  That's
2672 ;;; because it was generated by cut'n'paste methods.  Given that
2673 ;;; intersections and unions have all sorts of symmetries known to
2674 ;;; mathematics, it shouldn't be beyond the ken of some programmers to
2675 ;;; reflect those symmetries in code in a way that ties them together
2676 ;;; more strongly than having two independent near-copies :-/
2677 (!define-type-method (intersection :simple-union2 :complex-union2)
2678                      (type1 type2)
2679   ;; Within this method, type2 is guaranteed to be an intersection
2680   ;; type:
2681   (aver (intersection-type-p type2))
2682   ;; Make sure to call only the applicable methods...
2683   (cond ((and (intersection-type-p type1)
2684               (%intersection-simple-subtypep type1 type2)) type2)
2685         ((and (intersection-type-p type1)
2686               (%intersection-simple-subtypep type2 type1)) type1)
2687         ((and (not (intersection-type-p type1))
2688               (%intersection-complex-subtypep-arg2 type1 type2))
2689          type2)
2690         ((and (not (intersection-type-p type1))
2691               (%intersection-complex-subtypep-arg1 type2 type1))
2692          type1)
2693         ;; KLUDGE: This special (and somewhat hairy) magic is required
2694         ;; to deal with the RATIONAL/INTEGER special case.  The UNION
2695         ;; of (INTEGER * -1) and (AND (RATIONAL * -1/2) (NOT INTEGER))
2696         ;; should be (RATIONAL * -1/2) -- CSR, 2003-02-28
2697         ((and (csubtypep type2 (specifier-type 'ratio))
2698               (numeric-type-p type1)
2699               (csubtypep type1 (specifier-type 'integer))
2700               (csubtypep type2
2701                          (make-numeric-type
2702                           :class 'rational
2703                           :complexp nil
2704                           :low (if (null (numeric-type-low type1))
2705                                    nil
2706                                    (list (1- (numeric-type-low type1))))
2707                           :high (if (null (numeric-type-high type1))
2708                                     nil
2709                                     (list (1+ (numeric-type-high type1)))))))
2710          (type-union type1
2711                      (apply #'type-intersection
2712                             (remove (specifier-type '(not integer))
2713                                     (intersection-type-types type2)
2714                                     :test #'type=))))
2715         (t
2716          (let ((accumulator *universal-type*))
2717            (do ((t2s (intersection-type-types type2) (cdr t2s)))
2718                ((null t2s) accumulator)
2719              (let ((union (type-union type1 (car t2s))))
2720                (when (union-type-p union)
2721                  ;; we have to give up here -- there are all sorts of
2722                  ;; ordering worries, but it's better than before.
2723                  ;; Doing exactly the same as in the UNION
2724                  ;; :SIMPLE/:COMPLEX-INTERSECTION2 method causes stack
2725                  ;; overflow with the mutual recursion never bottoming
2726                  ;; out.
2727                  (if (and (eq accumulator *universal-type*)
2728                           (null (cdr t2s)))
2729                      ;; KLUDGE: if we get here, we have a partially
2730                      ;; simplified result.  While this isn't by any
2731                      ;; means a universal simplification, including
2732                      ;; this logic here means that we can get (OR
2733                      ;; KEYWORD (NOT KEYWORD)) canonicalized to T.
2734                      (return union)
2735                      (return nil)))
2736                (setf accumulator
2737                      (type-intersection accumulator union))))))))
2738
2739 (!def-type-translator and (&whole whole &rest type-specifiers)
2740   (apply #'type-intersection
2741          (mapcar #'specifier-type type-specifiers)))
2742 \f
2743 ;;;; union types
2744
2745 (!define-type-class union)
2746
2747 (!define-type-method (union :negate) (type)
2748   (declare (type ctype type))
2749   (apply #'type-intersection
2750          (mapcar #'type-negation (union-type-types type))))
2751
2752 ;;; The LIST, FLOAT and REAL types have special names.  Other union
2753 ;;; types just get mechanically unparsed.
2754 (!define-type-method (union :unparse) (type)
2755   (declare (type ctype type))
2756   (cond
2757     ((type= type (specifier-type 'list)) 'list)
2758     ((type= type (specifier-type 'float)) 'float)
2759     ((type= type (specifier-type 'real)) 'real)
2760     ((type= type (specifier-type 'sequence)) 'sequence)
2761     ((type= type (specifier-type 'bignum)) 'bignum)
2762     ((type= type (specifier-type 'simple-string)) 'simple-string)
2763     ((type= type (specifier-type 'string)) 'string)
2764     ((type= type (specifier-type 'complex)) 'complex)
2765     ((type= type (specifier-type 'standard-char)) 'standard-char)
2766     (t `(or ,@(mapcar #'type-specifier (union-type-types type))))))
2767
2768 ;;; Two union types are equal if they are each subtypes of each
2769 ;;; other. We need to be this clever because our complex subtypep
2770 ;;; methods are now more accurate; we don't get infinite recursion
2771 ;;; because the simple-subtypep method delegates to complex-subtypep
2772 ;;; of the individual types of type1. - CSR, 2002-04-09
2773 ;;;
2774 ;;; Previous comment, now obsolete, but worth keeping around because
2775 ;;; it is true, though too strong a condition:
2776 ;;;
2777 ;;; Two union types are equal if their subtypes are equal sets.
2778 (!define-type-method (union :simple-=) (type1 type2)
2779   (multiple-value-bind (subtype certain?)
2780       (csubtypep type1 type2)
2781     (if subtype
2782         (csubtypep type2 type1)
2783         ;; we might as well become as certain as possible.
2784         (if certain?
2785             (values nil t)
2786             (multiple-value-bind (subtype certain?)
2787                 (csubtypep type2 type1)
2788               (declare (ignore subtype))
2789               (values nil certain?))))))
2790
2791 (!define-type-method (union :complex-=) (type1 type2)
2792   (declare (ignore type1))
2793   (if (some #'type-might-contain-other-types-p
2794             (union-type-types type2))
2795       (values nil nil)
2796       (values nil t)))
2797
2798 ;;; Similarly, a union type is a subtype of another if and only if
2799 ;;; every element of TYPE1 is a subtype of TYPE2.
2800 (defun union-simple-subtypep (type1 type2)
2801   (every/type (swapped-args-fun #'union-complex-subtypep-arg2)
2802               type2
2803               (union-type-types type1)))
2804
2805 (!define-type-method (union :simple-subtypep) (type1 type2)
2806   (union-simple-subtypep type1 type2))
2807
2808 (defun union-complex-subtypep-arg1 (type1 type2)
2809   (every/type (swapped-args-fun #'csubtypep)
2810               type2
2811               (union-type-types type1)))
2812
2813 (!define-type-method (union :complex-subtypep-arg1) (type1 type2)
2814   (union-complex-subtypep-arg1 type1 type2))
2815
2816 (defun union-complex-subtypep-arg2 (type1 type2)
2817   (multiple-value-bind (sub-value sub-certain?)
2818       ;; was: (any/type #'csubtypep type1 (union-type-types type2)),
2819       ;; which turns out to be too restrictive, causing bug 91.
2820       ;;
2821       ;; the following reimplementation might look dodgy.  It is
2822       ;; dodgy. It depends on the union :complex-= method not doing
2823       ;; very much work -- certainly, not using subtypep. Reasoning:
2824       (progn
2825         ;; At this stage, we know that type2 is a union type and type1
2826         ;; isn't. We might as well check this, though:
2827         (aver (union-type-p type2))
2828         (aver (not (union-type-p type1)))
2829         ;;     A is a subset of (B1 u B2)
2830         ;; <=> A n (B1 u B2) = A
2831         ;; <=> (A n B1) u (A n B2) = A
2832         ;;
2833         ;; But, we have to be careful not to delegate this type= to
2834         ;; something that could invoke subtypep, which might get us
2835         ;; back here -> stack explosion. We therefore ensure that the
2836         ;; second type (which is the one that's dispatched on) is
2837         ;; either a union type (where we've ensured that the complex-=
2838         ;; method will not call subtypep) or something with no union
2839         ;; types involved, in which case we'll never come back here.
2840         ;;
2841         ;; If we don't do this, then e.g.
2842         ;; (SUBTYPEP '(MEMBER 3) '(OR (SATISFIES FOO) (SATISFIES BAR)))
2843         ;; would loop infinitely, as the member :complex-= method is
2844         ;; implemented in terms of subtypep.
2845         ;;
2846         ;; Ouch. - CSR, 2002-04-10
2847         (type= type1
2848                (apply #'type-union
2849                       (mapcar (lambda (x) (type-intersection type1 x))
2850                               (union-type-types type2)))))
2851     (if sub-certain?
2852         (values sub-value sub-certain?)
2853         ;; The ANY/TYPE expression above is a sufficient condition for
2854         ;; subsetness, but not a necessary one, so we might get a more
2855         ;; certain answer by this CALL-NEXT-METHOD-ish step when the
2856         ;; ANY/TYPE expression is uncertain.
2857         (invoke-complex-subtypep-arg1-method type1 type2))))
2858
2859 (!define-type-method (union :complex-subtypep-arg2) (type1 type2)
2860   (union-complex-subtypep-arg2 type1 type2))
2861
2862 (!define-type-method (union :simple-intersection2 :complex-intersection2)
2863                      (type1 type2)
2864   ;; The CSUBTYPEP clauses here let us simplify e.g.
2865   ;;   (TYPE-INTERSECTION2 (SPECIFIER-TYPE 'LIST)
2866   ;;                       (SPECIFIER-TYPE '(OR LIST VECTOR)))
2867   ;; (where LIST is (OR CONS NULL)).
2868   ;;
2869   ;; The tests are more or less (CSUBTYPEP TYPE1 TYPE2) and vice
2870   ;; versa, but it's important that we pre-expand them into
2871   ;; specialized operations on individual elements of
2872   ;; UNION-TYPE-TYPES, instead of using the ordinary call to
2873   ;; CSUBTYPEP, in order to avoid possibly invoking any methods which
2874   ;; might in turn invoke (TYPE-INTERSECTION2 TYPE1 TYPE2) and thus
2875   ;; cause infinite recursion.
2876   ;;
2877   ;; Within this method, type2 is guaranteed to be a union type:
2878   (aver (union-type-p type2))
2879   ;; Make sure to call only the applicable methods...
2880   (cond ((and (union-type-p type1)
2881               (union-simple-subtypep type1 type2)) type1)
2882         ((and (union-type-p type1)
2883               (union-simple-subtypep type2 type1)) type2)
2884         ((and (not (union-type-p type1))
2885               (union-complex-subtypep-arg2 type1 type2))
2886          type1)
2887         ((and (not (union-type-p type1))
2888               (union-complex-subtypep-arg1 type2 type1))
2889          type2)
2890         (t
2891          ;; KLUDGE: This code accumulates a sequence of TYPE-UNION2
2892          ;; operations in a particular order, and gives up if any of
2893          ;; the sub-unions turn out not to be simple. In other cases
2894          ;; ca. sbcl-0.6.11.15, that approach to taking a union was a
2895          ;; bad idea, since it can overlook simplifications which
2896          ;; might occur if the terms were accumulated in a different
2897          ;; order. It's possible that that will be a problem here too.
2898          ;; However, I can't think of a good example to demonstrate
2899          ;; it, and without an example to demonstrate it I can't write
2900          ;; test cases, and without test cases I don't want to
2901          ;; complicate the code to address what's still a hypothetical
2902          ;; problem. So I punted. -- WHN 2001-03-20
2903          (let ((accumulator *empty-type*))
2904            (dolist (t2 (union-type-types type2) accumulator)
2905              (setf accumulator
2906                    (type-union accumulator
2907                                (type-intersection type1 t2))))))))
2908
2909 (!def-type-translator or (&rest type-specifiers)
2910   (apply #'type-union
2911          (mapcar #'specifier-type
2912                  type-specifiers)))
2913 \f
2914 ;;;; CONS types
2915
2916 (!define-type-class cons)
2917
2918 (!def-type-translator cons (&optional (car-type-spec '*) (cdr-type-spec '*))
2919   (let ((car-type (single-value-specifier-type car-type-spec))
2920         (cdr-type (single-value-specifier-type cdr-type-spec)))
2921     (make-cons-type car-type cdr-type)))
2922
2923 (!define-type-method (cons :negate) (type)
2924   (if (and (eq (cons-type-car-type type) *universal-type*)
2925            (eq (cons-type-cdr-type type) *universal-type*))
2926       (make-negation-type :type type)
2927       (type-union
2928        (make-negation-type :type (specifier-type 'cons))
2929        (cond
2930          ((and (not (eq (cons-type-car-type type) *universal-type*))
2931                (not (eq (cons-type-cdr-type type) *universal-type*)))
2932           (type-union
2933            (make-cons-type
2934             (type-negation (cons-type-car-type type))
2935             *universal-type*)
2936            (make-cons-type
2937             *universal-type*
2938             (type-negation (cons-type-cdr-type type)))))
2939          ((not (eq (cons-type-car-type type) *universal-type*))
2940           (make-cons-type
2941            (type-negation (cons-type-car-type type))
2942            *universal-type*))
2943          ((not (eq (cons-type-cdr-type type) *universal-type*))
2944           (make-cons-type
2945            *universal-type*
2946            (type-negation (cons-type-cdr-type type))))
2947          (t (bug "Weird CONS type ~S" type))))))
2948
2949 (!define-type-method (cons :unparse) (type)
2950   (let ((car-eltype (type-specifier (cons-type-car-type type)))
2951         (cdr-eltype (type-specifier (cons-type-cdr-type type))))
2952     (if (and (member car-eltype '(t *))
2953              (member cdr-eltype '(t *)))
2954         'cons
2955         `(cons ,car-eltype ,cdr-eltype))))
2956
2957 (!define-type-method (cons :simple-=) (type1 type2)
2958   (declare (type cons-type type1 type2))
2959   (and (type= (cons-type-car-type type1) (cons-type-car-type type2))
2960        (type= (cons-type-cdr-type type1) (cons-type-cdr-type type2))))
2961
2962 (!define-type-method (cons :simple-subtypep) (type1 type2)
2963   (declare (type cons-type type1 type2))
2964   (multiple-value-bind (val-car win-car)
2965       (csubtypep (cons-type-car-type type1) (cons-type-car-type type2))
2966     (multiple-value-bind (val-cdr win-cdr)
2967         (csubtypep (cons-type-cdr-type type1) (cons-type-cdr-type type2))
2968       (if (and val-car val-cdr)
2969           (values t (and win-car win-cdr))
2970           (values nil (or (and (not val-car) win-car)
2971                           (and (not val-cdr) win-cdr)))))))
2972
2973 ;;; Give up if a precise type is not possible, to avoid returning
2974 ;;; overly general types.
2975 (!define-type-method (cons :simple-union2) (type1 type2)
2976   (declare (type cons-type type1 type2))
2977   (let ((car-type1 (cons-type-car-type type1))
2978         (car-type2 (cons-type-car-type type2))
2979         (cdr-type1 (cons-type-cdr-type type1))
2980         (cdr-type2 (cons-type-cdr-type type2))
2981         car-not1
2982         car-not2)
2983     ;; UGH.  -- CSR, 2003-02-24
2984     (macrolet ((frob-car (car1 car2 cdr1 cdr2
2985                           &optional (not1 nil not1p))
2986                  `(type-union
2987                    (make-cons-type ,car1 (type-union ,cdr1 ,cdr2))
2988                    (make-cons-type
2989                     (type-intersection ,car2
2990                      ,(if not1p
2991                           not1
2992                           `(type-negation ,car1)))
2993                     ,cdr2))))
2994       (cond ((type= car-type1 car-type2)
2995              (make-cons-type car-type1
2996                              (type-union cdr-type1 cdr-type2)))
2997             ((type= cdr-type1 cdr-type2)
2998              (make-cons-type (type-union car-type1 car-type2)
2999                              cdr-type1))
3000             ((csubtypep car-type1 car-type2)
3001              (frob-car car-type1 car-type2 cdr-type1 cdr-type2))
3002             ((csubtypep car-type2 car-type1)
3003              (frob-car car-type2 car-type1 cdr-type2 cdr-type1))
3004             ;; more general case of the above, but harder to compute
3005             ((progn
3006                (setf car-not1 (type-negation car-type1))
3007                (multiple-value-bind (yes win)
3008                    (csubtypep car-type2 car-not1)
3009                  (and (not yes) win)))
3010              (frob-car car-type1 car-type2 cdr-type1 cdr-type2 car-not1))
3011             ((progn
3012                (setf car-not2 (type-negation car-type2))
3013                (multiple-value-bind (yes win)
3014                    (csubtypep car-type1 car-not2)
3015                  (and (not yes) win)))
3016              (frob-car car-type2 car-type1 cdr-type2 cdr-type1 car-not2))
3017             ;; Don't put these in -- consider the effect of taking the
3018             ;; union of (CONS (INTEGER 0 2) (INTEGER 5 7)) and
3019             ;; (CONS (INTEGER 0 3) (INTEGER 5 6)).
3020             #+nil
3021             ((csubtypep cdr-type1 cdr-type2)
3022              (frob-cdr car-type1 car-type2 cdr-type1 cdr-type2))
3023             #+nil
3024             ((csubtypep cdr-type2 cdr-type1)
3025              (frob-cdr car-type2 car-type1 cdr-type2 cdr-type1))))))
3026
3027 (!define-type-method (cons :simple-intersection2) (type1 type2)
3028   (declare (type cons-type type1 type2))
3029   (let ((car-int2 (type-intersection2 (cons-type-car-type type1)
3030                                       (cons-type-car-type type2)))
3031         (cdr-int2 (type-intersection2 (cons-type-cdr-type type1)
3032                                       (cons-type-cdr-type type2))))
3033     (cond
3034       ((and car-int2 cdr-int2) (make-cons-type car-int2 cdr-int2))
3035       (car-int2 (make-cons-type car-int2
3036                                 (type-intersection
3037                                  (cons-type-cdr-type type1)
3038                                  (cons-type-cdr-type type2))))
3039       (cdr-int2 (make-cons-type
3040                  (type-intersection (cons-type-car-type type1)
3041                                     (cons-type-car-type type2))
3042                  cdr-int2)))))
3043 \f
3044 ;;;; CHARACTER-SET types
3045
3046 (!define-type-class character-set)
3047
3048 (!def-type-translator character-set
3049     (&optional (pairs '((0 . #.(1- sb!xc:char-code-limit)))))
3050   (make-character-set-type :pairs pairs))
3051
3052 (!define-type-method (character-set :negate) (type)
3053   (let ((pairs (character-set-type-pairs type)))
3054     (if (and (= (length pairs) 1)
3055             (= (caar pairs) 0)
3056             (= (cdar pairs) (1- sb!xc:char-code-limit)))
3057        (make-negation-type :type type)
3058        (let ((not-character
3059               (make-negation-type
3060                :type (make-character-set-type
3061                       :pairs '((0 . #.(1- sb!xc:char-code-limit)))))))
3062          (type-union
3063           not-character
3064           (make-character-set-type
3065            :pairs (let (not-pairs)
3066                     (when (> (caar pairs) 0)
3067                       (push (cons 0 (1- (caar pairs))) not-pairs))
3068                     (do* ((tail pairs (cdr tail))
3069                           (high1 (cdar tail))
3070                           (low2 (caadr tail)))
3071                          ((null (cdr tail))
3072                           (when (< (cdar tail) (1- sb!xc:char-code-limit))
3073                             (push (cons (1+ (cdar tail))
3074                                         (1- sb!xc:char-code-limit))
3075                                   not-pairs))
3076                           (nreverse not-pairs))
3077                       (push (cons (1+ high1) (1- low2)) not-pairs)))))))))
3078
3079 (!define-type-method (character-set :unparse) (type)
3080   (cond
3081     ((type= type (specifier-type 'character)) 'character)
3082     ((type= type (specifier-type 'base-char)) 'base-char)
3083     ((type= type (specifier-type 'extended-char)) 'extended-char)
3084     ((type= type (specifier-type 'standard-char)) 'standard-char)
3085     (t (let ((pairs (character-set-type-pairs type)))
3086         `(member ,@(loop for (low . high) in pairs
3087                          nconc (loop for code from low upto high
3088                                      collect (sb!xc:code-char code))))))))
3089
3090 (!define-type-method (character-set :simple-=) (type1 type2)
3091   (let ((pairs1 (character-set-type-pairs type1))
3092        (pairs2 (character-set-type-pairs type2)))
3093     (values (equal pairs1 pairs2) t)))
3094
3095 (!define-type-method (character-set :simple-subtypep) (type1 type2)
3096   (values
3097    (dolist (pair (character-set-type-pairs type1) t)
3098      (unless (position pair (character-set-type-pairs type2)
3099                       :test (lambda (x y) (and (>= (car x) (car y))
3100                                                (<= (cdr x) (cdr y)))))
3101        (return nil)))
3102    t))
3103
3104 (!define-type-method (character-set :simple-union2) (type1 type2)
3105   ;; KLUDGE: the canonizing in the MAKE-CHARACTER-SET-TYPE function
3106   ;; actually does the union for us.  It might be a little fragile to
3107   ;; rely on it.
3108   (make-character-set-type
3109    :pairs (merge 'list
3110                 (copy-alist (character-set-type-pairs type1))
3111                 (copy-alist (character-set-type-pairs type2))
3112                 #'< :key #'car)))
3113
3114 (!define-type-method (character-set :simple-intersection2) (type1 type2)
3115   ;; KLUDGE: brute force.
3116 #|
3117   (let (pairs)
3118     (dolist (pair1 (character-set-type-pairs type1)
3119             (make-character-set-type
3120              :pairs (sort pairs #'< :key #'car)))
3121       (dolist (pair2 (character-set-type-pairs type2))
3122        (cond
3123          ((<= (car pair1) (car pair2) (cdr pair1))
3124           (push (cons (car pair2) (min (cdr pair1) (cdr pair2))) pairs))
3125          ((<= (car pair2) (car pair1) (cdr pair2))
3126           (push (cons (car pair1) (min (cdr pair1) (cdr pair2))) pairs))))))
3127 |#
3128   (make-character-set-type
3129    :pairs (intersect-type-pairs
3130            (character-set-type-pairs type1)
3131            (character-set-type-pairs type2))))
3132
3133 ;;;
3134 ;;; Intersect two ordered lists of pairs
3135 ;;; Each list is of the form ((start1 . end1) ... (startn . endn)),
3136 ;;; where start1 <= end1 < start2 <= end2 < ... < startn <= endn.
3137 ;;; Each pair represents the integer interval start..end.
3138 ;;;
3139 (defun intersect-type-pairs (alist1 alist2)
3140   (if (and alist1 alist2)
3141       (let ((res nil)
3142             (pair1 (pop alist1))
3143             (pair2 (pop alist2)))
3144         (loop
3145          (when (> (car pair1) (car pair2))
3146            (rotatef pair1 pair2)
3147            (rotatef alist1 alist2))
3148          (let ((pair1-cdr (cdr pair1)))
3149            (cond
3150             ((> (car pair2) pair1-cdr)
3151              ;; No over lap -- discard pair1
3152              (unless alist1 (return))
3153              (setq pair1 (pop alist1)))
3154             ((<= (cdr pair2) pair1-cdr)
3155              (push (cons (car pair2) (cdr pair2)) res)
3156              (cond
3157               ((= (cdr pair2) pair1-cdr)
3158                (unless alist1 (return))
3159                (unless alist2 (return))
3160                (setq pair1 (pop alist1)
3161                      pair2 (pop alist2)))
3162               (t ;; (< (cdr pair2) pair1-cdr)
3163                (unless alist2 (return))
3164                (setq pair1 (cons (1+ (cdr pair2)) pair1-cdr))
3165                (setq pair2 (pop alist2)))))
3166             (t ;; (> (cdr pair2) (cdr pair1))
3167              (push (cons (car pair2) pair1-cdr) res)
3168              (unless alist1 (return))
3169              (setq pair2 (cons (1+ pair1-cdr) (cdr pair2)))
3170              (setq pair1 (pop alist1))))))
3171         (nreverse res))
3172     nil))
3173
3174 \f
3175 ;;; Return the type that describes all objects that are in X but not
3176 ;;; in Y. If we can't determine this type, then return NIL.
3177 ;;;
3178 ;;; For now, we only are clever dealing with union and member types.
3179 ;;; If either type is not a union type, then we pretend that it is a
3180 ;;; union of just one type. What we do is remove from X all the types
3181 ;;; that are a subtype any type in Y. If any type in X intersects with
3182 ;;; a type in Y but is not a subtype, then we give up.
3183 ;;;
3184 ;;; We must also special-case any member type that appears in the
3185 ;;; union. We remove from X's members all objects that are TYPEP to Y.
3186 ;;; If Y has any members, we must be careful that none of those
3187 ;;; members are CTYPEP to any of Y's non-member types. We give up in
3188 ;;; this case, since to compute that difference we would have to break
3189 ;;; the type from X into some collection of types that represents the
3190 ;;; type without that particular element. This seems too hairy to be
3191 ;;; worthwhile, given its low utility.
3192 (defun type-difference (x y)
3193   (let ((x-types (if (union-type-p x) (union-type-types x) (list x)))
3194         (y-types (if (union-type-p y) (union-type-types y) (list y))))
3195     (collect ((res))
3196       (dolist (x-type x-types)
3197         (if (member-type-p x-type)
3198             (collect ((members))
3199               (dolist (mem (member-type-members x-type))
3200                 (multiple-value-bind (val win) (ctypep mem y)
3201                   (unless win (return-from type-difference nil))
3202                   (unless val
3203                     (members mem))))
3204               (when (members)
3205                 (res (make-member-type :members (members)))))
3206             (dolist (y-type y-types (res x-type))
3207               (multiple-value-bind (val win) (csubtypep x-type y-type)
3208                 (unless win (return-from type-difference nil))
3209                 (when val (return))
3210                 (when (types-equal-or-intersect x-type y-type)
3211                   (return-from type-difference nil))))))
3212       (let ((y-mem (find-if #'member-type-p y-types)))
3213         (when y-mem
3214           (let ((members (member-type-members y-mem)))
3215             (dolist (x-type x-types)
3216               (unless (member-type-p x-type)
3217                 (dolist (member members)
3218                   (multiple-value-bind (val win) (ctypep member x-type)
3219                     (when (or (not win) val)
3220                       (return-from type-difference nil)))))))))
3221       (apply #'type-union (res)))))
3222 \f
3223 (!def-type-translator array (&optional (element-type '*)
3224                                        (dimensions '*))
3225   (specialize-array-type
3226    (make-array-type :dimensions (canonical-array-dimensions dimensions)
3227                     :complexp :maybe
3228                     :element-type (if (eq element-type '*)
3229                                       *wild-type*
3230                                       (specifier-type element-type)))))
3231
3232 (!def-type-translator simple-array (&optional (element-type '*)
3233                                               (dimensions '*))
3234   (specialize-array-type
3235    (make-array-type :dimensions (canonical-array-dimensions dimensions)
3236                     :complexp nil
3237                     :element-type (if (eq element-type '*)
3238                                       *wild-type*
3239                                       (specifier-type element-type)))))
3240 \f
3241 ;;;; utilities shared between cross-compiler and target system
3242
3243 ;;; Does the type derived from compilation of an actual function
3244 ;;; definition satisfy declarations of a function's type?
3245 (defun defined-ftype-matches-declared-ftype-p (defined-ftype declared-ftype)
3246   (declare (type ctype defined-ftype declared-ftype))
3247   (flet ((is-built-in-class-function-p (ctype)
3248            (and (built-in-classoid-p ctype)
3249                 (eq (built-in-classoid-name ctype) 'function))))
3250     (cond (;; DECLARED-FTYPE could certainly be #<BUILT-IN-CLASS FUNCTION>;
3251            ;; that's what happens when we (DECLAIM (FTYPE FUNCTION FOO)).
3252            (is-built-in-class-function-p declared-ftype)
3253            ;; In that case, any definition satisfies the declaration.
3254            t)
3255           (;; It's not clear whether or how DEFINED-FTYPE might be
3256            ;; #<BUILT-IN-CLASS FUNCTION>, but it's not obviously
3257            ;; invalid, so let's handle that case too, just in case.
3258            (is-built-in-class-function-p defined-ftype)
3259            ;; No matter what DECLARED-FTYPE might be, we can't prove
3260            ;; that an object of type FUNCTION doesn't satisfy it, so
3261            ;; we return success no matter what.
3262            t)
3263           (;; Otherwise both of them must be FUN-TYPE objects.
3264            t
3265            ;; FIXME: For now we only check compatibility of the return
3266            ;; type, not argument types, and we don't even check the
3267            ;; return type very precisely (as per bug 94a). It would be
3268            ;; good to do a better job. Perhaps to check the
3269            ;; compatibility of the arguments, we should (1) redo
3270            ;; VALUES-TYPES-EQUAL-OR-INTERSECT as
3271            ;; ARGS-TYPES-EQUAL-OR-INTERSECT, and then (2) apply it to
3272            ;; the ARGS-TYPE slices of the FUN-TYPEs. (ARGS-TYPE
3273            ;; is a base class both of VALUES-TYPE and of FUN-TYPE.)
3274            (values-types-equal-or-intersect
3275             (fun-type-returns defined-ftype)
3276             (fun-type-returns declared-ftype))))))
3277
3278 ;;; This messy case of CTYPE for NUMBER is shared between the
3279 ;;; cross-compiler and the target system.
3280 (defun ctype-of-number (x)
3281   (let ((num (if (complexp x) (realpart x) x)))
3282     (multiple-value-bind (complexp low high)
3283         (if (complexp x)
3284             (let ((imag (imagpart x)))
3285               (values :complex (min num imag) (max num imag)))
3286             (values :real num num))
3287       (make-numeric-type :class (etypecase num
3288                                   (integer (if (complexp x)
3289                                                (if (integerp (imagpart x))
3290                                                    'integer
3291                                                    'rational)
3292                                                'integer))
3293                                   (rational 'rational)
3294                                   (float 'float))
3295                          :format (and (floatp num) (float-format-name num))
3296                          :complexp complexp
3297                          :low low
3298                          :high high))))
3299 \f
3300 (locally
3301   ;; Why SAFETY 0? To suppress the is-it-the-right-structure-type
3302   ;; checking for declarations in structure accessors. Otherwise we
3303   ;; can get caught in a chicken-and-egg bootstrapping problem, whose
3304   ;; symptom on x86 OpenBSD sbcl-0.pre7.37.flaky5.22 is an illegal
3305   ;; instruction trap. I haven't tracked it down, but I'm guessing it
3306   ;; has to do with setting LAYOUTs when the LAYOUT hasn't been set
3307   ;; yet. -- WHN
3308   (declare (optimize (safety 0)))
3309   (!defun-from-collected-cold-init-forms !late-type-cold-init))
3310
3311 (/show0 "late-type.lisp end of file")