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