0.6.8.17:
[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 (!begin-collecting-cold-init-forms)
20
21 ;;; ### Remaining incorrectnesses:
22 ;;;
23 ;;; TYPE-UNION (and the OR type) doesn't properly canonicalize an
24 ;;; exhaustive partition or coalesce contiguous ranges of numeric
25 ;;; types.
26 ;;;
27 ;;; There are all sorts of nasty problems with open bounds on FLOAT
28 ;;; types (and probably FLOAT types in general.)
29 ;;;
30 ;;; RATIO and BIGNUM are not recognized as numeric types.
31
32 ;;; FIXME: It seems to me that this should be set to NIL by default,
33 ;;; and perhaps not even optionally set to T.
34 (defvar *use-implementation-types* t
35   #!+sb-doc
36   "*USE-IMPLEMENTATION-TYPES* is a semi-public flag which determines how
37    restrictive we are in determining type membership. If two types are the
38    same in the implementation, then we will consider them them the same when
39    this switch is on. When it is off, we try to be as restrictive as the
40    language allows, allowing us to detect more errors. Currently, this only
41    affects array types.")
42
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-intersection (type1 type2)
59   (let ((method (type-class-complex-intersection (type-class-info type1))))
60     (if (and method (not (eq method #'delegate-complex-intersection)))
61         (funcall method type2 type1)
62         (vanilla-intersection 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 ;;; This will never be called with a hairy type as TYPE2, since the
68 ;;; hairy type TYPE2 method gets first crack.
69 (defun !has-superclasses-complex-subtypep-arg1 (type1 type2 info)
70   (values
71    (and (sb!xc:typep type2 'sb!xc:class)
72         (dolist (x info nil)
73           (when (or (not (cdr x))
74                     (csubtypep type1 (specifier-type (cdr x))))
75             (return
76              (or (eq type2 (car x))
77                  (let ((inherits (layout-inherits (class-layout (car x)))))
78                    (dotimes (i (length inherits) nil)
79                      (when (eq type2 (layout-class (svref inherits i)))
80                        (return t)))))))))
81    t))
82
83 ;;; This function takes a list of specs, each of the form
84 ;;;    (SUPERCLASS-NAME &OPTIONAL GUARD).
85 ;;; Consider one spec (with no guard): any instance of the named
86 ;;; TYPE-CLASS is also a subtype of the named superclass and of any of
87 ;;; its superclasses. If there are multiple specs, then some will have
88 ;;; guards. We choose the first spec whose guard is a supertype of
89 ;;; TYPE1 and use its superclass. In effect, a sequence of guards
90 ;;;    G0, G1, G2
91 ;;; is actually
92 ;;;    G0,(and G1 (not G0)), (and G2 (not (or G0 G1))).
93 ;;;
94 ;;; WHEN controls when the forms are executed.
95 (defmacro !define-superclasses (type-class-name specs when)
96   (let ((type-class (gensym "TYPE-CLASS-"))
97         (info (gensym "INFO")))
98     `(,when
99        (let ((,type-class (type-class-or-lose ',type-class-name))
100              (,info (mapcar (lambda (spec)
101                               (destructuring-bind
102                                   (super &optional guard)
103                                   spec
104                                 (cons (sb!xc:find-class super) guard)))
105                             ',specs)))
106          (setf (type-class-complex-subtypep-arg1 ,type-class)
107                (lambda (type1 type2)
108                  (!has-superclasses-complex-subtypep-arg1 type1 type2 ,info)))
109          (setf (type-class-complex-subtypep-arg2 ,type-class)
110                #'delegate-complex-subtypep-arg2)
111          (setf (type-class-complex-intersection ,type-class)
112                #'delegate-complex-intersection)))))
113 \f
114 ;;;; FUNCTION and VALUES types
115 ;;;;
116 ;;;; Pretty much all of the general type operations are illegal on
117 ;;;; VALUES types, since we can't discriminate using them, do
118 ;;;; SUBTYPEP, etc. FUNCTION types are acceptable to the normal type
119 ;;;; operations, but are generally considered to be equivalent to
120 ;;;; FUNCTION. These really aren't true types in any type theoretic
121 ;;;; sense, but we still parse them into CTYPE structures for two
122 ;;;; reasons:
123
124 ;;;; -- Parsing and unparsing work the same way, and indeed we can't
125 ;;;;    tell whether a type is a function or values type without
126 ;;;;    parsing it.
127 ;;;; -- Many of the places that can be annotated with real types can
128 ;;;;    also be annotated with function or values types.
129
130 ;;; the description of a keyword argument
131 (defstruct (key-info #-sb-xc-host (:pure t))
132   ;; the keyword
133   (name (required-argument) :type keyword)
134   ;; the type of the argument value
135   (type (required-argument) :type ctype))
136
137 (!define-type-method (values :simple-subtypep :complex-subtypep-arg1)
138                     (type1 type2)
139   (declare (ignore type2))
140   (error "Subtypep is illegal on this type:~%  ~S" (type-specifier type1)))
141
142 (!define-type-method (values :complex-subtypep-arg2)
143                     (type1 type2)
144   (declare (ignore type1))
145   (error "Subtypep is illegal on this type:~%  ~S" (type-specifier type2)))
146
147 (!define-type-method (values :unparse) (type)
148   (cons 'values (unparse-args-types type)))
149
150 ;;; Return true if LIST1 and LIST2 have the same elements in the same
151 ;;; positions according to TYPE=. We return NIL, NIL if there is an
152 ;;; uncertain comparison.
153 (defun type=-list (list1 list2)
154   (declare (list list1 list2))
155   (do ((types1 list1 (cdr types1))
156        (types2 list2 (cdr types2)))
157       ((or (null types1) (null types2))
158        (if (or types1 types2)
159            (values nil t)
160            (values t t)))
161     (multiple-value-bind (val win)
162         (type= (first types1) (first types2))
163       (unless win
164         (return (values nil nil)))
165       (unless val
166         (return (values nil t))))))
167
168 (!define-type-method (values :simple-=) (type1 type2)
169   (let ((rest1 (args-type-rest type1))
170         (rest2 (args-type-rest type2)))
171     (cond ((or (args-type-keyp type1) (args-type-keyp type2)
172                (args-type-allowp type1) (args-type-allowp type2))
173            (values nil nil))
174           ((and rest1 rest2 (type/= rest1 rest2))
175            (type= rest1 rest2))
176           ((or rest1 rest2)
177            (values nil t))
178           (t
179            (multiple-value-bind (req-val req-win)
180                (type=-list (values-type-required type1)
181                            (values-type-required type2))
182              (multiple-value-bind (opt-val opt-win)
183                  (type=-list (values-type-optional type1)
184                              (values-type-optional type2))
185                (values (and req-val opt-val) (and req-win opt-win))))))))
186
187 (!define-type-class function)
188
189 ;;; a flag that we can bind to cause complex function types to be
190 ;;; unparsed as FUNCTION. This is useful when we want a type that we
191 ;;; can pass to TYPEP.
192 (defvar *unparse-function-type-simplify*)
193 (!cold-init-forms (setq *unparse-function-type-simplify* nil))
194
195 (!define-type-method (function :unparse) (type)
196   (if *unparse-function-type-simplify*
197       'function
198       (list 'function
199             (if (function-type-wild-args type)
200                 '*
201                 (unparse-args-types type))
202             (type-specifier
203              (function-type-returns type)))))
204
205 ;;; Since all function types are equivalent to FUNCTION, they are all
206 ;;; subtypes of each other.
207 (!define-type-method (function :simple-subtypep) (type1 type2)
208   (declare (ignore type1 type2))
209   (values t t))
210
211 (!define-superclasses function ((function)) !cold-init-forms)
212
213 ;;; The union or intersection of two FUNCTION types is FUNCTION.
214 (!define-type-method (function :simple-union) (type1 type2)
215   (declare (ignore type1 type2))
216   (specifier-type 'function))
217 (!define-type-method (function :simple-intersection) (type1 type2)
218   (declare (ignore type1 type2))
219   (values (specifier-type 'function) t))
220
221 ;;; ### Not very real, but good enough for redefining transforms
222 ;;; according to type:
223 (!define-type-method (function :simple-=) (type1 type2)
224   (values (equalp type1 type2) t))
225
226 (!define-type-class constant :inherits values)
227
228 (!define-type-method (constant :unparse) (type)
229   `(constant-argument ,(type-specifier (constant-type-type type))))
230
231 (!define-type-method (constant :simple-=) (type1 type2)
232   (type= (constant-type-type type1) (constant-type-type type2)))
233
234 (!def-type-translator constant-argument (type)
235   (make-constant-type :type (specifier-type type)))
236
237 ;;; Given a LAMBDA-LIST-like values type specification and an ARGS-TYPE
238 ;;; structure, fill in the slots in the structure accordingly. This is
239 ;;; used for both FUNCTION and VALUES types.
240 (declaim (ftype (function (list args-type) (values)) parse-args-types))
241 (defun parse-args-types (lambda-list result)
242   (multiple-value-bind (required optional restp rest keyp keys allowp aux)
243       (parse-lambda-list lambda-list)
244     (when aux
245       (error "&Aux in a FUNCTION or VALUES type: ~S." lambda-list))
246     (setf (args-type-required result) (mapcar #'specifier-type required))
247     (setf (args-type-optional result) (mapcar #'specifier-type optional))
248     (setf (args-type-rest result) (if restp (specifier-type rest) nil))
249     (setf (args-type-keyp result) keyp)
250     (collect ((key-info))
251       (dolist (key keys)
252         (unless (proper-list-of-length-p key 2)
253           (error "Keyword type description is not a two-list: ~S." key))
254         (let ((kwd (first key)))
255           (when (find kwd (key-info) :key #'key-info-name)
256             (error "Repeated keyword ~S in lambda list: ~S." kwd lambda-list))
257           (key-info (make-key-info :name kwd
258                                    :type (specifier-type (second key))))))
259       (setf (args-type-keywords result) (key-info)))
260     (setf (args-type-allowp result) allowp)
261     (values)))
262
263 ;;; Return the lambda-list-like type specification corresponding
264 ;;; to an ARGS-TYPE.
265 (declaim (ftype (function (args-type) list) unparse-args-types))
266 (defun unparse-args-types (type)
267   (collect ((result))
268
269     (dolist (arg (args-type-required type))
270       (result (type-specifier arg)))
271
272     (when (args-type-optional type)
273       (result '&optional)
274       (dolist (arg (args-type-optional type))
275         (result (type-specifier arg))))
276
277     (when (args-type-rest type)
278       (result '&rest)
279       (result (type-specifier (args-type-rest type))))
280
281     (when (args-type-keyp type)
282       (result '&key)
283       (dolist (key (args-type-keywords type))
284         (result (list (key-info-name key)
285                       (type-specifier (key-info-type key))))))
286
287     (when (args-type-allowp type)
288       (result '&allow-other-keys))
289
290     (result)))
291
292 (!def-type-translator function (&optional (args '*) (result '*))
293   (let ((res (make-function-type
294               :returns (values-specifier-type result))))
295     (if (eq args '*)
296         (setf (function-type-wild-args res) t)
297         (parse-args-types args res))
298     res))
299
300 (!def-type-translator values (&rest values)
301   (let ((res (make-values-type)))
302     (parse-args-types values res)
303     res))
304 \f
305 ;;;; VALUES types interfaces
306 ;;;;
307 ;;;; We provide a few special operations that can be meaningfully used
308 ;;;; on VALUES types (as well as on any other type).
309
310 ;;; Return the type of the first value indicated by Type. This is used
311 ;;; by people who don't want to have to deal with values types.
312
313 ;;; MNA: fix-instance-typep-call patch
314 #!-sb-fluid (declaim (freeze-type values-type))
315 ; (inline single-value-type))
316 (defun single-value-type (type)
317   (declare (type ctype type))
318   (cond ((values-type-p type)
319          (or (car (args-type-required type))
320              (if (args-type-optional type)
321                  (type-union (car (args-type-optional type)) (specifier-type 'null)))
322              (args-type-rest type)
323              (specifier-type 'null)))
324         ((eq type *wild-type*)
325          *universal-type*)
326         (t
327          type)))
328
329 ;;; Return the minmum number of arguments that a function can be
330 ;;; called with, and the maximum number or NIL. If not a function
331 ;;; type, return NIL, NIL.
332 (defun function-type-nargs (type)
333   (declare (type ctype type))
334   (if (function-type-p type)
335       (let ((fixed (length (args-type-required type))))
336         (if (or (args-type-rest type)
337                 (args-type-keyp type)
338                 (args-type-allowp type))
339             (values fixed nil)
340             (values fixed (+ fixed (length (args-type-optional type))))))
341       (values nil nil)))
342
343 ;;; Determine if Type corresponds to a definite number of values. The
344 ;;; first value is a list of the types for each value, and the second
345 ;;; value is the number of values. If the number of values is not
346 ;;; fixed, then return NIL and :Unknown.
347 (defun values-types (type)
348   (declare (type ctype type))
349   (cond ((eq type *wild-type*)
350          (values nil :unknown))
351         ((not (values-type-p type))
352          (values (list type) 1))
353         ((or (args-type-optional type)
354              (args-type-rest type)
355              (args-type-keyp type)
356              (args-type-allowp type))
357          (values nil :unknown))
358         (t
359          (let ((req (args-type-required type)))
360            (values (mapcar #'single-value-type req) (length req))))))
361
362 ;;; Return two values:
363 ;;; MNA: fix-instance-typep-call patch
364 ;;; 1. A list of all the positional (fixed and optional) types.
365 ;;; 2. The &REST type (if any). If keywords allowed, *UNIVERSAL-TYPE*.
366 ;;;    If no keywords or &REST, then the DEFAULT-TYPE.
367 (defun values-type-types (type &optional (default-type *empty-type*))
368   (declare (type values-type type))
369   (values (append (args-type-required type)
370                   (args-type-optional type))
371           (cond ((args-type-keyp type) *universal-type*)
372                 ((args-type-rest type))
373                 (t
374                   ;; MNA: fix-instance-typep-call patch
375                   default-type))))
376
377 ;;; Return a list of OPERATION applied to the types in TYPES1 and
378 ;;; TYPES2, padding with REST2 as needed. TYPES1 must not be shorter
379 ;;; than TYPES2. The second value is T if OPERATION always returned a
380 ;;; true second value.
381 (defun fixed-values-op (types1 types2 rest2 operation)
382   (declare (list types1 types2) (type ctype rest2) (type function operation))
383   (let ((exact t))
384     (values (mapcar #'(lambda (t1 t2)
385                         (multiple-value-bind (res win)
386                             (funcall operation t1 t2)
387                           (unless win
388                             (setq exact nil))
389                           res))
390                     types1
391                     (append types2
392                             (make-list (- (length types1) (length types2))
393                                        :initial-element rest2)))
394             exact)))
395
396 ;;; If Type isn't a values type, then make it into one:
397 ;;;    <type>  ==>  (values type &rest t)
398 (defun coerce-to-values (type)
399   (declare (type ctype type))
400   (if (values-type-p type)
401       type
402       (make-values-type :required (list type) :rest *universal-type*)))
403
404 ;;; Do the specified OPERATION on TYPE1 and TYPE2, which may be any
405 ;;; type, including VALUES types. With VALUES types such as:
406 ;;;    (VALUES a0 a1)
407 ;;;    (VALUES b0 b1)
408 ;;; we compute the more useful result
409 ;;;    (VALUES (<operation> a0 b0) (<operation> a1 b1))
410 ;;; rather than the precise result
411 ;;;    (<operation> (values a0 a1) (values b0 b1))
412 ;;; This has the virtue of always keeping the VALUES type specifier
413 ;;; outermost, and retains all of the information that is really
414 ;;; useful for static type analysis. We want to know what is always
415 ;;; true of each value independently. It is worthless to know that IF
416 ;;; the first value is B0 then the second will be B1.
417 ;;;
418 ;;; If the VALUES count signatures differ, then we produce a result with
419 ;;; the required VALUE count chosen by NREQ when applied to the number
420 ;;; of required values in TYPE1 and TYPE2. Any &KEY values become
421 ;;; &REST T (anyone who uses keyword values deserves to lose.)
422 ;;;
423 ;;; The second value is true if the result is definitely empty or if
424 ;;; OPERATION returned true as its second value each time we called
425 ;;; it. Since we approximate the intersection of VALUES types, the
426 ;;; second value being true doesn't mean the result is exact.
427 ;;; MNA: fix-instance-typep-call patch
428 (defun args-type-op (type1 type2 operation nreq default-type)
429   ;;; MNA: fix-instance-typep-call patch
430   (declare (type ctype type1 type2 default-type)
431            (type function operation nreq))
432   (if (or (values-type-p type1) (values-type-p type2))
433       (let ((type1 (coerce-to-values type1))
434             (type2 (coerce-to-values type2)))
435         (multiple-value-bind (types1 rest1)
436             ;;; MNA: fix-instance-typep-call patch
437             (values-type-types type1 default-type)
438           (multiple-value-bind (types2 rest2)
439               ;;; MNA: fix-instance-typep-call patch
440               (values-type-types type2 default-type)
441             (multiple-value-bind (rest rest-exact)
442                 (funcall operation rest1 rest2)
443               (multiple-value-bind (res res-exact)
444                   (if (< (length types1) (length types2))
445                       (fixed-values-op types2 types1 rest1 operation)
446                       (fixed-values-op types1 types2 rest2 operation))
447                 (let* ((req (funcall nreq
448                                      (length (args-type-required type1))
449                                      (length (args-type-required type2))))
450                        (required (subseq res 0 req))
451                        (opt (subseq res req))
452                        (opt-last (position rest opt :test-not #'type=
453                                            :from-end t)))
454                   (if (find *empty-type* required :test #'type=)
455                       (values *empty-type* t)
456                       (values (make-values-type
457                                :required required
458                                :optional (if opt-last
459                                              (subseq opt 0 (1+ opt-last))
460                                              ())
461                                ;; MNA fix-instance-typep-call patch
462                                :rest (if (eq rest default-type) nil rest))
463                               (and rest-exact res-exact)))))))))
464       (funcall operation type1 type2)))
465
466 ;;; Do a union or intersection operation on types that might be values
467 ;;; types. The result is optimized for utility rather than exactness,
468 ;;; but it is guaranteed that it will be no smaller (more restrictive)
469 ;;; than the precise result.
470 ;;;
471 ;;; The return convention seems to be analogous to
472 ;;; TYPES-INTERSECT. -- WHN 19990910.
473 (defun-cached (values-type-union :hash-function type-cache-hash
474                                  :hash-bits 8
475                                  :default nil
476                                  :init-wrapper !cold-init-forms)
477               ((type1 eq) (type2 eq))
478   (declare (type ctype type1 type2))
479   (cond ((or (eq type1 *wild-type*) (eq type2 *wild-type*)) *wild-type*)
480         ((eq type1 *empty-type*) type2)
481         ((eq type2 *empty-type*) type1)
482         (t
483           ;;; MNA: fix-instance-typep-call patch
484          (values (args-type-op type1 type2 #'type-union #'min *empty-type*)))))
485 ;;;
486 (defun-cached (values-type-intersection :hash-function type-cache-hash
487                                         :hash-bits 8
488                                         :values 2
489                                         :default (values nil :empty)
490                                         :init-wrapper !cold-init-forms)
491               ((type1 eq) (type2 eq))
492   (declare (type ctype type1 type2))
493   (cond ((eq type1 *wild-type*) (values type2 t))
494         ((eq type2 *wild-type*) (values type1 t))
495         (t
496          (args-type-op type1 type2 #'type-intersection #'max (specifier-type 'null)))))
497
498 ;;; This is like TYPES-INTERSECT, except that it sort of works on
499 ;;; VALUES types. Note that due to the semantics of
500 ;;; VALUES-TYPE-INTERSECTION, this might return (VALUES T T) when
501 ;;; there isn't really any intersection (?).
502 ;;;
503 ;;; The return convention seems to be analogous to
504 ;;; TYPES-INTERSECT. -- WHN 19990910.
505 (defun values-types-intersect (type1 type2)
506   (cond ((or (eq type1 *empty-type*) (eq type2 *empty-type*))
507          (values 't t))
508         ((or (values-type-p type1) (values-type-p type2))
509          (multiple-value-bind (res win) (values-type-intersection type1 type2)
510            (values (not (eq res *empty-type*))
511                    win)))
512         (t
513          (types-intersect type1 type2))))
514
515 ;;; a SUBTYPEP-like operation that can be used on any types, including
516 ;;; VALUES types
517 (defun-cached (values-subtypep :hash-function type-cache-hash
518                                :hash-bits 8
519                                :values 2
520                                :default (values nil :empty)
521                                :init-wrapper !cold-init-forms)
522               ((type1 eq) (type2 eq))
523   (declare (type ctype type1 type2))
524   (cond ((eq type2 *wild-type*) (values t t))
525         ((eq type1 *wild-type*)
526          (values (eq type2 *universal-type*) t))
527         ((not (values-types-intersect type1 type2))
528          (values nil t))
529         (t
530          (if (or (values-type-p type1) (values-type-p type2))
531              (let ((type1 (coerce-to-values type1))
532                    (type2 (coerce-to-values type2)))
533                (multiple-value-bind (types1 rest1) (values-type-types type1)
534                  (multiple-value-bind (types2 rest2) (values-type-types type2)
535                    (cond ((< (length (values-type-required type1))
536                              (length (values-type-required type2)))
537                           (values nil t))
538                          ((< (length types1) (length types2))
539                           (values nil nil))
540                          ((or (values-type-keyp type1)
541                               (values-type-keyp type2))
542                           (values nil nil))
543                          (t
544                           (do ((t1 types1 (rest t1))
545                                (t2 types2 (rest t2)))
546                               ((null t2)
547                                (csubtypep rest1 rest2))
548                             (multiple-value-bind (res win-p)
549                                 (csubtypep (first t1) (first t2))
550                               (unless win-p
551                                 (return (values nil nil)))
552                               (unless res
553                                 (return (values nil t))))))))))
554              (csubtypep type1 type2)))))
555 \f
556 ;;;; type method interfaces
557
558 ;;; like SUBTYPEP, only works on CTYPE structures
559 (defun-cached (csubtypep :hash-function type-cache-hash
560                          :hash-bits 8
561                          :values 2
562                          :default (values nil :empty)
563                          :init-wrapper !cold-init-forms)
564               ((type1 eq) (type2 eq))
565   (declare (type ctype type1 type2))
566   (cond ((or (eq type1 type2)
567              (eq type1 *empty-type*)
568              (eq type2 *wild-type*))
569          (values t t))
570         ((or (eq type1 *wild-type*)
571              (eq type2 *empty-type*))
572          (values nil t))
573         (t
574          (!invoke-type-method :simple-subtypep :complex-subtypep-arg2
575                               type1 type2
576                               :complex-arg1 :complex-subtypep-arg1))))
577
578 ;;; Just parse the type specifiers and call CSUBTYPE.
579 (defun sb!xc:subtypep (type1 type2)
580   #!+sb-doc
581   "Return two values indicating the relationship between type1 and type2.
582   If values are T and T, type1 definitely is a subtype of type2.
583   If values are NIL and T, type1 definitely is not a subtype of type2.
584   If values are NIL and NIL, it couldn't be determined."
585   (csubtypep (specifier-type type1) (specifier-type type2)))
586
587 ;;; If two types are definitely equivalent, return true. The second
588 ;;; value indicates whether the first value is definitely correct.
589 ;;; This should only fail in the presence of HAIRY types.
590 (defun-cached (type= :hash-function type-cache-hash
591                      :hash-bits 8
592                      :values 2
593                      :default (values nil :empty)
594                      :init-wrapper !cold-init-forms)
595               ((type1 eq) (type2 eq))
596   (declare (type ctype type1 type2))
597   (if (eq type1 type2)
598       (values t t)
599       (!invoke-type-method :simple-= :complex-= type1 type2)))
600
601 ;;; Not exactly the negation of TYPE=, since when the relationship is
602 ;;; uncertain, we still return NIL, NIL. This is useful in cases where
603 ;;; the conservative assumption is =.
604 (defun type/= (type1 type2)
605   (declare (type ctype type1 type2))
606   (multiple-value-bind (res win) (type= type1 type2)
607     (if win
608         (values (not res) t)
609         (values nil nil))))
610
611 ;;; Find a type which includes both types. Any inexactness is
612 ;;; represented by the fuzzy element types; we return a single value
613 ;;; that is precise to the best of our knowledge. This result is
614 ;;; simplified into the canonical form, thus is not a UNION type
615 ;;; unless there is no other way to represent the result.
616 (defun-cached (type-union :hash-function type-cache-hash
617                           :hash-bits 8
618                           :init-wrapper !cold-init-forms)
619               ((type1 eq) (type2 eq))
620   (declare (type ctype type1 type2))
621   (if (eq type1 type2)
622       type1
623       (let ((res (!invoke-type-method :simple-union :complex-union
624                                       type1 type2
625                                       :default :vanilla)))
626         (cond ((eq res :vanilla)
627                (or (vanilla-union type1 type2)
628                    (make-union-type (list type1 type2))))
629               (res)
630               (t
631                (make-union-type (list type1 type2)))))))
632
633 ;;; Return as restrictive a type as we can discover that is no more
634 ;;; restrictive than the intersection of Type1 and Type2. The second
635 ;;; value is true if the result is exact. At worst, we randomly return
636 ;;; one of the arguments as the first value (trying not to return a
637 ;;; hairy type).
638 (defun-cached (type-intersection :hash-function type-cache-hash
639                                  :hash-bits 8
640                                  :values 2
641                                  :default (values nil :empty)
642                                  :init-wrapper !cold-init-forms)
643               ((type1 eq) (type2 eq))
644   (declare (type ctype type1 type2))
645   (if (eq type1 type2)
646       (values type1 t)
647       (!invoke-type-method :simple-intersection :complex-intersection
648                            type1 type2
649                            :default (values *empty-type* t))))
650
651 ;;; The first value is true unless the types don't intersect. The
652 ;;; second value is true if the first value is definitely correct. NIL
653 ;;; is considered to intersect with any type. If T is a subtype of
654 ;;; either type, then we also return T, T. This way we consider hairy
655 ;;; types to intersect with T.
656 (defun types-intersect (type1 type2)
657   (declare (type ctype type1 type2))
658   (if (or (eq type1 *empty-type*) (eq type2 *empty-type*))
659       (values t t)
660       (multiple-value-bind (val winp) (type-intersection type1 type2)
661         (cond ((not winp)
662                (if (or (csubtypep *universal-type* type1)
663                        (csubtypep *universal-type* type2))
664                    (values t t)
665                    (values t nil)))
666               ((eq val *empty-type*) (values nil t))
667               (t (values t t))))))
668
669 ;;; Return a Common Lisp type specifier corresponding to the TYPE
670 ;;; object.
671 (defun type-specifier (type)
672   (declare (type ctype type))
673   (funcall (type-class-unparse (type-class-info type)) type))
674
675 ;;; (VALUES-SPECIFIER-TYPE and SPECIFIER-TYPE moved from here to
676 ;;; early-type.lisp by WHN ca. 19990201.)
677
678 ;;; Take a list of type specifiers, computing the translation of each
679 ;;; specifier and defining it as a builtin type.
680 (declaim (ftype (function (list) (values)) precompute-types))
681 (defun precompute-types (specs)
682   (dolist (spec specs)
683     (let ((res (specifier-type spec)))
684       (unless (unknown-type-p res)
685         (setf (info :type :builtin spec) res)
686         (setf (info :type :kind spec) :primitive))))
687   (values))
688 \f
689 ;;;; built-in types
690
691 (!define-type-class named)
692
693 (defvar *wild-type*)
694 (defvar *empty-type*)
695 (defvar *universal-type*)
696
697 (!cold-init-forms
698  (macrolet ((frob (name var)
699               `(progn
700                  (setq ,var (make-named-type :name ',name))
701                  (setf (info :type :kind ',name) :primitive)
702                  (setf (info :type :builtin ',name) ,var))))
703    ;; KLUDGE: In ANSI, * isn't really the name of a type, it's just a
704    ;; special symbol which can be stuck in some places where an
705    ;; ordinary type can go, e.g. (ARRAY * 1) instead of (ARRAY T 1).
706    ;; At some point, in order to become more standard, we should
707    ;; convert all the classic CMU CL legacy *s and *WILD-TYPE*s into
708    ;; Ts and *UNIVERSAL-TYPE*s.
709    (frob * *wild-type*)
710    (frob nil *empty-type*)
711    (frob t *universal-type*)))
712
713 (!define-type-method (named :simple-=) (type1 type2)
714   (values (eq type1 type2) t))
715
716 (!define-type-method (named :simple-subtypep) (type1 type2)
717   (values (or (eq type1 *empty-type*) (eq type2 *wild-type*)) t))
718
719 (!define-type-method (named :complex-subtypep-arg1) (type1 type2)
720   (assert (not (hairy-type-p type2)))
721   (values (eq type1 *empty-type*) t))
722
723 (!define-type-method (named :complex-subtypep-arg2) (type1 type2)
724   (if (hairy-type-p type1)
725       (values nil nil)
726       (values (not (eq type2 *empty-type*)) t)))
727
728 (!define-type-method (named :complex-intersection) (type1 type2)
729   (vanilla-intersection type1 type2))
730
731 (!define-type-method (named :unparse) (x)
732   (named-type-name x))
733 \f
734 ;;;; hairy and unknown types
735
736 (!define-type-method (hairy :unparse) (x) (hairy-type-specifier x))
737
738 (!define-type-method (hairy :simple-subtypep) (type1 type2)
739   (let ((hairy-spec1 (hairy-type-specifier type1))
740         (hairy-spec2 (hairy-type-specifier type2)))
741     (cond ((and (consp hairy-spec1) (eq (car hairy-spec1) 'not)
742                 (consp hairy-spec2) (eq (car hairy-spec2) 'not))
743            (csubtypep (specifier-type (cadr hairy-spec2))
744                       (specifier-type (cadr hairy-spec1))))
745           ((equal hairy-spec1 hairy-spec2)
746            (values t t))
747           (t
748            (values nil nil)))))
749
750 (!define-type-method (hairy :complex-subtypep-arg2) (type1 type2)
751   (let ((hairy-spec (hairy-type-specifier type2)))
752     (cond ((and (consp hairy-spec) (eq (car hairy-spec) 'not))
753            (multiple-value-bind (val win)
754                (type-intersection type1 (specifier-type (cadr hairy-spec)))
755              (if win
756                  (values (eq val *empty-type*) t)
757                  (values nil nil))))
758           (t
759            (values nil nil)))))
760
761 (!define-type-method (hairy :complex-subtypep-arg1 :complex-=) (type1 type2)
762   (declare (ignore type1 type2))
763   (values nil nil))
764
765 (!define-type-method (hairy :simple-intersection :complex-intersection)
766                     (type1 type2)
767   (declare (ignore type2))
768   (values type1 nil))
769
770 (!define-type-method (hairy :complex-union) (type1 type2)
771   (make-union-type (list type1 type2)))
772
773 (!define-type-method (hairy :simple-=) (type1 type2)
774   (if (equal (hairy-type-specifier type1)
775              (hairy-type-specifier type2))
776       (values t t)
777       (values nil nil)))
778
779 (!def-type-translator not (&whole whole type)
780   (declare (ignore type))
781   (make-hairy-type :specifier whole))
782
783 (!def-type-translator satisfies (&whole whole fun)
784   (declare (ignore fun))
785   (make-hairy-type :specifier whole))
786 \f
787 ;;;; numeric types
788
789 ;;; A list of all the float formats, in order of decreasing precision.
790 (eval-when (:compile-toplevel :load-toplevel :execute)
791   (defparameter *float-formats*
792     '(long-float double-float single-float short-float)))
793
794 ;;; The type of a float format.
795 (deftype float-format () `(member ,@*float-formats*))
796
797 #!+negative-zero-is-not-zero
798 (defun make-numeric-type (&key class format (complexp :real) low high
799                                enumerable)
800   (flet ((canonicalise-low-bound (x)
801            ;; Canonicalise a low bound of (-0.0) to 0.0.
802            (if (and (consp x) (floatp (car x)) (zerop (car x))
803                     (minusp (float-sign (car x))))
804                (float 0.0 (car x))
805                x))
806          (canonicalise-high-bound (x)
807            ;; Canonicalise a high bound of (+0.0) to -0.0.
808            (if (and (consp x) (floatp (car x)) (zerop (car x))
809                     (plusp (float-sign (car x))))
810                (float -0.0 (car x))
811                x)))
812     (%make-numeric-type :class class
813                         :format format
814                         :complexp complexp
815                         :low (canonicalise-low-bound low)
816                         :high (canonicalise-high-bound high)
817                         :enumerable enumerable)))
818
819 (!define-type-class number)
820
821 (!define-type-method (number :simple-=) (type1 type2)
822   (values
823    (and (eq (numeric-type-class type1) (numeric-type-class type2))
824         (eq (numeric-type-format type1) (numeric-type-format type2))
825         (eq (numeric-type-complexp type1) (numeric-type-complexp type2))
826         (equal (numeric-type-low type1) (numeric-type-low type2))
827         (equal (numeric-type-high type1) (numeric-type-high type2)))
828    t))
829
830 (!define-type-method (number :unparse) (type)
831   (let* ((complexp (numeric-type-complexp type))
832          (low (numeric-type-low type))
833          (high (numeric-type-high type))
834          (base (case (numeric-type-class type)
835                  (integer 'integer)
836                  (rational 'rational)
837                  (float (or (numeric-type-format type) 'float))
838                  (t 'real))))
839     (let ((base+bounds
840            (cond ((and (eq base 'integer) high low)
841                   (let ((high-count (logcount high))
842                         (high-length (integer-length high)))
843                     (cond ((= low 0)
844                            (cond ((= high 0) '(integer 0 0))
845                                  ((= high 1) 'bit)
846                                  ((and (= high-count high-length)
847                                        (plusp high-length))
848                                   `(unsigned-byte ,high-length))
849                                  (t
850                                   `(mod ,(1+ high)))))
851                           ((and (= low sb!vm:*target-most-negative-fixnum*)
852                                 (= high sb!vm:*target-most-positive-fixnum*))
853                            'fixnum)
854                           ((and (= low (lognot high))
855                                 (= high-count high-length)
856                                 (> high-count 0))
857                            `(signed-byte ,(1+ high-length)))
858                           (t
859                            `(integer ,low ,high)))))
860                  (high `(,base ,(or low '*) ,high))
861                  (low
862                   (if (and (eq base 'integer) (= low 0))
863                       'unsigned-byte
864                       `(,base ,low)))
865                  (t base))))
866       (ecase complexp
867         (:real
868          base+bounds)
869         (:complex
870          (if (eq base+bounds 'real)
871              'complex
872              `(complex ,base+bounds)))
873         ((nil)
874          (assert (eq base+bounds 'real))
875          'number)))))
876
877 ;;; Return true if X is "less than or equal" to Y, taking open bounds
878 ;;; into consideration. CLOSED is the predicate used to test the bound
879 ;;; on a closed interval (e.g. <=), and OPEN is the predicate used on
880 ;;; open bounds (e.g. <). Y is considered to be the outside bound, in
881 ;;; the sense that if it is infinite (NIL), then the test succeeds,
882 ;;; whereas if X is infinite, then the test fails (unless Y is also
883 ;;; infinite).
884 ;;;
885 ;;; This is for comparing bounds of the same kind, e.g. upper and
886 ;;; upper. Use NUMERIC-BOUND-TEST* for different kinds of bounds.
887 #!-negative-zero-is-not-zero
888 (defmacro numeric-bound-test (x y closed open)
889   `(cond ((not ,y) t)
890          ((not ,x) nil)
891          ((consp ,x)
892           (if (consp ,y)
893               (,closed (car ,x) (car ,y))
894               (,closed (car ,x) ,y)))
895          (t
896           (if (consp ,y)
897               (,open ,x (car ,y))
898               (,closed ,x ,y)))))
899
900 #!+negative-zero-is-not-zero
901 (defmacro numeric-bound-test-zero (op x y)
902   `(if (and (zerop ,x) (zerop ,y) (floatp ,x) (floatp ,y))
903        (,op (float-sign ,x) (float-sign ,y))
904        (,op ,x ,y)))
905
906 #!+negative-zero-is-not-zero
907 (defmacro numeric-bound-test (x y closed open)
908   `(cond ((not ,y) t)
909          ((not ,x) nil)
910          ((consp ,x)
911           (if (consp ,y)
912               (numeric-bound-test-zero ,closed (car ,x) (car ,y))
913               (numeric-bound-test-zero ,closed (car ,x) ,y)))
914          (t
915           (if (consp ,y)
916               (numeric-bound-test-zero ,open ,x (car ,y))
917               (numeric-bound-test-zero ,closed ,x ,y)))))
918
919 ;;; This is used to compare upper and lower bounds. This is different
920 ;;; from the same-bound case:
921 ;;; -- Since X = NIL is -infinity, whereas y = NIL is +infinity, we
922 ;;;    return true if *either* arg is NIL.
923 ;;; -- an open inner bound is "greater" and also squeezes the interval,
924 ;;;    causing us to use the OPEN test for those cases as well.
925 #!-negative-zero-is-not-zero
926 (defmacro numeric-bound-test* (x y closed open)
927   `(cond ((not ,y) t)
928          ((not ,x) t)
929          ((consp ,x)
930           (if (consp ,y)
931               (,open (car ,x) (car ,y))
932               (,open (car ,x) ,y)))
933          (t
934           (if (consp ,y)
935               (,open ,x (car ,y))
936               (,closed ,x ,y)))))
937
938 #!+negative-zero-is-not-zero
939 (defmacro numeric-bound-test* (x y closed open)
940   `(cond ((not ,y) t)
941          ((not ,x) t)
942          ((consp ,x)
943           (if (consp ,y)
944               (numeric-bound-test-zero ,open (car ,x) (car ,y))
945               (numeric-bound-test-zero ,open (car ,x) ,y)))
946          (t
947           (if (consp ,y)
948               (numeric-bound-test-zero ,open ,x (car ,y))
949               (numeric-bound-test-zero ,closed ,x ,y)))))
950
951 ;;; Return whichever of the numeric bounds X and Y is "maximal"
952 ;;; according to the predicates CLOSED (e.g. >=) and OPEN (e.g. >).
953 ;;; This is only meaningful for maximizing like bounds, i.e. upper and
954 ;;; upper. If MAX-P is true, then we return NIL if X or Y is NIL,
955 ;;; otherwise we return the other arg.
956 (defmacro numeric-bound-max (x y closed open max-p)
957   (once-only ((n-x x)
958               (n-y y))
959     `(cond ((not ,n-x) ,(if max-p nil n-y))
960            ((not ,n-y) ,(if max-p nil n-x))
961            ((consp ,n-x)
962             (if (consp ,n-y)
963                 (if (,closed (car ,n-x) (car ,n-y)) ,n-x ,n-y)
964                 (if (,open (car ,n-x) ,n-y) ,n-x ,n-y)))
965            (t
966             (if (consp ,n-y)
967                 (if (,open (car ,n-y) ,n-x) ,n-y ,n-x)
968                 (if (,closed ,n-y ,n-x) ,n-y ,n-x))))))
969
970 (!define-type-method (number :simple-subtypep) (type1 type2)
971   (let ((class1 (numeric-type-class type1))
972         (class2 (numeric-type-class type2))
973         (complexp2 (numeric-type-complexp type2))
974         (format2 (numeric-type-format type2))
975         (low1 (numeric-type-low type1))
976         (high1 (numeric-type-high type1))
977         (low2 (numeric-type-low type2))
978         (high2 (numeric-type-high type2)))
979     ;; If one is complex and the other isn't, they are disjoint.
980     (cond ((not (or (eq (numeric-type-complexp type1) complexp2)
981                     (null complexp2)))
982            (values nil t))
983           ;; If the classes are specified and different, the types are
984           ;; disjoint unless type2 is rational and type1 is integer.
985           ((not (or (eq class1 class2)
986                     (null class2)
987                     (and (eq class1 'integer)
988                          (eq class2 'rational))))
989            (values nil t))
990           ;; If the float formats are specified and different, the types
991           ;; are disjoint.
992           ((not (or (eq (numeric-type-format type1) format2)
993                     (null format2)))
994            (values nil t))
995           ;; Check the bounds.
996           ((and (numeric-bound-test low1 low2 >= >)
997                 (numeric-bound-test high1 high2 <= <))
998            (values t t))
999           (t
1000            (values nil t)))))
1001
1002 (!define-superclasses number ((generic-number)) !cold-init-forms)
1003
1004 ;;; If the high bound of LOW is adjacent to the low bound of HIGH,
1005 ;;; then return true, otherwise NIL.
1006 (defun numeric-types-adjacent (low high)
1007   (let ((low-bound (numeric-type-high low))
1008         (high-bound (numeric-type-low high)))
1009     (cond ((not (and low-bound high-bound)) nil)
1010           ((and (consp low-bound) (consp high-bound)) nil)
1011           ((consp low-bound)
1012            #!-negative-zero-is-not-zero
1013            (let ((low-value (car low-bound)))
1014              (or (eql low-value high-bound)
1015                  (and (eql low-value -0f0) (eql high-bound 0f0))
1016                  (and (eql low-value 0f0) (eql high-bound -0f0))
1017                  (and (eql low-value -0d0) (eql high-bound 0d0))
1018                  (and (eql low-value 0d0) (eql high-bound -0d0))))
1019            #!+negative-zero-is-not-zero
1020            (eql (car low-bound) high-bound))
1021           ((consp high-bound)
1022            #!-negative-zero-is-not-zero
1023            (let ((high-value (car high-bound)))
1024              (or (eql high-value low-bound)
1025                  (and (eql high-value -0f0) (eql low-bound 0f0))
1026                  (and (eql high-value 0f0) (eql low-bound -0f0))
1027                  (and (eql high-value -0d0) (eql low-bound 0d0))
1028                  (and (eql high-value 0d0) (eql low-bound -0d0))))
1029            #!+negative-zero-is-not-zero
1030            (eql (car high-bound) low-bound))
1031           #!+negative-zero-is-not-zero
1032           ((or (and (eql low-bound -0f0) (eql high-bound 0f0))
1033                (and (eql low-bound -0d0) (eql high-bound 0d0))))
1034           ((and (eq (numeric-type-class low) 'integer)
1035                 (eq (numeric-type-class high) 'integer))
1036            (eql (1+ low-bound) high-bound))
1037           (t
1038            nil))))
1039
1040 ;;; Return a numeric type that is a supertype for both TYPE1 and TYPE2.
1041 ;;;
1042 ;;; ### Note: we give up early to keep from dropping lots of information on
1043 ;;; the floor by returning overly general types.
1044 (!define-type-method (number :simple-union) (type1 type2)
1045   (declare (type numeric-type type1 type2))
1046   (cond ((csubtypep type1 type2) type2)
1047         ((csubtypep type2 type1) type1)
1048         (t
1049          (let ((class1 (numeric-type-class type1))
1050                (format1 (numeric-type-format type1))
1051                (complexp1 (numeric-type-complexp type1))
1052                (class2 (numeric-type-class type2))
1053                (format2 (numeric-type-format type2))
1054                (complexp2 (numeric-type-complexp type2)))
1055            (when (and (eq class1 class2)
1056                       (eq format1 format2)
1057                       (eq complexp1 complexp2)
1058                       (or (numeric-types-intersect type1 type2)
1059                           (numeric-types-adjacent type1 type2)
1060                           (numeric-types-adjacent type2 type1)))
1061              (make-numeric-type
1062               :class class1
1063               :format format1
1064               :complexp complexp1
1065               :low (numeric-bound-max (numeric-type-low type1)
1066                                       (numeric-type-low type2)
1067                                       <= < t)
1068               :high (numeric-bound-max (numeric-type-high type1)
1069                                        (numeric-type-high type2)
1070                                        >= > t)))))))
1071
1072 (!cold-init-forms
1073   (setf (info :type :kind 'number) :primitive)
1074   (setf (info :type :builtin 'number)
1075         (make-numeric-type :complexp nil)))
1076
1077 (!def-type-translator complex (&optional (spec '*))
1078   (if (eq spec '*)
1079       (make-numeric-type :complexp :complex)
1080       (let ((type (specifier-type spec)))
1081         (unless (numeric-type-p type)
1082           (error "Component type for Complex is not numeric: ~S." spec))
1083         (when (eq (numeric-type-complexp type) :complex)
1084           (error "Component type for Complex is complex: ~S." spec))
1085         (let ((res (copy-numeric-type type)))
1086           (setf (numeric-type-complexp res) :complex)
1087           res))))
1088
1089 ;;; If X is *, return NIL, otherwise return the bound, which must be a
1090 ;;; member of TYPE or a one-element list of a member of TYPE.
1091 #!-sb-fluid (declaim (inline canonicalized-bound))
1092 (defun canonicalized-bound (bound type)
1093   (cond ((eq bound '*) nil)
1094         ((or (sb!xc:typep bound type)
1095              (and (consp bound)
1096                   (sb!xc:typep (car bound) type)
1097                   (null (cdr bound))))
1098           bound)
1099         (t
1100          (error "Bound is not ~S, a ~S or a list of a ~S: ~S"
1101                 '*
1102                 type
1103                 type
1104                 bound))))
1105
1106 (!def-type-translator integer (&optional (low '*) (high '*))
1107   (let* ((l (canonicalized-bound low 'integer))
1108          (lb (if (consp l) (1+ (car l)) l))
1109          (h (canonicalized-bound high 'integer))
1110          (hb (if (consp h) (1- (car h)) h)))
1111     (when (and hb lb (< hb lb))
1112       (error "Lower bound ~S is greater than upper bound ~S." l h))
1113     (make-numeric-type :class 'integer
1114                        :complexp :real
1115                        :enumerable (not (null (and l h)))
1116                        :low lb
1117                        :high hb)))
1118
1119 (defmacro def-bounded-type (type class format)
1120   `(!def-type-translator ,type (&optional (low '*) (high '*))
1121      (let ((lb (canonicalized-bound low ',type))
1122            (hb (canonicalized-bound high ',type)))
1123        (unless (numeric-bound-test* lb hb <= <)
1124          (error "Lower bound ~S is not less than upper bound ~S." low high))
1125        (make-numeric-type :class ',class :format ',format :low lb :high hb))))
1126
1127 (def-bounded-type rational rational nil)
1128 (def-bounded-type float float nil)
1129 (def-bounded-type real nil nil)
1130
1131 (defmacro define-float-format (f)
1132   `(def-bounded-type ,f float ,f))
1133
1134 (define-float-format short-float)
1135 (define-float-format single-float)
1136 (define-float-format double-float)
1137 (define-float-format long-float)
1138
1139 (defun numeric-types-intersect (type1 type2)
1140   (declare (type numeric-type type1 type2))
1141   (let* ((class1 (numeric-type-class type1))
1142          (class2 (numeric-type-class type2))
1143          (complexp1 (numeric-type-complexp type1))
1144          (complexp2 (numeric-type-complexp type2))
1145          (format1 (numeric-type-format type1))
1146          (format2 (numeric-type-format type2))
1147          (low1 (numeric-type-low type1))
1148          (high1 (numeric-type-high type1))
1149          (low2 (numeric-type-low type2))
1150          (high2 (numeric-type-high type2)))
1151     ;; If one is complex and the other isn't, then they are disjoint.
1152     (cond ((not (or (eq complexp1 complexp2)
1153                     (null complexp1) (null complexp2)))
1154            nil)
1155           ;; If either type is a float, then the other must either be
1156           ;; specified to be a float or unspecified. Otherwise, they
1157           ;; are disjoint.
1158           ((and (eq class1 'float)
1159                 (not (member class2 '(float nil)))) nil)
1160           ((and (eq class2 'float)
1161                 (not (member class1 '(float nil)))) nil)
1162           ;; If the float formats are specified and different, the
1163           ;; types are disjoint.
1164           ((not (or (eq format1 format2) (null format1) (null format2)))
1165            nil)
1166           (t
1167            ;; Check the bounds. This is a bit odd because we must
1168            ;; always have the outer bound of the interval as the
1169            ;; second arg.
1170            (if (numeric-bound-test high1 high2 <= <)
1171                (or (and (numeric-bound-test low1 low2 >= >)
1172                         (numeric-bound-test* low1 high2 <= <))
1173                    (and (numeric-bound-test low2 low1 >= >)
1174                         (numeric-bound-test* low2 high1 <= <)))
1175                (or (and (numeric-bound-test* low2 high1 <= <)
1176                         (numeric-bound-test low2 low1 >= >))
1177                    (and (numeric-bound-test high2 high1 <= <)
1178                         (numeric-bound-test* high2 low1 >= >))))))))
1179
1180 ;;; Take the numeric bound X and convert it into something that can be
1181 ;;; used as a bound in a numeric type with the specified CLASS and
1182 ;;; FORMAT. If UP-P is true, then we round up as needed, otherwise we
1183 ;;; round down. UP-P true implies that X is a lower bound, i.e. (N) > N.
1184 ;;;
1185 ;;; This is used by NUMERIC-TYPE-INTERSECTION to mash the bound into
1186 ;;; the appropriate type number. X may only be a float when CLASS is
1187 ;;; FLOAT.
1188 ;;;
1189 ;;; ### Note: it is possible for the coercion to a float to overflow
1190 ;;; or underflow. This happens when the bound doesn't fit in the
1191 ;;; specified format. In this case, we should really return the
1192 ;;; appropriate {Most | Least}-{Positive | Negative}-XXX-Float float
1193 ;;; of desired format. But these conditions aren't currently signalled
1194 ;;; in any useful way.
1195 ;;;
1196 ;;; Also, when converting an open rational bound into a float we
1197 ;;; should probably convert it to a closed bound of the closest float
1198 ;;; in the specified format. KLUDGE: In general, open float bounds are
1199 ;;; screwed up. -- (comment from original CMU CL)
1200 (defun round-numeric-bound (x class format up-p)
1201   (if x
1202       (let ((cx (if (consp x) (car x) x)))
1203         (ecase class
1204           ((nil rational) x)
1205           (integer
1206            (if (and (consp x) (integerp cx))
1207                (if up-p (1+ cx) (1- cx))
1208                (if up-p (ceiling cx) (floor cx))))
1209           (float
1210            (let ((res (if format (coerce cx format) (float cx))))
1211              (if (consp x) (list res) res)))))
1212       nil))
1213
1214 ;;; Handle the case of TYPE-INTERSECTION on two numeric types. We use
1215 ;;; TYPES-INTERSECT to throw out the case of types with no
1216 ;;; intersection. If an attribute in TYPE1 is unspecified, then we use
1217 ;;; TYPE2's attribute, which must be at least as restrictive. If the
1218 ;;; types intersect, then the only attributes that can be specified
1219 ;;; and different are the class and the bounds.
1220 ;;;
1221 ;;; When the class differs, we use the more restrictive class. The
1222 ;;; only interesting case is RATIONAL/INTEGER, since RATIONAL includes
1223 ;;; INTEGER.
1224 ;;;
1225 ;;; We make the result lower (upper) bound the maximum (minimum) of
1226 ;;; the argument lower (upper) bounds. We convert the bounds into the
1227 ;;; appropriate numeric type before maximizing. This avoids possible
1228 ;;; confusion due to mixed-type comparisons (but I think the result is
1229 ;;; the same).
1230 (!define-type-method (number :simple-intersection) (type1 type2)
1231   (declare (type numeric-type type1 type2))
1232   (if (numeric-types-intersect type1 type2)
1233       (let* ((class1 (numeric-type-class type1))
1234              (class2 (numeric-type-class type2))
1235              (class (ecase class1
1236                       ((nil) class2)
1237                       ((integer float) class1)
1238                       (rational (if (eq class2 'integer)
1239                                        'integer
1240                                        'rational))))
1241              (format (or (numeric-type-format type1)
1242                          (numeric-type-format type2))))
1243         (values
1244          (make-numeric-type
1245           :class class
1246           :format format
1247           :complexp (or (numeric-type-complexp type1)
1248                         (numeric-type-complexp type2))
1249           :low (numeric-bound-max
1250                 (round-numeric-bound (numeric-type-low type1)
1251                                      class format t)
1252                 (round-numeric-bound (numeric-type-low type2)
1253                                      class format t)
1254                 > >= nil)
1255           :high (numeric-bound-max
1256                  (round-numeric-bound (numeric-type-high type1)
1257                                       class format nil)
1258                  (round-numeric-bound (numeric-type-high type2)
1259                                       class format nil)
1260                  < <= nil))
1261          t))
1262       (values *empty-type* t)))
1263
1264 ;;; Given two float formats, return the one with more precision. If
1265 ;;; either one is null, return NIL.
1266 (defun float-format-max (f1 f2)
1267   (when (and f1 f2)
1268     (dolist (f *float-formats* (error "bad float format: ~S" f1))
1269       (when (or (eq f f1) (eq f f2))
1270         (return f)))))
1271
1272 ;;; Return the result of an operation on TYPE1 and TYPE2 according to
1273 ;;; the rules of numeric contagion. This is always NUMBER, some float
1274 ;;; format (possibly complex) or RATIONAL. Due to rational
1275 ;;; canonicalization, there isn't much we can do here with integers or
1276 ;;; rational complex numbers.
1277 ;;;
1278 ;;; If either argument is not a NUMERIC-TYPE, then return NUMBER. This
1279 ;;; is useful mainly for allowing types that are technically numbers,
1280 ;;; but not a NUMERIC-TYPE.
1281 (defun numeric-contagion (type1 type2)
1282   (if (and (numeric-type-p type1) (numeric-type-p type2))
1283       (let ((class1 (numeric-type-class type1))
1284             (class2 (numeric-type-class type2))
1285             (format1 (numeric-type-format type1))
1286             (format2 (numeric-type-format type2))
1287             (complexp1 (numeric-type-complexp type1))
1288             (complexp2 (numeric-type-complexp type2)))
1289         (cond ((or (null complexp1)
1290                    (null complexp2))
1291                (specifier-type 'number))
1292               ((eq class1 'float)
1293                (make-numeric-type
1294                 :class 'float
1295                 :format (ecase class2
1296                           (float (float-format-max format1 format2))
1297                           ((integer rational) format1)
1298                           ((nil)
1299                            ;; A double-float with any real number is a
1300                            ;; double-float.
1301                            #!-long-float
1302                            (if (eq format1 'double-float)
1303                              'double-float
1304                              nil)
1305                            ;; A long-float with any real number is a
1306                            ;; long-float.
1307                            #!+long-float
1308                            (if (eq format1 'long-float)
1309                              'long-float
1310                              nil)))
1311                 :complexp (if (or (eq complexp1 :complex)
1312                                   (eq complexp2 :complex))
1313                               :complex
1314                               :real)))
1315               ((eq class2 'float) (numeric-contagion type2 type1))
1316               ((and (eq complexp1 :real) (eq complexp2 :real))
1317                (make-numeric-type
1318                 :class (and class1 class2 'rational)
1319                 :complexp :real))
1320               (t
1321                (specifier-type 'number))))
1322       (specifier-type 'number)))
1323 \f
1324 ;;;; array types
1325
1326 (!define-type-class array)
1327
1328 ;;; What this does depends on the setting of the
1329 ;;; *USE-IMPLEMENTATION-TYPES* switch. If true, return the specialized
1330 ;;; element type, otherwise return the original element type.
1331 (defun specialized-element-type-maybe (type)
1332   (declare (type array-type type))
1333   (if *use-implementation-types*
1334       (array-type-specialized-element-type type)
1335       (array-type-element-type type)))
1336
1337 (!define-type-method (array :simple-=) (type1 type2)
1338   (values (and (equal (array-type-dimensions type1)
1339                       (array-type-dimensions type2))
1340                (eq (array-type-complexp type1)
1341                    (array-type-complexp type2))
1342                (type= (specialized-element-type-maybe type1)
1343                       (specialized-element-type-maybe type2)))
1344           t))
1345
1346 (!define-type-method (array :unparse) (type)
1347   (let ((dims (array-type-dimensions type))
1348         (eltype (type-specifier (array-type-element-type type)))
1349         (complexp (array-type-complexp type)))
1350     (cond ((eq dims '*)
1351            (if (eq eltype '*)
1352                (if complexp 'array 'simple-array)
1353                (if complexp `(array ,eltype) `(simple-array ,eltype))))
1354           ((= (length dims) 1)
1355            (if complexp
1356                (if (eq (car dims) '*)
1357                    (case eltype
1358                      (bit 'bit-vector)
1359                      (base-char 'base-string)
1360                      (character 'string)
1361                      (* 'vector)
1362                      (t `(vector ,eltype)))
1363                    (case eltype
1364                      (bit `(bit-vector ,(car dims)))
1365                      (base-char `(base-string ,(car dims)))
1366                      (character `(string ,(car dims)))
1367                      (t `(vector ,eltype ,(car dims)))))
1368                (if (eq (car dims) '*)
1369                    (case eltype
1370                      (bit 'simple-bit-vector)
1371                      (base-char 'simple-base-string)
1372                      (character 'simple-string)
1373                      ((t) 'simple-vector)
1374                      (t `(simple-array ,eltype (*))))
1375                    (case eltype
1376                      (bit `(simple-bit-vector ,(car dims)))
1377                      (base-char `(simple-base-string ,(car dims)))
1378                      (character `(simple-string ,(car dims)))
1379                      ((t) `(simple-vector ,(car dims)))
1380                      (t `(simple-array ,eltype ,dims))))))
1381           (t
1382            (if complexp
1383                `(array ,eltype ,dims)
1384                `(simple-array ,eltype ,dims))))))
1385
1386 (!define-type-method (array :simple-subtypep) (type1 type2)
1387   (let ((dims1 (array-type-dimensions type1))
1388         (dims2 (array-type-dimensions type2))
1389         (complexp2 (array-type-complexp type2)))
1390     ;; See whether dimensions are compatible.
1391     (cond ((not (or (eq dims2 '*)
1392                     (and (not (eq dims1 '*))
1393                          ;; (sbcl-0.6.4 has trouble figuring out that
1394                          ;; DIMS1 and DIMS2 must be lists at this
1395                          ;; point, and knowing that is important to
1396                          ;; compiling EVERY efficiently.)
1397                          (= (length (the list dims1))
1398                             (length (the list dims2)))
1399                          (every (lambda (x y)
1400                                   (or (eq y '*) (eql x y)))
1401                                 (the list dims1)
1402                                 (the list dims2)))))
1403            (values nil t))
1404           ;; See whether complexpness is compatible.
1405           ((not (or (eq complexp2 :maybe)
1406                     (eq (array-type-complexp type1) complexp2)))
1407            (values nil t))
1408           ;; If the TYPE2 eltype is wild, we win. Otherwise, the types
1409           ;; must be identical.
1410           ((or (eq (array-type-element-type type2) *wild-type*)
1411                (type= (specialized-element-type-maybe type1)
1412                       (specialized-element-type-maybe type2)))
1413            (values t t))
1414           (t
1415            (values nil t)))))
1416
1417 (!define-superclasses array
1418   ((string string)
1419    (vector vector)
1420    (array))
1421   !cold-init-forms)
1422
1423 (defun array-types-intersect (type1 type2)
1424   (declare (type array-type type1 type2))
1425   (let ((dims1 (array-type-dimensions type1))
1426         (dims2 (array-type-dimensions type2))
1427         (complexp1 (array-type-complexp type1))
1428         (complexp2 (array-type-complexp type2)))
1429     ;; See whether dimensions are compatible.
1430     (cond ((not (or (eq dims1 '*) (eq dims2 '*)
1431                     (and (= (length dims1) (length dims2))
1432                          (every #'(lambda (x y)
1433                                     (or (eq x '*) (eq y '*) (= x y)))
1434                                 dims1 dims2))))
1435            (values nil t))
1436           ;; See whether complexpness is compatible.
1437           ((not (or (eq complexp1 :maybe)
1438                     (eq complexp2 :maybe)
1439                     (eq complexp1 complexp2)))
1440            (values nil t))
1441           ;; If either element type is wild, then they intersect.
1442           ;; Otherwise, the types must be identical.
1443           ((or (eq (array-type-element-type type1) *wild-type*)
1444                (eq (array-type-element-type type2) *wild-type*)
1445                (type= (specialized-element-type-maybe type1)
1446                       (specialized-element-type-maybe type2)))
1447
1448            (values t t))
1449           (t
1450            (values nil t)))))
1451
1452 (!define-type-method (array :simple-intersection) (type1 type2)
1453   (declare (type array-type type1 type2))
1454   (if (array-types-intersect type1 type2)
1455       (let ((dims1 (array-type-dimensions type1))
1456             (dims2 (array-type-dimensions type2))
1457             (complexp1 (array-type-complexp type1))
1458             (complexp2 (array-type-complexp type2))
1459             (eltype1 (array-type-element-type type1))
1460             (eltype2 (array-type-element-type type2)))
1461         (values
1462          (specialize-array-type
1463           (make-array-type
1464            :dimensions (cond ((eq dims1 '*) dims2)
1465                              ((eq dims2 '*) dims1)
1466                              (t
1467                               (mapcar (lambda (x y) (if (eq x '*) y x))
1468                                       dims1 dims2)))
1469            :complexp (if (eq complexp1 :maybe) complexp2 complexp1)
1470            :element-type (if (eq eltype1 *wild-type*) eltype2 eltype1)))
1471          t))
1472       (values *empty-type* t)))
1473
1474 ;;; Check a supplied dimension list to determine whether it is legal,
1475 ;;; and return it in canonical form (as either '* or a list).
1476 (defun canonical-array-dimensions (dims)
1477   (typecase dims
1478     ((member *) dims)
1479     (integer
1480      (when (minusp dims)
1481        (error "Arrays can't have a negative number of dimensions: ~S" dims))
1482      (when (>= dims sb!xc:array-rank-limit)
1483        (error "array type with too many dimensions: ~S" dims))
1484      (make-list dims :initial-element '*))
1485     (list
1486      (when (>= (length dims) sb!xc:array-rank-limit)
1487        (error "array type with too many dimensions: ~S" dims))
1488      (dolist (dim dims)
1489        (unless (eq dim '*)
1490          (unless (and (integerp dim)
1491                       (>= dim 0)
1492                       (< dim sb!xc:array-dimension-limit))
1493            (error "bad dimension in array type: ~S" dim))))
1494      dims)
1495     (t
1496      (error "Array dimensions is not a list, integer or *:~%  ~S" dims))))
1497 \f
1498 ;;;; MEMBER types
1499
1500 (!define-type-class member)
1501
1502 (!define-type-method (member :unparse) (type)
1503   (let ((members (member-type-members type)))
1504     (if (equal members '(nil))
1505         'null
1506         `(member ,@members))))
1507
1508 (!define-type-method (member :simple-subtypep) (type1 type2)
1509   (values (subsetp (member-type-members type1) (member-type-members type2))
1510           t))
1511
1512 (!define-type-method (member :complex-subtypep-arg1) (type1 type2)
1513   (block PUNT
1514     (values (every-type-op ctypep type2 (member-type-members type1)
1515                            :list-first t)
1516             t)))
1517
1518 ;;; We punt if the odd type is enumerable and intersects with the
1519 ;;; MEMBER type. If not enumerable, then it is definitely not a
1520 ;;; subtype of the MEMBER type.
1521 (!define-type-method (member :complex-subtypep-arg2) (type1 type2)
1522   (cond ((not (type-enumerable type1)) (values nil t))
1523         ((types-intersect type1 type2) (values nil nil))
1524         (t
1525          (values nil t))))
1526
1527 (!define-type-method (member :simple-intersection) (type1 type2)
1528   (let ((mem1 (member-type-members type1))
1529         (mem2 (member-type-members type2)))
1530     (values (cond ((subsetp mem1 mem2) type1)
1531                   ((subsetp mem2 mem1) type2)
1532                   (t
1533                    (let ((res (intersection mem1 mem2)))
1534                      (if res
1535                          (make-member-type :members res)
1536                          *empty-type*))))
1537             t)))
1538
1539 (!define-type-method (member :complex-intersection) (type1 type2)
1540   (block PUNT
1541     (collect ((members))
1542       (let ((mem2 (member-type-members type2)))
1543         (dolist (member mem2)
1544           (multiple-value-bind (val win) (ctypep member type1)
1545             (unless win
1546               (return-from PUNT (values type2 nil)))
1547             (when val (members member))))
1548
1549         (values (cond ((subsetp mem2 (members)) type2)
1550                       ((null (members)) *empty-type*)
1551                       (t
1552                        (make-member-type :members (members))))
1553                 t)))))
1554
1555 ;;; We don't need a :COMPLEX-UNION, since the only interesting case is a union
1556 ;;; type, and the member/union interaction is handled by the union type
1557 ;;; method.
1558 (!define-type-method (member :simple-union) (type1 type2)
1559   (let ((mem1 (member-type-members type1))
1560         (mem2 (member-type-members type2)))
1561     (cond ((subsetp mem1 mem2) type2)
1562           ((subsetp mem2 mem1) type1)
1563           (t
1564            (make-member-type :members (union mem1 mem2))))))
1565
1566 (!define-type-method (member :simple-=) (type1 type2)
1567   (let ((mem1 (member-type-members type1))
1568         (mem2 (member-type-members type2)))
1569     (values (and (subsetp mem1 mem2) (subsetp mem2 mem1))
1570             t)))
1571
1572 (!define-type-method (member :complex-=) (type1 type2)
1573   (if (type-enumerable type1)
1574       (multiple-value-bind (val win) (csubtypep type2 type1)
1575         (if (or val (not win))
1576             (values nil nil)
1577             (values nil t)))
1578       (values nil t)))
1579
1580 (!def-type-translator member (&rest members)
1581   (if members
1582     (make-member-type :members (remove-duplicates members))
1583     *empty-type*))
1584 \f
1585 ;;;; union types
1586
1587 ;;; Make a union type from the specifier types, setting ENUMERABLE in
1588 ;;; the result if all are enumerable.
1589 (defun make-union-type (types)
1590   (declare (list types))
1591   (%make-union-type (every #'type-enumerable types) types))
1592
1593 (!define-type-class union)
1594
1595 ;;; If LIST, then return that, otherwise the OR of the component types.
1596 (!define-type-method (union :unparse) (type)
1597   (declare (type ctype type))
1598   (if (type= type (specifier-type 'list))
1599       'list
1600       `(or ,@(mapcar #'type-specifier (union-type-types type)))))
1601
1602 ;;; Two union types are equal if every type in one is equal to some
1603 ;;; type in the other.
1604 (!define-type-method (union :simple-=) (type1 type2)
1605   (block PUNT
1606     (let ((types1 (union-type-types type1))
1607           (types2 (union-type-types type2)))
1608       (values (and (dolist (type1 types1 t)
1609                      (unless (any-type-op type= type1 types2)
1610                        (return nil)))
1611                    (dolist (type2 types2 t)
1612                      (unless (any-type-op type= type2 types1)
1613                        (return nil))))
1614               t))))
1615
1616 ;;; Similarly, a union type is a subtype of another if every element
1617 ;;; of TYPE1 is a subtype of some element of TYPE2.
1618 (!define-type-method (union :simple-subtypep) (type1 type2)
1619   (block PUNT
1620     (let ((types2 (union-type-types type2)))
1621       (values (dolist (type1 (union-type-types type1) t)
1622                 (unless (any-type-op csubtypep type1 types2)
1623                   (return nil)))
1624               t))))
1625
1626 (!define-type-method (union :complex-subtypep-arg1) (type1 type2)
1627   (block PUNT
1628     (values (every-type-op csubtypep type2 (union-type-types type1)
1629                            :list-first t)
1630             t)))
1631
1632 (!define-type-method (union :complex-subtypep-arg2) (type1 type2)
1633   (block PUNT
1634     (values (any-type-op csubtypep type1 (union-type-types type2)) t)))
1635
1636 (!define-type-method (union :complex-union) (type1 type2)
1637   (let* ((class1 (type-class-info type1)))
1638     (collect ((res))
1639       (let ((this-type type1))
1640         (dolist (type (union-type-types type2)
1641                       (if (res)
1642                           (make-union-type (cons this-type (res)))
1643                           this-type))
1644           (cond ((eq (type-class-info type) class1)
1645                  (let ((union (funcall (type-class-simple-union class1)
1646                                        this-type type)))
1647                    (if union
1648                        (setq this-type union)
1649                        (res type))))
1650                 ((csubtypep type this-type))
1651                 ((csubtypep type1 type) (return type2))
1652                 (t
1653                  (res type))))))))
1654
1655 ;;; For the union of union types, we let the :COMPLEX-UNION method do
1656 ;;; the work.
1657 (!define-type-method (union :simple-union) (type1 type2)
1658   (let ((res type1))
1659     (dolist (t2 (union-type-types type2) res)
1660       (setq res (type-union res t2)))))
1661
1662 (!define-type-method (union :simple-intersection :complex-intersection)
1663                     (type1 type2)
1664   (let ((res *empty-type*)
1665         (win t))
1666     (dolist (type (union-type-types type2) (values res win))
1667       (multiple-value-bind (int w) (type-intersection type1 type)
1668         (setq res (type-union res int))
1669         (unless w (setq win nil))))))
1670
1671 (!def-type-translator or (&rest types)
1672   (reduce #'type-union
1673           (mapcar #'specifier-type types)
1674           :initial-value *empty-type*))
1675
1676 ;;; We don't actually have intersection types, since the result of
1677 ;;; reasonable type intersections is always describable as a union of
1678 ;;; simple types. If something is too hairy to fit this mold, then we
1679 ;;; make a hairy type.
1680 (!def-type-translator and (&whole spec &rest types)
1681   (let ((res *wild-type*))
1682     (dolist (type types res)
1683       (let ((ctype (specifier-type type)))
1684         (multiple-value-bind (int win) (type-intersection res ctype)
1685           (unless win
1686             (return (make-hairy-type :specifier spec)))
1687           (setq res int))))))
1688 \f
1689 ;;;; CONS types
1690
1691 (!define-type-class cons)
1692
1693 (!def-type-translator cons (&optional (car-type-spec '*) (cdr-type-spec '*))
1694   (make-cons-type (specifier-type car-type-spec)
1695                   (specifier-type cdr-type-spec)))
1696  
1697 (!define-type-method (cons :unparse) (type)
1698   (let ((car-eltype (type-specifier (cons-type-car-type type)))
1699         (cdr-eltype (type-specifier (cons-type-cdr-type type))))
1700     (if (and (member car-eltype '(t *))
1701              (member cdr-eltype '(t *)))
1702         'cons
1703         `(cons ,car-eltype ,cdr-eltype))))
1704  
1705 (!define-type-method (cons :simple-=) (type1 type2)
1706   (declare (type cons-type type1 type2))
1707   (and (type= (cons-type-car-type type1) (cons-type-car-type type2))
1708        (type= (cons-type-cdr-type type1) (cons-type-cdr-type type2))))
1709  
1710 (!define-type-method (cons :simple-subtypep) (type1 type2)
1711   (declare (type cons-type type1 type2))
1712   (multiple-value-bind (val-car win-car)
1713       (csubtypep (cons-type-car-type type1) (cons-type-car-type type2))
1714     (multiple-value-bind (val-cdr win-cdr)
1715         (csubtypep (cons-type-cdr-type type1) (cons-type-cdr-type type2))
1716       (if (and val-car val-cdr)
1717           (values t (and win-car win-cdr))
1718           (values nil (or win-car win-cdr))))))
1719  
1720 ;;; Give up if a precise type is not possible, to avoid returning
1721 ;;; overly general types.
1722 (!define-type-method (cons :simple-union) (type1 type2)
1723   (declare (type cons-type type1 type2))
1724   (let ((car-type1 (cons-type-car-type type1))
1725         (car-type2 (cons-type-car-type type2))
1726         (cdr-type1 (cons-type-cdr-type type1))
1727         (cdr-type2 (cons-type-cdr-type type2)))
1728     (cond ((type= car-type1 car-type2)
1729            (make-cons-type car-type1
1730                            (type-union cdr-type1 cdr-type2)))
1731           ((type= cdr-type1 cdr-type2)
1732            (make-cons-type (type-union cdr-type1 cdr-type2)
1733                            cdr-type1)))))
1734
1735 (!define-type-method (cons :simple-intersection) (type1 type2)
1736   (declare (type cons-type type1 type2))
1737   (multiple-value-bind (int-car win-car)
1738       (type-intersection (cons-type-car-type type1)
1739                          (cons-type-car-type type2))
1740     (multiple-value-bind (int-cdr win-cdr)
1741         (type-intersection (cons-type-cdr-type type1)
1742                            (cons-type-cdr-type type2))
1743       (values (make-cons-type int-car int-cdr)
1744               (and win-car win-cdr)))))
1745 \f
1746 ;;; Return the type that describes all objects that are in X but not
1747 ;;; in Y. If we can't determine this type, then return NIL.
1748 ;;;
1749 ;;; For now, we only are clever dealing with union and member types.
1750 ;;; If either type is not a union type, then we pretend that it is a
1751 ;;; union of just one type. What we do is remove from X all the types
1752 ;;; that are a subtype any type in Y. If any type in X intersects with
1753 ;;; a type in Y but is not a subtype, then we give up.
1754 ;;;
1755 ;;; We must also special-case any member type that appears in the
1756 ;;; union. We remove from X's members all objects that are TYPEP to Y.
1757 ;;; If Y has any members, we must be careful that none of those
1758 ;;; members are CTYPEP to any of Y's non-member types. We give up in
1759 ;;; this case, since to compute that difference we would have to break
1760 ;;; the type from X into some collection of types that represents the
1761 ;;; type without that particular element. This seems too hairy to be
1762 ;;; worthwhile, given its low utility.
1763 (defun type-difference (x y)
1764   (let ((x-types (if (union-type-p x) (union-type-types x) (list x)))
1765         (y-types (if (union-type-p y) (union-type-types y) (list y))))
1766     (collect ((res))
1767       (dolist (x-type x-types)
1768         (if (member-type-p x-type)
1769             (collect ((members))
1770               (dolist (mem (member-type-members x-type))
1771                 (multiple-value-bind (val win) (ctypep mem y)
1772                   (unless win (return-from type-difference nil))
1773                   (unless val
1774                     (members mem))))
1775               (when (members)
1776                 (res (make-member-type :members (members)))))
1777             (dolist (y-type y-types (res x-type))
1778               (multiple-value-bind (val win) (csubtypep x-type y-type)
1779                 (unless win (return-from type-difference nil))
1780                 (when val (return))
1781                 (when (types-intersect x-type y-type)
1782                   (return-from type-difference nil))))))
1783
1784       (let ((y-mem (find-if #'member-type-p y-types)))
1785         (when y-mem
1786           (let ((members (member-type-members y-mem)))
1787             (dolist (x-type x-types)
1788               (unless (member-type-p x-type)
1789                 (dolist (member members)
1790                   (multiple-value-bind (val win) (ctypep member x-type)
1791                     (when (or (not win) val)
1792                       (return-from type-difference nil)))))))))
1793
1794       (cond ((null (res)) *empty-type*)
1795             ((null (rest (res))) (first (res)))
1796             (t
1797              (make-union-type (res)))))))
1798 \f
1799 (!def-type-translator array (&optional (element-type '*)
1800                                       (dimensions '*))
1801   (specialize-array-type
1802    (make-array-type :dimensions (canonical-array-dimensions dimensions)
1803                     :element-type (specifier-type element-type))))
1804
1805 (!def-type-translator simple-array (&optional (element-type '*)
1806                                              (dimensions '*))
1807   (specialize-array-type
1808    (make-array-type :dimensions (canonical-array-dimensions dimensions)
1809                     :element-type (specifier-type element-type)
1810                     :complexp nil)))
1811 \f
1812 (!defun-from-collected-cold-init-forms !late-type-cold-init)