1.0.32.36: (subtypep 'symbol 'keyword) must be NIL, T
[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   (let ((specifier (hairy-type-specifier type2)))
1353     (cond
1354       ((and (consp specifier) (eql (car specifier) 'satisfies))
1355        (case (cadr specifier)
1356          ((keywordp) (if (type= type1 (specifier-type 'symbol))
1357                          (values nil t)
1358                          (invoke-complex-subtypep-arg1-method type1 type2)))
1359          (t (invoke-complex-subtypep-arg1-method type1 type2))))
1360       (t (invoke-complex-subtypep-arg1-method type1 type2)))))
1361
1362 (!define-type-method (hairy :complex-subtypep-arg1) (type1 type2)
1363   (declare (ignore type1 type2))
1364   (values nil nil))
1365
1366 (!define-type-method (hairy :complex-=) (type1 type2)
1367   (if (and (unknown-type-p type2)
1368            (let* ((specifier2 (unknown-type-specifier type2))
1369                   (name2 (if (consp specifier2)
1370                              (car specifier2)
1371                              specifier2)))
1372              (info :type :kind name2)))
1373       (let ((type2 (specifier-type (unknown-type-specifier type2))))
1374         (if (unknown-type-p type2)
1375             (values nil nil)
1376             (type= type1 type2)))
1377   (values nil nil)))
1378
1379 (!define-type-method (hairy :simple-intersection2 :complex-intersection2)
1380                      (type1 type2)
1381   (if (type= type1 type2)
1382       type1
1383       nil))
1384
1385 (!define-type-method (hairy :simple-union2)
1386                      (type1 type2)
1387   (if (type= type1 type2)
1388       type1
1389       nil))
1390
1391 (!define-type-method (hairy :simple-=) (type1 type2)
1392   (if (equal-but-no-car-recursion (hairy-type-specifier type1)
1393                                   (hairy-type-specifier type2))
1394       (values t t)
1395       (values nil nil)))
1396
1397 (!def-type-translator satisfies (&whole whole fun)
1398   (declare (ignore fun))
1399   ;; Check legality of arguments.
1400   (destructuring-bind (satisfies predicate-name) whole
1401     (declare (ignore satisfies))
1402     (unless (symbolp predicate-name)
1403       (error 'simple-type-error
1404              :datum predicate-name
1405              :expected-type 'symbol
1406              :format-control "The SATISFIES predicate name is not a symbol: ~S"
1407              :format-arguments (list predicate-name))))
1408   ;; Create object.
1409   (make-hairy-type :specifier whole))
1410 \f
1411 ;;;; negation types
1412
1413 (!define-type-method (negation :negate) (x)
1414   (negation-type-type x))
1415
1416 (!define-type-method (negation :unparse) (x)
1417   (if (type= (negation-type-type x) (specifier-type 'cons))
1418       'atom
1419       `(not ,(type-specifier (negation-type-type x)))))
1420
1421 (!define-type-method (negation :simple-subtypep) (type1 type2)
1422   (csubtypep (negation-type-type type2) (negation-type-type type1)))
1423
1424 (!define-type-method (negation :complex-subtypep-arg2) (type1 type2)
1425   (let* ((complement-type2 (negation-type-type type2))
1426          (intersection2 (type-intersection2 type1
1427                                             complement-type2)))
1428     (if intersection2
1429         ;; FIXME: if uncertain, maybe try arg1?
1430         (type= intersection2 *empty-type*)
1431         (invoke-complex-subtypep-arg1-method type1 type2))))
1432
1433 (!define-type-method (negation :complex-subtypep-arg1) (type1 type2)
1434   ;; "Incrementally extended heuristic algorithms tend inexorably toward the
1435   ;; incomprehensible." -- http://www.unlambda.com/~james/lambda/lambda.txt
1436   ;;
1437   ;; You may not believe this. I couldn't either. But then I sat down
1438   ;; and drew lots of Venn diagrams. Comments involving a and b refer
1439   ;; to the call (subtypep '(not a) 'b) -- CSR, 2002-02-27.
1440   (block nil
1441     ;; (Several logical truths in this block are true as long as
1442     ;; b/=T. As of sbcl-0.7.1.28, it seems impossible to construct a
1443     ;; case with b=T where we actually reach this type method, but
1444     ;; we'll test for and exclude this case anyway, since future
1445     ;; maintenance might make it possible for it to end up in this
1446     ;; code.)
1447     (multiple-value-bind (equal certain)
1448         (type= type2 *universal-type*)
1449       (unless certain
1450         (return (values nil nil)))
1451       (when equal
1452         (return (values t t))))
1453     (let ((complement-type1 (negation-type-type type1)))
1454       ;; Do the special cases first, in order to give us a chance if
1455       ;; subtype/supertype relationships are hairy.
1456       (multiple-value-bind (equal certain)
1457           (type= complement-type1 type2)
1458         ;; If a = b, ~a is not a subtype of b (unless b=T, which was
1459         ;; excluded above).
1460         (unless certain
1461           (return (values nil nil)))
1462         (when equal
1463           (return (values nil t))))
1464       ;; KLUDGE: ANSI requires that the SUBTYPEP result between any
1465       ;; two built-in atomic type specifiers never be uncertain. This
1466       ;; is hard to do cleanly for the built-in types whose
1467       ;; definitions include (NOT FOO), i.e. CONS and RATIO. However,
1468       ;; we can do it with this hack, which uses our global knowledge
1469       ;; that our implementation of the type system uses disjoint
1470       ;; implementation types to represent disjoint sets (except when
1471       ;; types are contained in other types).  (This is a KLUDGE
1472       ;; because it's fragile. Various changes in internal
1473       ;; representation in the type system could make it start
1474       ;; confidently returning incorrect results.) -- WHN 2002-03-08
1475       (unless (or (type-might-contain-other-types-p complement-type1)
1476                   (type-might-contain-other-types-p type2))
1477         ;; Because of the way our types which don't contain other
1478         ;; types are disjoint subsets of the space of possible values,
1479         ;; (SUBTYPEP '(NOT AA) 'B)=NIL when AA and B are simple (and B
1480         ;; is not T, as checked above).
1481         (return (values nil t)))
1482       ;; The old (TYPE= TYPE1 TYPE2) branch would never be taken, as
1483       ;; TYPE1 and TYPE2 will only be equal if they're both NOT types,
1484       ;; and then the :SIMPLE-SUBTYPEP method would be used instead.
1485       ;; But a CSUBTYPEP relationship might still hold:
1486       (multiple-value-bind (equal certain)
1487           (csubtypep complement-type1 type2)
1488         ;; If a is a subtype of b, ~a is not a subtype of b (unless
1489         ;; b=T, which was excluded above).
1490         (unless certain
1491           (return (values nil nil)))
1492         (when equal
1493           (return (values nil t))))
1494       (multiple-value-bind (equal certain)
1495           (csubtypep type2 complement-type1)
1496         ;; If b is a subtype of a, ~a is not a subtype of b.  (FIXME:
1497         ;; That's not true if a=T. Do we know at this point that a is
1498         ;; not T?)
1499         (unless certain
1500           (return (values nil nil)))
1501         (when equal
1502           (return (values nil t))))
1503       ;; old CSR comment ca. 0.7.2, now obsoleted by the SIMPLE-CTYPE?
1504       ;; KLUDGE case above: Other cases here would rely on being able
1505       ;; to catch all possible cases, which the fragility of this type
1506       ;; system doesn't inspire me; for instance, if a is type= to ~b,
1507       ;; then we want T, T; if this is not the case and the types are
1508       ;; disjoint (have an intersection of *empty-type*) then we want
1509       ;; NIL, T; else if the union of a and b is the *universal-type*
1510       ;; then we want T, T. So currently we still claim to be unsure
1511       ;; about e.g. (subtypep '(not fixnum) 'single-float).
1512       ;;
1513       ;; OTOH we might still get here:
1514       (values nil nil))))
1515
1516 (!define-type-method (negation :complex-=) (type1 type2)
1517   ;; (NOT FOO) isn't equivalent to anything that's not a negation
1518   ;; type, except possibly a type that might contain it in disguise.
1519   (declare (ignore type2))
1520   (if (type-might-contain-other-types-p type1)
1521       (values nil nil)
1522       (values nil t)))
1523
1524 (!define-type-method (negation :simple-intersection2) (type1 type2)
1525   (let ((not1 (negation-type-type type1))
1526         (not2 (negation-type-type type2)))
1527     (cond
1528       ((csubtypep not1 not2) type2)
1529       ((csubtypep not2 not1) type1)
1530       ;; Why no analagous clause to the disjoint in the SIMPLE-UNION2
1531       ;; method, below?  The clause would read
1532       ;;
1533       ;; ((EQ (TYPE-UNION NOT1 NOT2) *UNIVERSAL-TYPE*) *EMPTY-TYPE*)
1534       ;;
1535       ;; but with proper canonicalization of negation types, there's
1536       ;; no way of constructing two negation types with union of their
1537       ;; negations being the universal type.
1538       (t
1539        (aver (not (eq (type-union not1 not2) *universal-type*)))
1540        nil))))
1541
1542 (defun maybe-complex-array-refinement (type1 type2)
1543   (let* ((ntype (negation-type-type type2))
1544          (ndims (array-type-dimensions ntype))
1545          (ncomplexp (array-type-complexp ntype))
1546          (nseltype (array-type-specialized-element-type ntype))
1547          (neltype (array-type-element-type ntype)))
1548     (if (and (eql ndims '*) (null ncomplexp)
1549              (eql neltype *wild-type*) (eql nseltype *wild-type*))
1550         (make-array-type :dimensions (array-type-dimensions type1)
1551                          :complexp t
1552                          :element-type (array-type-element-type type1)
1553                          :specialized-element-type (array-type-specialized-element-type type1)))))
1554
1555 (!define-type-method (negation :complex-intersection2) (type1 type2)
1556   (cond
1557     ((csubtypep type1 (negation-type-type type2)) *empty-type*)
1558     ((eq (type-intersection type1 (negation-type-type type2)) *empty-type*)
1559      type1)
1560     ((and (array-type-p type1) (array-type-p (negation-type-type type2)))
1561      (maybe-complex-array-refinement type1 type2))
1562     (t nil)))
1563
1564 (!define-type-method (negation :simple-union2) (type1 type2)
1565   (let ((not1 (negation-type-type type1))
1566         (not2 (negation-type-type type2)))
1567     (cond
1568       ((csubtypep not1 not2) type1)
1569       ((csubtypep not2 not1) type2)
1570       ((eq (type-intersection not1 not2) *empty-type*)
1571        *universal-type*)
1572       (t nil))))
1573
1574 (!define-type-method (negation :complex-union2) (type1 type2)
1575   (cond
1576     ((csubtypep (negation-type-type type2) type1) *universal-type*)
1577     ((eq (type-intersection type1 (negation-type-type type2)) *empty-type*)
1578      type2)
1579     (t nil)))
1580
1581 (!define-type-method (negation :simple-=) (type1 type2)
1582   (type= (negation-type-type type1) (negation-type-type type2)))
1583
1584 (!def-type-translator not (typespec)
1585   (type-negation (specifier-type typespec)))
1586 \f
1587 ;;;; numeric types
1588
1589 (!define-type-class number)
1590
1591 (declaim (inline numeric-type-equal))
1592 (defun numeric-type-equal (type1 type2)
1593   (and (eq (numeric-type-class type1) (numeric-type-class type2))
1594        (eq (numeric-type-format type1) (numeric-type-format type2))
1595        (eq (numeric-type-complexp type1) (numeric-type-complexp type2))))
1596
1597 (!define-type-method (number :simple-=) (type1 type2)
1598   (values
1599    (and (numeric-type-equal type1 type2)
1600         (equalp (numeric-type-low type1) (numeric-type-low type2))
1601         (equalp (numeric-type-high type1) (numeric-type-high type2)))
1602    t))
1603
1604 (!define-type-method (number :negate) (type)
1605   (if (and (null (numeric-type-low type)) (null (numeric-type-high type)))
1606       (make-negation-type :type type)
1607       (type-union
1608        (make-negation-type
1609         :type (modified-numeric-type type :low nil :high nil))
1610        (cond
1611          ((null (numeric-type-low type))
1612           (modified-numeric-type
1613            type
1614            :low (let ((h (numeric-type-high type)))
1615                   (if (consp h) (car h) (list h)))
1616            :high nil))
1617          ((null (numeric-type-high type))
1618           (modified-numeric-type
1619            type
1620            :low nil
1621            :high (let ((l (numeric-type-low type)))
1622                    (if (consp l) (car l) (list l)))))
1623          (t (type-union
1624              (modified-numeric-type
1625               type
1626               :low nil
1627               :high (let ((l (numeric-type-low type)))
1628                       (if (consp l) (car l) (list l))))
1629              (modified-numeric-type
1630               type
1631               :low (let ((h (numeric-type-high type)))
1632                      (if (consp h) (car h) (list h)))
1633               :high nil)))))))
1634
1635 (!define-type-method (number :unparse) (type)
1636   (let* ((complexp (numeric-type-complexp type))
1637          (low (numeric-type-low type))
1638          (high (numeric-type-high type))
1639          (base (case (numeric-type-class type)
1640                  (integer 'integer)
1641                  (rational 'rational)
1642                  (float (or (numeric-type-format type) 'float))
1643                  (t 'real))))
1644     (let ((base+bounds
1645            (cond ((and (eq base 'integer) high low)
1646                   (let ((high-count (logcount high))
1647                         (high-length (integer-length high)))
1648                     (cond ((= low 0)
1649                            (cond ((= high 0) '(integer 0 0))
1650                                  ((= high 1) 'bit)
1651                                  ((and (= high-count high-length)
1652                                        (plusp high-length))
1653                                   `(unsigned-byte ,high-length))
1654                                  (t
1655                                   `(mod ,(1+ high)))))
1656                           ((and (= low sb!xc:most-negative-fixnum)
1657                                 (= high sb!xc:most-positive-fixnum))
1658                            'fixnum)
1659                           ((and (= low (lognot high))
1660                                 (= high-count high-length)
1661                                 (> high-count 0))
1662                            `(signed-byte ,(1+ high-length)))
1663                           (t
1664                            `(integer ,low ,high)))))
1665                  (high `(,base ,(or low '*) ,high))
1666                  (low
1667                   (if (and (eq base 'integer) (= low 0))
1668                       'unsigned-byte
1669                       `(,base ,low)))
1670                  (t base))))
1671       (ecase complexp
1672         (:real
1673          base+bounds)
1674         (:complex
1675          (aver (neq base+bounds 'real))
1676          `(complex ,base+bounds))
1677         ((nil)
1678          (aver (eq base+bounds 'real))
1679          'number)))))
1680
1681 ;;; Return true if X is "less than or equal" to Y, taking open bounds
1682 ;;; into consideration. CLOSED is the predicate used to test the bound
1683 ;;; on a closed interval (e.g. <=), and OPEN is the predicate used on
1684 ;;; open bounds (e.g. <). Y is considered to be the outside bound, in
1685 ;;; the sense that if it is infinite (NIL), then the test succeeds,
1686 ;;; whereas if X is infinite, then the test fails (unless Y is also
1687 ;;; infinite).
1688 ;;;
1689 ;;; This is for comparing bounds of the same kind, e.g. upper and
1690 ;;; upper. Use NUMERIC-BOUND-TEST* for different kinds of bounds.
1691 (defmacro numeric-bound-test (x y closed open)
1692   `(cond ((not ,y) t)
1693          ((not ,x) nil)
1694          ((consp ,x)
1695           (if (consp ,y)
1696               (,closed (car ,x) (car ,y))
1697               (,closed (car ,x) ,y)))
1698          (t
1699           (if (consp ,y)
1700               (,open ,x (car ,y))
1701               (,closed ,x ,y)))))
1702
1703 ;;; This is used to compare upper and lower bounds. This is different
1704 ;;; from the same-bound case:
1705 ;;; -- Since X = NIL is -infinity, whereas y = NIL is +infinity, we
1706 ;;;    return true if *either* arg is NIL.
1707 ;;; -- an open inner bound is "greater" and also squeezes the interval,
1708 ;;;    causing us to use the OPEN test for those cases as well.
1709 (defmacro numeric-bound-test* (x y closed open)
1710   `(cond ((not ,y) t)
1711          ((not ,x) t)
1712          ((consp ,x)
1713           (if (consp ,y)
1714               (,open (car ,x) (car ,y))
1715               (,open (car ,x) ,y)))
1716          (t
1717           (if (consp ,y)
1718               (,open ,x (car ,y))
1719               (,closed ,x ,y)))))
1720
1721 ;;; Return whichever of the numeric bounds X and Y is "maximal"
1722 ;;; according to the predicates CLOSED (e.g. >=) and OPEN (e.g. >).
1723 ;;; This is only meaningful for maximizing like bounds, i.e. upper and
1724 ;;; upper. If MAX-P is true, then we return NIL if X or Y is NIL,
1725 ;;; otherwise we return the other arg.
1726 (defmacro numeric-bound-max (x y closed open max-p)
1727   (once-only ((n-x x)
1728               (n-y y))
1729     `(cond ((not ,n-x) ,(if max-p nil n-y))
1730            ((not ,n-y) ,(if max-p nil n-x))
1731            ((consp ,n-x)
1732             (if (consp ,n-y)
1733                 (if (,closed (car ,n-x) (car ,n-y)) ,n-x ,n-y)
1734                 (if (,open (car ,n-x) ,n-y) ,n-x ,n-y)))
1735            (t
1736             (if (consp ,n-y)
1737                 (if (,open (car ,n-y) ,n-x) ,n-y ,n-x)
1738                 (if (,closed ,n-y ,n-x) ,n-y ,n-x))))))
1739
1740 (!define-type-method (number :simple-subtypep) (type1 type2)
1741   (let ((class1 (numeric-type-class type1))
1742         (class2 (numeric-type-class type2))
1743         (complexp2 (numeric-type-complexp type2))
1744         (format2 (numeric-type-format type2))
1745         (low1 (numeric-type-low type1))
1746         (high1 (numeric-type-high type1))
1747         (low2 (numeric-type-low type2))
1748         (high2 (numeric-type-high type2)))
1749     ;; If one is complex and the other isn't, they are disjoint.
1750     (cond ((not (or (eq (numeric-type-complexp type1) complexp2)
1751                     (null complexp2)))
1752            (values nil t))
1753           ;; If the classes are specified and different, the types are
1754           ;; disjoint unless type2 is RATIONAL and type1 is INTEGER.
1755           ;; [ or type1 is INTEGER and type2 is of the form (RATIONAL
1756           ;; X X) for integral X, but this is dealt with in the
1757           ;; canonicalization inside MAKE-NUMERIC-TYPE ]
1758           ((not (or (eq class1 class2)
1759                     (null class2)
1760                     (and (eq class1 'integer) (eq class2 'rational))))
1761            (values nil t))
1762           ;; If the float formats are specified and different, the types
1763           ;; are disjoint.
1764           ((not (or (eq (numeric-type-format type1) format2)
1765                     (null format2)))
1766            (values nil t))
1767           ;; Check the bounds.
1768           ((and (numeric-bound-test low1 low2 >= >)
1769                 (numeric-bound-test high1 high2 <= <))
1770            (values t t))
1771           (t
1772            (values nil t)))))
1773
1774 (!define-superclasses number ((number)) !cold-init-forms)
1775
1776 ;;; If the high bound of LOW is adjacent to the low bound of HIGH,
1777 ;;; then return true, otherwise NIL.
1778 (defun numeric-types-adjacent (low high)
1779   (let ((low-bound (numeric-type-high low))
1780         (high-bound (numeric-type-low high)))
1781     (cond ((not (and low-bound high-bound)) nil)
1782           ((and (consp low-bound) (consp high-bound)) nil)
1783           ((consp low-bound)
1784            (let ((low-value (car low-bound)))
1785              (or (eql low-value high-bound)
1786                  (and (eql low-value
1787                            (load-time-value (make-unportable-float
1788                                              :single-float-negative-zero)))
1789                       (eql high-bound 0f0))
1790                  (and (eql low-value 0f0)
1791                       (eql high-bound
1792                            (load-time-value (make-unportable-float
1793                                              :single-float-negative-zero))))
1794                  (and (eql low-value
1795                            (load-time-value (make-unportable-float
1796                                              :double-float-negative-zero)))
1797                       (eql high-bound 0d0))
1798                  (and (eql low-value 0d0)
1799                       (eql high-bound
1800                            (load-time-value (make-unportable-float
1801                                              :double-float-negative-zero)))))))
1802           ((consp high-bound)
1803            (let ((high-value (car high-bound)))
1804              (or (eql high-value low-bound)
1805                  (and (eql high-value
1806                            (load-time-value (make-unportable-float
1807                                              :single-float-negative-zero)))
1808                       (eql low-bound 0f0))
1809                  (and (eql high-value 0f0)
1810                       (eql low-bound
1811                            (load-time-value (make-unportable-float
1812                                              :single-float-negative-zero))))
1813                  (and (eql high-value
1814                            (load-time-value (make-unportable-float
1815                                              :double-float-negative-zero)))
1816                       (eql low-bound 0d0))
1817                  (and (eql high-value 0d0)
1818                       (eql low-bound
1819                            (load-time-value (make-unportable-float
1820                                              :double-float-negative-zero)))))))
1821           ((and (eq (numeric-type-class low) 'integer)
1822                 (eq (numeric-type-class high) 'integer))
1823            (eql (1+ low-bound) high-bound))
1824           (t
1825            nil))))
1826
1827 ;;; Return a numeric type that is a supertype for both TYPE1 and TYPE2.
1828 ;;;
1829 ;;; Old comment, probably no longer applicable:
1830 ;;;
1831 ;;;   ### Note: we give up early to keep from dropping lots of
1832 ;;;   information on the floor by returning overly general types.
1833 (!define-type-method (number :simple-union2) (type1 type2)
1834   (declare (type numeric-type type1 type2))
1835   (cond ((csubtypep type1 type2) type2)
1836         ((csubtypep type2 type1) type1)
1837         (t
1838          (let ((class1 (numeric-type-class type1))
1839                (format1 (numeric-type-format type1))
1840                (complexp1 (numeric-type-complexp type1))
1841                (class2 (numeric-type-class type2))
1842                (format2 (numeric-type-format type2))
1843                (complexp2 (numeric-type-complexp type2)))
1844            (cond
1845              ((and (eq class1 class2)
1846                    (eq format1 format2)
1847                    (eq complexp1 complexp2)
1848                    (or (numeric-types-intersect type1 type2)
1849                        (numeric-types-adjacent type1 type2)
1850                        (numeric-types-adjacent type2 type1)))
1851               (make-numeric-type
1852                :class class1
1853                :format format1
1854                :complexp complexp1
1855                :low (numeric-bound-max (numeric-type-low type1)
1856                                        (numeric-type-low type2)
1857                                        <= < t)
1858                :high (numeric-bound-max (numeric-type-high type1)
1859                                         (numeric-type-high type2)
1860                                         >= > t)))
1861              ;; FIXME: These two clauses are almost identical, and the
1862              ;; consequents are in fact identical in every respect.
1863              ((and (eq class1 'rational)
1864                    (eq class2 'integer)
1865                    (eq format1 format2)
1866                    (eq complexp1 complexp2)
1867                    (integerp (numeric-type-low type2))
1868                    (integerp (numeric-type-high type2))
1869                    (= (numeric-type-low type2) (numeric-type-high type2))
1870                    (or (numeric-types-adjacent type1 type2)
1871                        (numeric-types-adjacent type2 type1)))
1872               (make-numeric-type
1873                :class 'rational
1874                :format format1
1875                :complexp complexp1
1876                :low (numeric-bound-max (numeric-type-low type1)
1877                                        (numeric-type-low type2)
1878                                        <= < t)
1879                :high (numeric-bound-max (numeric-type-high type1)
1880                                         (numeric-type-high type2)
1881                                         >= > t)))
1882              ((and (eq class1 'integer)
1883                    (eq class2 'rational)
1884                    (eq format1 format2)
1885                    (eq complexp1 complexp2)
1886                    (integerp (numeric-type-low type1))
1887                    (integerp (numeric-type-high type1))
1888                    (= (numeric-type-low type1) (numeric-type-high type1))
1889                    (or (numeric-types-adjacent type1 type2)
1890                        (numeric-types-adjacent type2 type1)))
1891               (make-numeric-type
1892                :class 'rational
1893                :format format1
1894                :complexp complexp1
1895                :low (numeric-bound-max (numeric-type-low type1)
1896                                        (numeric-type-low type2)
1897                                        <= < t)
1898                :high (numeric-bound-max (numeric-type-high type1)
1899                                         (numeric-type-high type2)
1900                                         >= > t)))
1901              (t nil))))))
1902
1903
1904 (!cold-init-forms
1905   (setf (info :type :kind 'number)
1906         #+sb-xc-host :defined #-sb-xc-host :primitive)
1907   (setf (info :type :builtin 'number)
1908         (make-numeric-type :complexp nil)))
1909
1910 (!def-type-translator complex (&optional (typespec '*))
1911   (if (eq typespec '*)
1912       (specifier-type '(complex real))
1913       (labels ((not-numeric ()
1914                  (error "The component type for COMPLEX is not numeric: ~S"
1915                         typespec))
1916                (not-real ()
1917                  (error "The component type for COMPLEX is not a subtype of REAL: ~S"
1918                         typespec))
1919                (complex1 (component-type)
1920                  (unless (numeric-type-p component-type)
1921                    (not-numeric))
1922                  (when (eq (numeric-type-complexp component-type) :complex)
1923                    (not-real))
1924                  (if (csubtypep component-type (specifier-type '(eql 0)))
1925                      *empty-type*
1926                      (modified-numeric-type component-type
1927                                             :complexp :complex)))
1928                (do-complex (ctype)
1929                  (cond
1930                    ((eq ctype *empty-type*) *empty-type*)
1931                    ((eq ctype *universal-type*) (not-real))
1932                    ((typep ctype 'numeric-type) (complex1 ctype))
1933                    ((typep ctype 'union-type)
1934                     (apply #'type-union
1935                            (mapcar #'do-complex (union-type-types ctype))))
1936                    ((typep ctype 'member-type)
1937                     (apply #'type-union
1938                            (mapcar-member-type-members
1939                             (lambda (x) (do-complex (ctype-of x)))
1940                             ctype)))
1941                    ((and (typep ctype 'intersection-type)
1942                          ;; FIXME: This is very much a
1943                          ;; not-quite-worst-effort, but we are required to do
1944                          ;; something here because of our representation of
1945                          ;; RATIO as (AND RATIONAL (NOT INTEGER)): we must
1946                          ;; allow users to ask about (COMPLEX RATIO).  This
1947                          ;; will of course fail to work right on such types
1948                          ;; as (AND INTEGER (SATISFIES ZEROP))...
1949                          (let ((numbers (remove-if-not
1950                                          #'numeric-type-p
1951                                          (intersection-type-types ctype))))
1952                            (and (car numbers)
1953                                 (null (cdr numbers))
1954                                 (eq (numeric-type-complexp (car numbers)) :real)
1955                                 (complex1 (car numbers))))))
1956                    (t
1957                     (multiple-value-bind (subtypep certainly)
1958                         (csubtypep ctype (specifier-type 'real))
1959                       (if (and (not subtypep) certainly)
1960                           (not-real)
1961                           ;; ANSI just says that TYPESPEC is any subtype of
1962                           ;; type REAL, not necessarily a NUMERIC-TYPE. In
1963                           ;; particular, at this point TYPESPEC could legally
1964                           ;; be a hairy type like (AND NUMBER (SATISFIES
1965                           ;; REALP) (SATISFIES ZEROP)), in which case we fall
1966                           ;; through the logic above and end up here,
1967                           ;; stumped.
1968                           (bug "~@<(known bug #145): The type ~S is too hairy to be ~
1969 used for a COMPLEX component.~:@>"
1970                                typespec)))))))
1971         (let ((ctype (specifier-type typespec)))
1972           (do-complex ctype)))))
1973
1974 ;;; If X is *, return NIL, otherwise return the bound, which must be a
1975 ;;; member of TYPE or a one-element list of a member of TYPE.
1976 #!-sb-fluid (declaim (inline canonicalized-bound))
1977 (defun canonicalized-bound (bound type)
1978   (cond ((eq bound '*) nil)
1979         ((or (sb!xc:typep bound type)
1980              (and (consp bound)
1981                   (sb!xc:typep (car bound) type)
1982                   (null (cdr bound))))
1983           bound)
1984         (t
1985          (error "Bound is not ~S, a ~S or a list of a ~S: ~S"
1986                 '*
1987                 type
1988                 type
1989                 bound))))
1990
1991 (!def-type-translator integer (&optional (low '*) (high '*))
1992   (let* ((l (canonicalized-bound low 'integer))
1993          (lb (if (consp l) (1+ (car l)) l))
1994          (h (canonicalized-bound high 'integer))
1995          (hb (if (consp h) (1- (car h)) h)))
1996     (if (and hb lb (< hb lb))
1997         *empty-type*
1998       (make-numeric-type :class 'integer
1999                          :complexp :real
2000                          :enumerable (not (null (and l h)))
2001                          :low lb
2002                          :high hb))))
2003
2004 (defmacro !def-bounded-type (type class format)
2005   `(!def-type-translator ,type (&optional (low '*) (high '*))
2006      (let ((lb (canonicalized-bound low ',type))
2007            (hb (canonicalized-bound high ',type)))
2008        (if (not (numeric-bound-test* lb hb <= <))
2009            *empty-type*
2010          (make-numeric-type :class ',class
2011                             :format ',format
2012                             :low lb
2013                             :high hb)))))
2014
2015 (!def-bounded-type rational rational nil)
2016
2017 ;;; Unlike CMU CL, we represent the types FLOAT and REAL as
2018 ;;; UNION-TYPEs of more primitive types, in order to make
2019 ;;; type representation more unique, avoiding problems in the
2020 ;;; simplification of things like
2021 ;;;   (subtypep '(or (single-float -1.0 1.0) (single-float 0.1))
2022 ;;;             '(or (real -1 7) (single-float 0.1) (single-float -1.0 1.0)))
2023 ;;; When we allowed REAL to remain as a separate NUMERIC-TYPE,
2024 ;;; it was too easy for the first argument to be simplified to
2025 ;;; '(SINGLE-FLOAT -1.0), and for the second argument to be simplified
2026 ;;; to '(OR (REAL -1 7) (SINGLE-FLOAT 0.1)) and then for the
2027 ;;; SUBTYPEP to fail (returning NIL,T instead of T,T) because
2028 ;;; the first argument can't be seen to be a subtype of any of the
2029 ;;; terms in the second argument.
2030 ;;;
2031 ;;; The old CMU CL way was:
2032 ;;;   (!def-bounded-type float float nil)
2033 ;;;   (!def-bounded-type real nil nil)
2034 ;;;
2035 ;;; FIXME: If this new way works for a while with no weird new
2036 ;;; problems, we can go back and rip out support for separate FLOAT
2037 ;;; and REAL flavors of NUMERIC-TYPE. The new way was added in
2038 ;;; sbcl-0.6.11.22, 2001-03-21.
2039 ;;;
2040 ;;; FIXME: It's probably necessary to do something to fix the
2041 ;;; analogous problem with INTEGER and RATIONAL types. Perhaps
2042 ;;; bounded RATIONAL types should be represented as (OR RATIO INTEGER).
2043 (defun coerce-bound (bound type upperp inner-coerce-bound-fun)
2044   (declare (type function inner-coerce-bound-fun))
2045   (if (eql bound '*)
2046       bound
2047       (funcall inner-coerce-bound-fun bound type upperp)))
2048 (defun inner-coerce-real-bound (bound type upperp)
2049   #+sb-xc-host (declare (ignore upperp))
2050   (let #+sb-xc-host ()
2051        #-sb-xc-host
2052        ((nl (load-time-value (symbol-value 'sb!xc:most-negative-long-float)))
2053         (pl (load-time-value (symbol-value 'sb!xc:most-positive-long-float))))
2054     (let ((nbound (if (consp bound) (car bound) bound))
2055           (consp (consp bound)))
2056       (ecase type
2057         (rational
2058          (if consp
2059              (list (rational nbound))
2060              (rational nbound)))
2061         (float
2062          (cond
2063            ((floatp nbound) bound)
2064            (t
2065             ;; Coerce to the widest float format available, to avoid
2066             ;; unnecessary loss of precision, but don't coerce
2067             ;; unrepresentable numbers, except on the host where we
2068             ;; shouldn't be making these types (but KLUDGE: can't even
2069             ;; assert portably that we're not).
2070             #-sb-xc-host
2071             (ecase upperp
2072               ((nil)
2073                (when (< nbound nl) (return-from inner-coerce-real-bound nl)))
2074               ((t)
2075                (when (> nbound pl) (return-from inner-coerce-real-bound pl))))
2076             (let ((result (coerce nbound 'long-float)))
2077               (if consp (list result) result)))))))))
2078 (defun inner-coerce-float-bound (bound type upperp)
2079   #+sb-xc-host (declare (ignore upperp))
2080   (let #+sb-xc-host ()
2081        #-sb-xc-host
2082        ((nd (load-time-value (symbol-value 'sb!xc:most-negative-double-float)))
2083         (pd (load-time-value (symbol-value 'sb!xc:most-positive-double-float)))
2084         (ns (load-time-value (symbol-value 'sb!xc:most-negative-single-float)))
2085         (ps (load-time-value
2086              (symbol-value 'sb!xc:most-positive-single-float))))
2087     (let ((nbound (if (consp bound) (car bound) bound))
2088           (consp (consp bound)))
2089       (ecase type
2090         (single-float
2091          (cond
2092            ((typep nbound 'single-float) bound)
2093            (t
2094             #-sb-xc-host
2095             (ecase upperp
2096               ((nil)
2097                (when (< nbound ns) (return-from inner-coerce-float-bound ns)))
2098               ((t)
2099                (when (> nbound ps) (return-from inner-coerce-float-bound ps))))
2100             (let ((result (coerce nbound 'single-float)))
2101               (if consp (list result) result)))))
2102         (double-float
2103          (cond
2104            ((typep nbound 'double-float) bound)
2105            (t
2106             #-sb-xc-host
2107             (ecase upperp
2108               ((nil)
2109                (when (< nbound nd) (return-from inner-coerce-float-bound nd)))
2110               ((t)
2111                (when (> nbound pd) (return-from inner-coerce-float-bound pd))))
2112             (let ((result (coerce nbound 'double-float)))
2113               (if consp (list result) result)))))))))
2114 (defun coerced-real-bound (bound type upperp)
2115   (coerce-bound bound type upperp #'inner-coerce-real-bound))
2116 (defun coerced-float-bound (bound type upperp)
2117   (coerce-bound bound type upperp #'inner-coerce-float-bound))
2118 (!def-type-translator real (&optional (low '*) (high '*))
2119   (specifier-type `(or (float ,(coerced-real-bound  low 'float nil)
2120                               ,(coerced-real-bound high 'float t))
2121                        (rational ,(coerced-real-bound  low 'rational nil)
2122                                  ,(coerced-real-bound high 'rational t)))))
2123 (!def-type-translator float (&optional (low '*) (high '*))
2124   (specifier-type
2125    `(or (single-float ,(coerced-float-bound  low 'single-float nil)
2126                       ,(coerced-float-bound high 'single-float t))
2127         (double-float ,(coerced-float-bound  low 'double-float nil)
2128                       ,(coerced-float-bound high 'double-float t))
2129         #!+long-float ,(error "stub: no long float support yet"))))
2130
2131 (defmacro !define-float-format (f)
2132   `(!def-bounded-type ,f float ,f))
2133
2134 (!define-float-format short-float)
2135 (!define-float-format single-float)
2136 (!define-float-format double-float)
2137 (!define-float-format long-float)
2138
2139 (defun numeric-types-intersect (type1 type2)
2140   (declare (type numeric-type type1 type2))
2141   (let* ((class1 (numeric-type-class type1))
2142          (class2 (numeric-type-class type2))
2143          (complexp1 (numeric-type-complexp type1))
2144          (complexp2 (numeric-type-complexp type2))
2145          (format1 (numeric-type-format type1))
2146          (format2 (numeric-type-format type2))
2147          (low1 (numeric-type-low type1))
2148          (high1 (numeric-type-high type1))
2149          (low2 (numeric-type-low type2))
2150          (high2 (numeric-type-high type2)))
2151     ;; If one is complex and the other isn't, then they are disjoint.
2152     (cond ((not (or (eq complexp1 complexp2)
2153                     (null complexp1) (null complexp2)))
2154            nil)
2155           ;; If either type is a float, then the other must either be
2156           ;; specified to be a float or unspecified. Otherwise, they
2157           ;; are disjoint.
2158           ((and (eq class1 'float)
2159                 (not (member class2 '(float nil)))) nil)
2160           ((and (eq class2 'float)
2161                 (not (member class1 '(float nil)))) nil)
2162           ;; If the float formats are specified and different, the
2163           ;; types are disjoint.
2164           ((not (or (eq format1 format2) (null format1) (null format2)))
2165            nil)
2166           (t
2167            ;; Check the bounds. This is a bit odd because we must
2168            ;; always have the outer bound of the interval as the
2169            ;; second arg.
2170            (if (numeric-bound-test high1 high2 <= <)
2171                (or (and (numeric-bound-test low1 low2 >= >)
2172                         (numeric-bound-test* low1 high2 <= <))
2173                    (and (numeric-bound-test low2 low1 >= >)
2174                         (numeric-bound-test* low2 high1 <= <)))
2175                (or (and (numeric-bound-test* low2 high1 <= <)
2176                         (numeric-bound-test low2 low1 >= >))
2177                    (and (numeric-bound-test high2 high1 <= <)
2178                         (numeric-bound-test* high2 low1 >= >))))))))
2179
2180 ;;; Take the numeric bound X and convert it into something that can be
2181 ;;; used as a bound in a numeric type with the specified CLASS and
2182 ;;; FORMAT. If UP-P is true, then we round up as needed, otherwise we
2183 ;;; round down. UP-P true implies that X is a lower bound, i.e. (N) > N.
2184 ;;;
2185 ;;; This is used by NUMERIC-TYPE-INTERSECTION to mash the bound into
2186 ;;; the appropriate type number. X may only be a float when CLASS is
2187 ;;; FLOAT.
2188 ;;;
2189 ;;; ### Note: it is possible for the coercion to a float to overflow
2190 ;;; or underflow. This happens when the bound doesn't fit in the
2191 ;;; specified format. In this case, we should really return the
2192 ;;; appropriate {Most | Least}-{Positive | Negative}-XXX-Float float
2193 ;;; of desired format. But these conditions aren't currently signalled
2194 ;;; in any useful way.
2195 ;;;
2196 ;;; Also, when converting an open rational bound into a float we
2197 ;;; should probably convert it to a closed bound of the closest float
2198 ;;; in the specified format. KLUDGE: In general, open float bounds are
2199 ;;; screwed up. -- (comment from original CMU CL)
2200 (defun round-numeric-bound (x class format up-p)
2201   (if x
2202       (let ((cx (if (consp x) (car x) x)))
2203         (ecase class
2204           ((nil rational) x)
2205           (integer
2206            (if (and (consp x) (integerp cx))
2207                (if up-p (1+ cx) (1- cx))
2208                (if up-p (ceiling cx) (floor cx))))
2209           (float
2210            (let ((res
2211                   (cond
2212                     ((and format (subtypep format 'double-float))
2213                      (if (<= most-negative-double-float cx most-positive-double-float)
2214                          (coerce cx format)
2215                          nil))
2216                     (t
2217                      (if (<= most-negative-single-float cx most-positive-single-float)
2218                          ;; FIXME: bug #389
2219                          (coerce cx (or format 'single-float))
2220                          nil)))))
2221              (if (consp x) (list res) res)))))
2222       nil))
2223
2224 ;;; Handle the case of type intersection on two numeric types. We use
2225 ;;; TYPES-EQUAL-OR-INTERSECT to throw out the case of types with no
2226 ;;; intersection. If an attribute in TYPE1 is unspecified, then we use
2227 ;;; TYPE2's attribute, which must be at least as restrictive. If the
2228 ;;; types intersect, then the only attributes that can be specified
2229 ;;; and different are the class and the bounds.
2230 ;;;
2231 ;;; When the class differs, we use the more restrictive class. The
2232 ;;; only interesting case is RATIONAL/INTEGER, since RATIONAL includes
2233 ;;; INTEGER.
2234 ;;;
2235 ;;; We make the result lower (upper) bound the maximum (minimum) of
2236 ;;; the argument lower (upper) bounds. We convert the bounds into the
2237 ;;; appropriate numeric type before maximizing. This avoids possible
2238 ;;; confusion due to mixed-type comparisons (but I think the result is
2239 ;;; the same).
2240 (!define-type-method (number :simple-intersection2) (type1 type2)
2241   (declare (type numeric-type type1 type2))
2242   (if (numeric-types-intersect type1 type2)
2243       (let* ((class1 (numeric-type-class type1))
2244              (class2 (numeric-type-class type2))
2245              (class (ecase class1
2246                       ((nil) class2)
2247                       ((integer float) class1)
2248                       (rational (if (eq class2 'integer)
2249                                        'integer
2250                                        'rational))))
2251              (format (or (numeric-type-format type1)
2252                          (numeric-type-format type2))))
2253         (make-numeric-type
2254          :class class
2255          :format format
2256          :complexp (or (numeric-type-complexp type1)
2257                        (numeric-type-complexp type2))
2258          :low (numeric-bound-max
2259                (round-numeric-bound (numeric-type-low type1)
2260                                     class format t)
2261                (round-numeric-bound (numeric-type-low type2)
2262                                     class format t)
2263                > >= nil)
2264          :high (numeric-bound-max
2265                 (round-numeric-bound (numeric-type-high type1)
2266                                      class format nil)
2267                 (round-numeric-bound (numeric-type-high type2)
2268                                      class format nil)
2269                 < <= nil)))
2270       *empty-type*))
2271
2272 ;;; Given two float formats, return the one with more precision. If
2273 ;;; either one is null, return NIL.
2274 (defun float-format-max (f1 f2)
2275   (when (and f1 f2)
2276     (dolist (f *float-formats* (error "bad float format: ~S" f1))
2277       (when (or (eq f f1) (eq f f2))
2278         (return f)))))
2279
2280 ;;; Return the result of an operation on TYPE1 and TYPE2 according to
2281 ;;; the rules of numeric contagion. This is always NUMBER, some float
2282 ;;; format (possibly complex) or RATIONAL. Due to rational
2283 ;;; canonicalization, there isn't much we can do here with integers or
2284 ;;; rational complex numbers.
2285 ;;;
2286 ;;; If either argument is not a NUMERIC-TYPE, then return NUMBER. This
2287 ;;; is useful mainly for allowing types that are technically numbers,
2288 ;;; but not a NUMERIC-TYPE.
2289 (defun numeric-contagion (type1 type2)
2290   (if (and (numeric-type-p type1) (numeric-type-p type2))
2291       (let ((class1 (numeric-type-class type1))
2292             (class2 (numeric-type-class type2))
2293             (format1 (numeric-type-format type1))
2294             (format2 (numeric-type-format type2))
2295             (complexp1 (numeric-type-complexp type1))
2296             (complexp2 (numeric-type-complexp type2)))
2297         (cond ((or (null complexp1)
2298                    (null complexp2))
2299                (specifier-type 'number))
2300               ((eq class1 'float)
2301                (make-numeric-type
2302                 :class 'float
2303                 :format (ecase class2
2304                           (float (float-format-max format1 format2))
2305                           ((integer rational) format1)
2306                           ((nil)
2307                            ;; A double-float with any real number is a
2308                            ;; double-float.
2309                            #!-long-float
2310                            (if (eq format1 'double-float)
2311                              'double-float
2312                              nil)
2313                            ;; A long-float with any real number is a
2314                            ;; long-float.
2315                            #!+long-float
2316                            (if (eq format1 'long-float)
2317                              'long-float
2318                              nil)))
2319                 :complexp (if (or (eq complexp1 :complex)
2320                                   (eq complexp2 :complex))
2321                               :complex
2322                               :real)))
2323               ((eq class2 'float) (numeric-contagion type2 type1))
2324               ((and (eq complexp1 :real) (eq complexp2 :real))
2325                (make-numeric-type
2326                 :class (and class1 class2 'rational)
2327                 :complexp :real))
2328               (t
2329                (specifier-type 'number))))
2330       (specifier-type 'number)))
2331 \f
2332 ;;;; array types
2333
2334 (!define-type-class array)
2335
2336 (!define-type-method (array :simple-=) (type1 type2)
2337   (cond ((not (and (equal (array-type-dimensions type1)
2338                           (array-type-dimensions type2))
2339                    (eq (array-type-complexp type1)
2340                        (array-type-complexp type2))))
2341          (values nil t))
2342         ((or (unknown-type-p (array-type-element-type type1))
2343              (unknown-type-p (array-type-element-type type2)))
2344          (multiple-value-bind (equalp certainp)
2345              (type= (array-type-element-type type1)
2346                     (array-type-element-type type2))
2347            ;; By its nature, the call to TYPE= should never return
2348            ;; NIL, T, as we don't know what the UNKNOWN-TYPE will grow
2349            ;; up to be.  -- CSR, 2002-08-19
2350            (aver (not (and (not equalp) certainp)))
2351            (values equalp certainp)))
2352         (t
2353          (values (type= (array-type-specialized-element-type type1)
2354                         (array-type-specialized-element-type type2))
2355                  t))))
2356
2357 (!define-type-method (array :negate) (type)
2358   ;; FIXME (and hint to PFD): we're vulnerable here to attacks of the
2359   ;; form "are (AND ARRAY (NOT (ARRAY T))) and (OR (ARRAY BIT) (ARRAY
2360   ;; NIL) (ARRAY CHAR) ...) equivalent?" -- CSR, 2003-12-10
2361   (make-negation-type :type type))
2362
2363 (!define-type-method (array :unparse) (type)
2364   (let ((dims (array-type-dimensions type))
2365         (eltype (type-specifier (array-type-element-type type)))
2366         (complexp (array-type-complexp type)))
2367     (cond ((eq dims '*)
2368            (if (eq eltype '*)
2369                (ecase complexp
2370                  ((t) '(and array (not simple-array)))
2371                  ((:maybe) 'array)
2372                  ((nil) 'simple-array))
2373                (ecase complexp
2374                  ((t) `(and (array ,eltype) (not simple-array)))
2375                  ((:maybe) `(array ,eltype))
2376                  ((nil) `(simple-array ,eltype)))))
2377           ((= (length dims) 1)
2378            (if complexp
2379                (let ((answer
2380                       (if (eq (car dims) '*)
2381                           (case eltype
2382                             (bit 'bit-vector)
2383                             ((base-char #!-sb-unicode character) 'base-string)
2384                             (* 'vector)
2385                             (t `(vector ,eltype)))
2386                           (case eltype
2387                             (bit `(bit-vector ,(car dims)))
2388                             ((base-char #!-sb-unicode character)
2389                              `(base-string ,(car dims)))
2390                             (t `(vector ,eltype ,(car dims)))))))
2391                  (if (eql complexp :maybe)
2392                      answer
2393                      `(and ,answer (not simple-array))))
2394                (if (eq (car dims) '*)
2395                    (case eltype
2396                      (bit 'simple-bit-vector)
2397                      ((base-char #!-sb-unicode character) 'simple-base-string)
2398                      ((t) 'simple-vector)
2399                      (t `(simple-array ,eltype (*))))
2400                    (case eltype
2401                      (bit `(simple-bit-vector ,(car dims)))
2402                      ((base-char #!-sb-unicode character)
2403                       `(simple-base-string ,(car dims)))
2404                      ((t) `(simple-vector ,(car dims)))
2405                      (t `(simple-array ,eltype ,dims))))))
2406           (t
2407            (ecase complexp
2408              ((t) `(and (array ,eltype ,dims) (not simple-array)))
2409              ((:maybe) `(array ,eltype ,dims))
2410              ((nil) `(simple-array ,eltype ,dims)))))))
2411
2412 (!define-type-method (array :simple-subtypep) (type1 type2)
2413   (let ((dims1 (array-type-dimensions type1))
2414         (dims2 (array-type-dimensions type2))
2415         (complexp2 (array-type-complexp type2)))
2416     (cond (;; not subtypep unless dimensions are compatible
2417            (not (or (eq dims2 '*)
2418                     (and (not (eq dims1 '*))
2419                          ;; (sbcl-0.6.4 has trouble figuring out that
2420                          ;; DIMS1 and DIMS2 must be lists at this
2421                          ;; point, and knowing that is important to
2422                          ;; compiling EVERY efficiently.)
2423                          (= (length (the list dims1))
2424                             (length (the list dims2)))
2425                          (every (lambda (x y)
2426                                   (or (eq y '*) (eql x y)))
2427                                 (the list dims1)
2428                                 (the list dims2)))))
2429            (values nil t))
2430           ;; not subtypep unless complexness is compatible
2431           ((not (or (eq complexp2 :maybe)
2432                     (eq (array-type-complexp type1) complexp2)))
2433            (values nil t))
2434           ;; Since we didn't fail any of the tests above, we win
2435           ;; if the TYPE2 element type is wild.
2436           ((eq (array-type-element-type type2) *wild-type*)
2437            (values t t))
2438           (;; Since we didn't match any of the special cases above, if
2439            ;; either element type is unknown we can only give a good
2440            ;; answer if they are the same.
2441            (or (unknown-type-p (array-type-element-type type1))
2442                (unknown-type-p (array-type-element-type type2)))
2443            (if (type= (array-type-element-type type1)
2444                       (array-type-element-type type2))
2445                (values t t)
2446                (values nil nil)))
2447           (;; Otherwise, the subtype relationship holds iff the
2448            ;; types are equal, and they're equal iff the specialized
2449            ;; element types are identical.
2450            t
2451            (values (type= (array-type-specialized-element-type type1)
2452                           (array-type-specialized-element-type type2))
2453                    t)))))
2454
2455 (!define-superclasses array
2456   ((vector vector) (array))
2457   !cold-init-forms)
2458
2459 (defun array-types-intersect (type1 type2)
2460   (declare (type array-type type1 type2))
2461   (let ((dims1 (array-type-dimensions type1))
2462         (dims2 (array-type-dimensions type2))
2463         (complexp1 (array-type-complexp type1))
2464         (complexp2 (array-type-complexp type2)))
2465     ;; See whether dimensions are compatible.
2466     (cond ((not (or (eq dims1 '*) (eq dims2 '*)
2467                     (and (= (length dims1) (length dims2))
2468                          (every (lambda (x y)
2469                                   (or (eq x '*) (eq y '*) (= x y)))
2470                                 dims1 dims2))))
2471            (values nil t))
2472           ;; See whether complexpness is compatible.
2473           ((not (or (eq complexp1 :maybe)
2474                     (eq complexp2 :maybe)
2475                     (eq complexp1 complexp2)))
2476            (values nil t))
2477           ;; Old comment:
2478           ;;
2479           ;;   If either element type is wild, then they intersect.
2480           ;;   Otherwise, the types must be identical.
2481           ;;
2482           ;; FIXME: There seems to have been a fair amount of
2483           ;; confusion about the distinction between requested element
2484           ;; type and specialized element type; here is one of
2485           ;; them. If we request an array to hold objects of an
2486           ;; unknown type, we can do no better than represent that
2487           ;; type as an array specialized on wild-type.  We keep the
2488           ;; requested element-type in the -ELEMENT-TYPE slot, and
2489           ;; *WILD-TYPE* in the -SPECIALIZED-ELEMENT-TYPE.  So, here,
2490           ;; we must test for the SPECIALIZED slot being *WILD-TYPE*,
2491           ;; not just the ELEMENT-TYPE slot.  Maybe the return value
2492           ;; in that specific case should be T, NIL?  Or maybe this
2493           ;; function should really be called
2494           ;; ARRAY-TYPES-COULD-POSSIBLY-INTERSECT?  In any case, this
2495           ;; was responsible for bug #123, and this whole issue could
2496           ;; do with a rethink and/or a rewrite.  -- CSR, 2002-08-21
2497           ((or (eq (array-type-specialized-element-type type1) *wild-type*)
2498                (eq (array-type-specialized-element-type type2) *wild-type*)
2499                (type= (array-type-specialized-element-type type1)
2500                       (array-type-specialized-element-type type2)))
2501
2502            (values t t))
2503           (t
2504            (values nil t)))))
2505
2506 (!define-type-method (array :simple-union2) (type1 type2)
2507    (let* ((dims1 (array-type-dimensions type1))
2508           (dims2 (array-type-dimensions type2))
2509           (complexp1 (array-type-complexp type1))
2510           (complexp2 (array-type-complexp type2))
2511           (eltype1 (array-type-element-type type1))
2512           (eltype2 (array-type-element-type type2))
2513           (stype1 (array-type-specialized-element-type type1))
2514           (stype2 (array-type-specialized-element-type type2))
2515           (wild1 (eq eltype1 *wild-type*))
2516           (wild2 (eq eltype2 *wild-type*))
2517           (e2 nil))
2518      (when (or wild1 wild2
2519                (and (or (setf e2 (csubtypep eltype1 eltype2))
2520                         (csubtypep eltype2 eltype1))
2521                     (type= stype1 stype2)))
2522        (make-array-type
2523         :dimensions (cond ((or (eq dims1 '*) (eq dims2 '*))
2524                            '*)
2525                           ((equal dims1 dims2)
2526                            dims1)
2527                           ((= (length dims1) (length dims2))
2528                            (mapcar (lambda (x y) (if (eq x y) x '*))
2529                                    dims1 dims2))
2530                           (t
2531                            '*))
2532         :complexp (if (eq complexp1 complexp2) complexp1 :maybe)
2533         :element-type (if (or wild2 e2) eltype2 eltype1)
2534         :specialized-element-type (if wild2 stype2 stype1)))))
2535
2536 (!define-type-method (array :simple-intersection2) (type1 type2)
2537   (declare (type array-type type1 type2))
2538   (if (array-types-intersect type1 type2)
2539       (let ((dims1 (array-type-dimensions type1))
2540             (dims2 (array-type-dimensions type2))
2541             (complexp1 (array-type-complexp type1))
2542             (complexp2 (array-type-complexp type2))
2543             (eltype1 (array-type-element-type type1))
2544             (eltype2 (array-type-element-type type2))
2545             (stype1 (array-type-specialized-element-type type1))
2546             (stype2 (array-type-specialized-element-type type2)))
2547         (flet ((intersect ()
2548                  (make-array-type
2549                   :dimensions (cond ((eq dims1 '*) dims2)
2550                                     ((eq dims2 '*) dims1)
2551                                     (t
2552                                      (mapcar (lambda (x y) (if (eq x '*) y x))
2553                                              dims1 dims2)))
2554                   :complexp (if (eq complexp1 :maybe) complexp2 complexp1)
2555                   :element-type (cond
2556                                   ((eq eltype1 *wild-type*) eltype2)
2557                                   ((eq eltype2 *wild-type*) eltype1)
2558                                   (t (type-intersection eltype1 eltype2))))))
2559           (if (or (eq stype1 *wild-type*) (eq stype2 *wild-type*))
2560               (specialize-array-type (intersect))
2561               (let ((type (intersect)))
2562                 (aver (type= stype1 stype2))
2563                 (setf (array-type-specialized-element-type type) stype1)
2564                 type))))
2565       *empty-type*))
2566
2567 ;;; Check a supplied dimension list to determine whether it is legal,
2568 ;;; and return it in canonical form (as either '* or a list).
2569 (defun canonical-array-dimensions (dims)
2570   (typecase dims
2571     ((member *) dims)
2572     (integer
2573      (when (minusp dims)
2574        (error "Arrays can't have a negative number of dimensions: ~S" dims))
2575      (when (>= dims sb!xc:array-rank-limit)
2576        (error "array type with too many dimensions: ~S" dims))
2577      (make-list dims :initial-element '*))
2578     (list
2579      (when (>= (length dims) sb!xc:array-rank-limit)
2580        (error "array type with too many dimensions: ~S" dims))
2581      (dolist (dim dims)
2582        (unless (eq dim '*)
2583          (unless (and (integerp dim)
2584                       (>= dim 0)
2585                       (< dim sb!xc:array-dimension-limit))
2586            (error "bad dimension in array type: ~S" dim))))
2587      dims)
2588     (t
2589      (error "Array dimensions is not a list, integer or *:~%  ~S" dims))))
2590 \f
2591 ;;;; MEMBER types
2592
2593 (!define-type-class member)
2594
2595 (!define-type-method (member :negate) (type)
2596   (let ((xset (member-type-xset type))
2597         (fp-zeroes (member-type-fp-zeroes type)))
2598     (if fp-zeroes
2599         ;; Hairy case, which needs to do a bit of float type
2600         ;; canonicalization.
2601         (apply #'type-intersection
2602                (if (xset-empty-p xset)
2603                    *universal-type*
2604                    (make-negation-type
2605                     :type (make-member-type :xset xset)))
2606                (mapcar
2607                 (lambda (x)
2608                   (let* ((opposite (neg-fp-zero x))
2609                          (type (ctype-of opposite)))
2610                     (type-union
2611                      (make-negation-type
2612                       :type (modified-numeric-type type :low nil :high nil))
2613                      (modified-numeric-type type :low nil :high (list opposite))
2614                      (make-member-type :members (list opposite))
2615                      (modified-numeric-type type :low (list opposite) :high nil))))
2616                 fp-zeroes))
2617         ;; Easy case
2618         (make-negation-type :type type))))
2619
2620 (!define-type-method (member :unparse) (type)
2621   (let ((members (member-type-members type)))
2622     (cond
2623       ((equal members '(nil)) 'null)
2624       ((type= type (specifier-type 'standard-char)) 'standard-char)
2625       (t `(member ,@members)))))
2626
2627 (!define-type-method (member :simple-subtypep) (type1 type2)
2628    (values (and (xset-subset-p (member-type-xset type1)
2629                                  (member-type-xset type2))
2630                 (subsetp (member-type-fp-zeroes type1)
2631                          (member-type-fp-zeroes type2)))
2632            t))
2633
2634 (!define-type-method (member :complex-subtypep-arg1) (type1 type2)
2635   (block punt
2636     (mapc-member-type-members
2637      (lambda (elt)
2638        (multiple-value-bind (ok surep) (ctypep elt type2)
2639          (unless surep
2640            (return-from punt (values nil nil)))
2641          (unless ok
2642            (return-from punt (values nil t)))))
2643      type1)
2644     (values t t)))
2645
2646 ;;; We punt if the odd type is enumerable and intersects with the
2647 ;;; MEMBER type. If not enumerable, then it is definitely not a
2648 ;;; subtype of the MEMBER type.
2649 (!define-type-method (member :complex-subtypep-arg2) (type1 type2)
2650   (cond ((not (type-enumerable type1)) (values nil t))
2651         ((types-equal-or-intersect type1 type2)
2652          (invoke-complex-subtypep-arg1-method type1 type2))
2653         (t (values nil t))))
2654
2655 (!define-type-method (member :simple-intersection2) (type1 type2)
2656   (make-member-type :xset (xset-intersection (member-type-xset type1)
2657                                              (member-type-xset type2))
2658                     :fp-zeroes (intersection (member-type-fp-zeroes type1)
2659                                              (member-type-fp-zeroes type2))))
2660
2661 (!define-type-method (member :complex-intersection2) (type1 type2)
2662   (block punt
2663     (let ((xset (alloc-xset))
2664           (fp-zeroes nil))
2665       (mapc-member-type-members
2666        (lambda (member)
2667          (multiple-value-bind (ok sure) (ctypep member type1)
2668            (unless sure
2669              (return-from punt nil))
2670            (when ok
2671              (if (fp-zero-p member)
2672                  (pushnew member fp-zeroes)
2673                  (add-to-xset member xset)))))
2674        type2)
2675       (if (and (xset-empty-p xset) (not fp-zeroes))
2676           *empty-type*
2677           (make-member-type :xset xset :fp-zeroes fp-zeroes)))))
2678
2679 ;;; We don't need a :COMPLEX-UNION2, since the only interesting case is
2680 ;;; a union type, and the member/union interaction is handled by the
2681 ;;; union type method.
2682 (!define-type-method (member :simple-union2) (type1 type2)
2683   (make-member-type :xset (xset-union (member-type-xset type1)
2684                                       (member-type-xset type2))
2685                     :fp-zeroes (union (member-type-fp-zeroes type1)
2686                                       (member-type-fp-zeroes type2))))
2687
2688 (!define-type-method (member :simple-=) (type1 type2)
2689   (let ((xset1 (member-type-xset type1))
2690         (xset2 (member-type-xset type2))
2691         (l1 (member-type-fp-zeroes type1))
2692         (l2 (member-type-fp-zeroes type2)))
2693     (values (and (eql (xset-count xset1) (xset-count xset2))
2694                  (xset-subset-p xset1 xset2)
2695                  (xset-subset-p xset2 xset1)
2696                  (subsetp l1 l2)
2697                  (subsetp l2 l1))
2698             t)))
2699
2700 (!define-type-method (member :complex-=) (type1 type2)
2701   (if (type-enumerable type1)
2702       (multiple-value-bind (val win) (csubtypep type2 type1)
2703         (if (or val (not win))
2704             (values nil nil)
2705             (values nil t)))
2706       (values nil t)))
2707
2708 (!def-type-translator member (&rest members)
2709   (if members
2710       (let (ms numbers char-codes)
2711         (dolist (m (remove-duplicates members))
2712           (typecase m
2713             (float (if (zerop m)
2714                        (push m ms)
2715                        (push (ctype-of m) numbers)))
2716             (real (push (ctype-of m) numbers))
2717            (character (push (sb!xc:char-code m) char-codes))
2718             (t (push m ms))))
2719         (apply #'type-union
2720                (if ms
2721                    (make-member-type :members ms)
2722                    *empty-type*)
2723               (if char-codes
2724                   (make-character-set-type
2725                    :pairs (mapcar (lambda (x) (cons x x))
2726                                   (sort char-codes #'<)))
2727                   *empty-type*)
2728                (nreverse numbers)))
2729       *empty-type*))
2730 \f
2731 ;;;; intersection types
2732 ;;;;
2733 ;;;; Until version 0.6.10.6, SBCL followed the original CMU CL approach
2734 ;;;; of punting on all AND types, not just the unreasonably complicated
2735 ;;;; ones. The change was motivated by trying to get the KEYWORD type
2736 ;;;; to behave sensibly:
2737 ;;;;    ;; reasonable definition
2738 ;;;;    (DEFTYPE KEYWORD () '(AND SYMBOL (SATISFIES KEYWORDP)))
2739 ;;;;    ;; reasonable behavior
2740 ;;;;    (AVER (SUBTYPEP 'KEYWORD 'SYMBOL))
2741 ;;;; Without understanding a little about the semantics of AND, we'd
2742 ;;;; get (SUBTYPEP 'KEYWORD 'SYMBOL)=>NIL,NIL and, for entirely
2743 ;;;; parallel reasons, (SUBTYPEP 'RATIO 'NUMBER)=>NIL,NIL. That's
2744 ;;;; not so good..)
2745 ;;;;
2746 ;;;; We still follow the example of CMU CL to some extent, by punting
2747 ;;;; (to the opaque HAIRY-TYPE) on sufficiently complicated types
2748 ;;;; involving AND.
2749
2750 (!define-type-class intersection)
2751
2752 (!define-type-method (intersection :negate) (type)
2753   (apply #'type-union
2754          (mapcar #'type-negation (intersection-type-types type))))
2755
2756 ;;; A few intersection types have special names. The others just get
2757 ;;; mechanically unparsed.
2758 (!define-type-method (intersection :unparse) (type)
2759   (declare (type ctype type))
2760   (or (find type '(ratio keyword compiled-function) :key #'specifier-type :test #'type=)
2761       `(and ,@(mapcar #'type-specifier (intersection-type-types type)))))
2762
2763 ;;; shared machinery for type equality: true if every type in the set
2764 ;;; TYPES1 matches a type in the set TYPES2 and vice versa
2765 (defun type=-set (types1 types2)
2766   (flet ((type<=-set (x y)
2767            (declare (type list x y))
2768            (every/type (lambda (x y-element)
2769                          (any/type #'type= y-element x))
2770                        x y)))
2771     (and/type (type<=-set types1 types2)
2772               (type<=-set types2 types1))))
2773
2774 ;;; Two intersection types are equal if their subtypes are equal sets.
2775 ;;;
2776 ;;; FIXME: Might it be better to use
2777 ;;;   (AND (SUBTYPEP X Y) (SUBTYPEP Y X))
2778 ;;; instead, since SUBTYPEP is the usual relationship that we care
2779 ;;; most about, so it would be good to leverage any ingenuity there
2780 ;;; in this more obscure method?
2781 (!define-type-method (intersection :simple-=) (type1 type2)
2782   (type=-set (intersection-type-types type1)
2783              (intersection-type-types type2)))
2784
2785 (defun %intersection-complex-subtypep-arg1 (type1 type2)
2786   (type= type1 (type-intersection type1 type2)))
2787
2788 (defun %intersection-simple-subtypep (type1 type2)
2789   (every/type #'%intersection-complex-subtypep-arg1
2790               type1
2791               (intersection-type-types type2)))
2792
2793 (!define-type-method (intersection :simple-subtypep) (type1 type2)
2794   (%intersection-simple-subtypep type1 type2))
2795
2796 (!define-type-method (intersection :complex-subtypep-arg1) (type1 type2)
2797   (%intersection-complex-subtypep-arg1 type1 type2))
2798
2799 (defun %intersection-complex-subtypep-arg2 (type1 type2)
2800   (every/type #'csubtypep type1 (intersection-type-types type2)))
2801
2802 (!define-type-method (intersection :complex-subtypep-arg2) (type1 type2)
2803   (%intersection-complex-subtypep-arg2 type1 type2))
2804
2805 ;;; FIXME: This will look eeriely familiar to readers of the UNION
2806 ;;; :SIMPLE-INTERSECTION2 :COMPLEX-INTERSECTION2 method.  That's
2807 ;;; because it was generated by cut'n'paste methods.  Given that
2808 ;;; intersections and unions have all sorts of symmetries known to
2809 ;;; mathematics, it shouldn't be beyond the ken of some programmers to
2810 ;;; reflect those symmetries in code in a way that ties them together
2811 ;;; more strongly than having two independent near-copies :-/
2812 (!define-type-method (intersection :simple-union2 :complex-union2)
2813                      (type1 type2)
2814   ;; Within this method, type2 is guaranteed to be an intersection
2815   ;; type:
2816   (aver (intersection-type-p type2))
2817   ;; Make sure to call only the applicable methods...
2818   (cond ((and (intersection-type-p type1)
2819               (%intersection-simple-subtypep type1 type2)) type2)
2820         ((and (intersection-type-p type1)
2821               (%intersection-simple-subtypep type2 type1)) type1)
2822         ((and (not (intersection-type-p type1))
2823               (%intersection-complex-subtypep-arg2 type1 type2))
2824          type2)
2825         ((and (not (intersection-type-p type1))
2826               (%intersection-complex-subtypep-arg1 type2 type1))
2827          type1)
2828         ;; KLUDGE: This special (and somewhat hairy) magic is required
2829         ;; to deal with the RATIONAL/INTEGER special case.  The UNION
2830         ;; of (INTEGER * -1) and (AND (RATIONAL * -1/2) (NOT INTEGER))
2831         ;; should be (RATIONAL * -1/2) -- CSR, 2003-02-28
2832         ((and (csubtypep type2 (specifier-type 'ratio))
2833               (numeric-type-p type1)
2834               (csubtypep type1 (specifier-type 'integer))
2835               (csubtypep type2
2836                          (make-numeric-type
2837                           :class 'rational
2838                           :complexp nil
2839                           :low (if (null (numeric-type-low type1))
2840                                    nil
2841                                    (list (1- (numeric-type-low type1))))
2842                           :high (if (null (numeric-type-high type1))
2843                                     nil
2844                                     (list (1+ (numeric-type-high type1)))))))
2845          (type-union type1
2846                      (apply #'type-intersection
2847                             (remove (specifier-type '(not integer))
2848                                     (intersection-type-types type2)
2849                                     :test #'type=))))
2850         (t
2851          (let ((accumulator *universal-type*))
2852            (do ((t2s (intersection-type-types type2) (cdr t2s)))
2853                ((null t2s) accumulator)
2854              (let ((union (type-union type1 (car t2s))))
2855                (when (union-type-p union)
2856                  ;; we have to give up here -- there are all sorts of
2857                  ;; ordering worries, but it's better than before.
2858                  ;; Doing exactly the same as in the UNION
2859                  ;; :SIMPLE/:COMPLEX-INTERSECTION2 method causes stack
2860                  ;; overflow with the mutual recursion never bottoming
2861                  ;; out.
2862                  (if (and (eq accumulator *universal-type*)
2863                           (null (cdr t2s)))
2864                      ;; KLUDGE: if we get here, we have a partially
2865                      ;; simplified result.  While this isn't by any
2866                      ;; means a universal simplification, including
2867                      ;; this logic here means that we can get (OR
2868                      ;; KEYWORD (NOT KEYWORD)) canonicalized to T.
2869                      (return union)
2870                      (return nil)))
2871                (setf accumulator
2872                      (type-intersection accumulator union))))))))
2873
2874 (!def-type-translator and (&whole whole &rest type-specifiers)
2875   (apply #'type-intersection
2876          (mapcar #'specifier-type type-specifiers)))
2877 \f
2878 ;;;; union types
2879
2880 (!define-type-class union)
2881
2882 (!define-type-method (union :negate) (type)
2883   (declare (type ctype type))
2884   (apply #'type-intersection
2885          (mapcar #'type-negation (union-type-types type))))
2886
2887 ;;; The LIST, FLOAT and REAL types have special names.  Other union
2888 ;;; types just get mechanically unparsed.
2889 (!define-type-method (union :unparse) (type)
2890   (declare (type ctype type))
2891   (cond
2892     ((type= type (specifier-type 'list)) 'list)
2893     ((type= type (specifier-type 'float)) 'float)
2894     ((type= type (specifier-type 'real)) 'real)
2895     ((type= type (specifier-type 'sequence)) 'sequence)
2896     ((type= type (specifier-type 'bignum)) 'bignum)
2897     ((type= type (specifier-type 'simple-string)) 'simple-string)
2898     ((type= type (specifier-type 'string)) 'string)
2899     ((type= type (specifier-type 'complex)) 'complex)
2900     ((type= type (specifier-type 'standard-char)) 'standard-char)
2901     (t `(or ,@(mapcar #'type-specifier (union-type-types type))))))
2902
2903 ;;; Two union types are equal if they are each subtypes of each
2904 ;;; other. We need to be this clever because our complex subtypep
2905 ;;; methods are now more accurate; we don't get infinite recursion
2906 ;;; because the simple-subtypep method delegates to complex-subtypep
2907 ;;; of the individual types of type1. - CSR, 2002-04-09
2908 ;;;
2909 ;;; Previous comment, now obsolete, but worth keeping around because
2910 ;;; it is true, though too strong a condition:
2911 ;;;
2912 ;;; Two union types are equal if their subtypes are equal sets.
2913 (!define-type-method (union :simple-=) (type1 type2)
2914   (multiple-value-bind (subtype certain?)
2915       (csubtypep type1 type2)
2916     (if subtype
2917         (csubtypep type2 type1)
2918         ;; we might as well become as certain as possible.
2919         (if certain?
2920             (values nil t)
2921             (multiple-value-bind (subtype certain?)
2922                 (csubtypep type2 type1)
2923               (declare (ignore subtype))
2924               (values nil certain?))))))
2925
2926 (!define-type-method (union :complex-=) (type1 type2)
2927   (declare (ignore type1))
2928   (if (some #'type-might-contain-other-types-p
2929             (union-type-types type2))
2930       (values nil nil)
2931       (values nil t)))
2932
2933 ;;; Similarly, a union type is a subtype of another if and only if
2934 ;;; every element of TYPE1 is a subtype of TYPE2.
2935 (defun union-simple-subtypep (type1 type2)
2936   (every/type (swapped-args-fun #'union-complex-subtypep-arg2)
2937               type2
2938               (union-type-types type1)))
2939
2940 (!define-type-method (union :simple-subtypep) (type1 type2)
2941   (union-simple-subtypep type1 type2))
2942
2943 (defun union-complex-subtypep-arg1 (type1 type2)
2944   (every/type (swapped-args-fun #'csubtypep)
2945               type2
2946               (union-type-types type1)))
2947
2948 (!define-type-method (union :complex-subtypep-arg1) (type1 type2)
2949   (union-complex-subtypep-arg1 type1 type2))
2950
2951 (defun union-complex-subtypep-arg2 (type1 type2)
2952   ;; At this stage, we know that type2 is a union type and type1
2953   ;; isn't. We might as well check this, though:
2954   (aver (union-type-p type2))
2955   (aver (not (union-type-p type1)))
2956   ;; was: (any/type #'csubtypep type1 (union-type-types type2)), which
2957   ;; turns out to be too restrictive, causing bug 91.
2958   ;;
2959   ;; the following reimplementation might look dodgy. It is dodgy. It
2960   ;; depends on the union :complex-= method not doing very much work
2961   ;; -- certainly, not using subtypep. Reasoning:
2962   ;;
2963   ;;     A is a subset of (B1 u B2)
2964   ;; <=> A n (B1 u B2) = A
2965   ;; <=> (A n B1) u (A n B2) = A
2966   ;;
2967   ;; But, we have to be careful not to delegate this type= to
2968   ;; something that could invoke subtypep, which might get us back
2969   ;; here -> stack explosion. We therefore ensure that the second type
2970   ;; (which is the one that's dispatched on) is either a union type
2971   ;; (where we've ensured that the complex-= method will not call
2972   ;; subtypep) or something with no union types involved, in which
2973   ;; case we'll never come back here.
2974   ;;
2975   ;; If we don't do this, then e.g.
2976   ;; (SUBTYPEP '(MEMBER 3) '(OR (SATISFIES FOO) (SATISFIES BAR)))
2977   ;; would loop infinitely, as the member :complex-= method is
2978   ;; implemented in terms of subtypep.
2979   ;;
2980   ;; Ouch. - CSR, 2002-04-10
2981   (multiple-value-bind (sub-value sub-certain?)
2982       (type= type1
2983              (apply #'type-union
2984                     (mapcar (lambda (x) (type-intersection type1 x))
2985                             (union-type-types type2))))
2986     (if sub-certain?
2987         (values sub-value sub-certain?)
2988         ;; The ANY/TYPE expression above is a sufficient condition for
2989         ;; subsetness, but not a necessary one, so we might get a more
2990         ;; certain answer by this CALL-NEXT-METHOD-ish step when the
2991         ;; ANY/TYPE expression is uncertain.
2992         (invoke-complex-subtypep-arg1-method type1 type2))))
2993
2994 (!define-type-method (union :complex-subtypep-arg2) (type1 type2)
2995   (union-complex-subtypep-arg2 type1 type2))
2996
2997 (!define-type-method (union :simple-intersection2 :complex-intersection2)
2998                      (type1 type2)
2999   ;; The CSUBTYPEP clauses here let us simplify e.g.
3000   ;;   (TYPE-INTERSECTION2 (SPECIFIER-TYPE 'LIST)
3001   ;;                       (SPECIFIER-TYPE '(OR LIST VECTOR)))
3002   ;; (where LIST is (OR CONS NULL)).
3003   ;;
3004   ;; The tests are more or less (CSUBTYPEP TYPE1 TYPE2) and vice
3005   ;; versa, but it's important that we pre-expand them into
3006   ;; specialized operations on individual elements of
3007   ;; UNION-TYPE-TYPES, instead of using the ordinary call to
3008   ;; CSUBTYPEP, in order to avoid possibly invoking any methods which
3009   ;; might in turn invoke (TYPE-INTERSECTION2 TYPE1 TYPE2) and thus
3010   ;; cause infinite recursion.
3011   ;;
3012   ;; Within this method, type2 is guaranteed to be a union type:
3013   (aver (union-type-p type2))
3014   ;; Make sure to call only the applicable methods...
3015   (cond ((and (union-type-p type1)
3016               (union-simple-subtypep type1 type2)) type1)
3017         ((and (union-type-p type1)
3018               (union-simple-subtypep type2 type1)) type2)
3019         ((and (not (union-type-p type1))
3020               (union-complex-subtypep-arg2 type1 type2))
3021          type1)
3022         ((and (not (union-type-p type1))
3023               (union-complex-subtypep-arg1 type2 type1))
3024          type2)
3025         (t
3026          ;; KLUDGE: This code accumulates a sequence of TYPE-UNION2
3027          ;; operations in a particular order, and gives up if any of
3028          ;; the sub-unions turn out not to be simple. In other cases
3029          ;; ca. sbcl-0.6.11.15, that approach to taking a union was a
3030          ;; bad idea, since it can overlook simplifications which
3031          ;; might occur if the terms were accumulated in a different
3032          ;; order. It's possible that that will be a problem here too.
3033          ;; However, I can't think of a good example to demonstrate
3034          ;; it, and without an example to demonstrate it I can't write
3035          ;; test cases, and without test cases I don't want to
3036          ;; complicate the code to address what's still a hypothetical
3037          ;; problem. So I punted. -- WHN 2001-03-20
3038          (let ((accumulator *empty-type*))
3039            (dolist (t2 (union-type-types type2) accumulator)
3040              (setf accumulator
3041                    (type-union accumulator
3042                                (type-intersection type1 t2))))))))
3043
3044 (!def-type-translator or (&rest type-specifiers)
3045   (apply #'type-union
3046          (mapcar #'specifier-type
3047                  type-specifiers)))
3048 \f
3049 ;;;; CONS types
3050
3051 (!define-type-class cons)
3052
3053 (!def-type-translator cons (&optional (car-type-spec '*) (cdr-type-spec '*))
3054   (let ((car-type (single-value-specifier-type car-type-spec))
3055         (cdr-type (single-value-specifier-type cdr-type-spec)))
3056     (make-cons-type car-type cdr-type)))
3057
3058 (!define-type-method (cons :negate) (type)
3059   (if (and (eq (cons-type-car-type type) *universal-type*)
3060            (eq (cons-type-cdr-type type) *universal-type*))
3061       (make-negation-type :type type)
3062       (type-union
3063        (make-negation-type :type (specifier-type 'cons))
3064        (cond
3065          ((and (not (eq (cons-type-car-type type) *universal-type*))
3066                (not (eq (cons-type-cdr-type type) *universal-type*)))
3067           (type-union
3068            (make-cons-type
3069             (type-negation (cons-type-car-type type))
3070             *universal-type*)
3071            (make-cons-type
3072             *universal-type*
3073             (type-negation (cons-type-cdr-type type)))))
3074          ((not (eq (cons-type-car-type type) *universal-type*))
3075           (make-cons-type
3076            (type-negation (cons-type-car-type type))
3077            *universal-type*))
3078          ((not (eq (cons-type-cdr-type type) *universal-type*))
3079           (make-cons-type
3080            *universal-type*
3081            (type-negation (cons-type-cdr-type type))))
3082          (t (bug "Weird CONS type ~S" type))))))
3083
3084 (!define-type-method (cons :unparse) (type)
3085   (let ((car-eltype (type-specifier (cons-type-car-type type)))
3086         (cdr-eltype (type-specifier (cons-type-cdr-type type))))
3087     (if (and (member car-eltype '(t *))
3088              (member cdr-eltype '(t *)))
3089         'cons
3090         `(cons ,car-eltype ,cdr-eltype))))
3091
3092 (!define-type-method (cons :simple-=) (type1 type2)
3093   (declare (type cons-type type1 type2))
3094   (multiple-value-bind (car-match car-win)
3095       (type= (cons-type-car-type type1) (cons-type-car-type type2))
3096     (multiple-value-bind (cdr-match cdr-win)
3097         (type= (cons-type-cdr-type type1) (cons-type-cdr-type type2))
3098       (cond ((and car-match cdr-match)
3099              (aver (and car-win cdr-win))
3100              (values t t))
3101             (t
3102              (values nil
3103                      ;; FIXME: Ideally we would like to detect and handle
3104                      ;;  (CONS UNKNOWN INTEGER) (CONS UNKNOWN SYMBOL) => NIL, T
3105                      ;; but just returning a secondary true on (and car-win cdr-win)
3106                      ;; unfortunately breaks other things. --NS 2006-08-16
3107                      (and (or (and (not car-match) car-win)
3108                               (and (not cdr-match) cdr-win))
3109                           (not (and (cons-type-might-be-empty-type type1)
3110                                     (cons-type-might-be-empty-type type2))))))))))
3111
3112 (!define-type-method (cons :simple-subtypep) (type1 type2)
3113   (declare (type cons-type type1 type2))
3114   (multiple-value-bind (val-car win-car)
3115       (csubtypep (cons-type-car-type type1) (cons-type-car-type type2))
3116     (multiple-value-bind (val-cdr win-cdr)
3117         (csubtypep (cons-type-cdr-type type1) (cons-type-cdr-type type2))
3118       (if (and val-car val-cdr)
3119           (values t (and win-car win-cdr))
3120           (values nil (or (and (not val-car) win-car)
3121                           (and (not val-cdr) win-cdr)))))))
3122
3123 ;;; Give up if a precise type is not possible, to avoid returning
3124 ;;; overly general types.
3125 (!define-type-method (cons :simple-union2) (type1 type2)
3126   (declare (type cons-type type1 type2))
3127   (let ((car-type1 (cons-type-car-type type1))
3128         (car-type2 (cons-type-car-type type2))
3129         (cdr-type1 (cons-type-cdr-type type1))
3130         (cdr-type2 (cons-type-cdr-type type2))
3131         car-not1
3132         car-not2)
3133     ;; UGH.  -- CSR, 2003-02-24
3134     (macrolet ((frob-car (car1 car2 cdr1 cdr2
3135                           &optional (not1 nil not1p))
3136                  `(type-union
3137                    (make-cons-type ,car1 (type-union ,cdr1 ,cdr2))
3138                    (make-cons-type
3139                     (type-intersection ,car2
3140                      ,(if not1p
3141                           not1
3142                           `(type-negation ,car1)))
3143                     ,cdr2))))
3144       (cond ((type= car-type1 car-type2)
3145              (make-cons-type car-type1
3146                              (type-union cdr-type1 cdr-type2)))
3147             ((type= cdr-type1 cdr-type2)
3148              (make-cons-type (type-union car-type1 car-type2)
3149                              cdr-type1))
3150             ((csubtypep car-type1 car-type2)
3151              (frob-car car-type1 car-type2 cdr-type1 cdr-type2))
3152             ((csubtypep car-type2 car-type1)
3153              (frob-car car-type2 car-type1 cdr-type2 cdr-type1))
3154             ;; more general case of the above, but harder to compute
3155             ((progn
3156                (setf car-not1 (type-negation car-type1))
3157                (multiple-value-bind (yes win)
3158                    (csubtypep car-type2 car-not1)
3159                  (and (not yes) win)))
3160              (frob-car car-type1 car-type2 cdr-type1 cdr-type2 car-not1))
3161             ((progn
3162                (setf car-not2 (type-negation car-type2))
3163                (multiple-value-bind (yes win)
3164                    (csubtypep car-type1 car-not2)
3165                  (and (not yes) win)))
3166              (frob-car car-type2 car-type1 cdr-type2 cdr-type1 car-not2))
3167             ;; Don't put these in -- consider the effect of taking the
3168             ;; union of (CONS (INTEGER 0 2) (INTEGER 5 7)) and
3169             ;; (CONS (INTEGER 0 3) (INTEGER 5 6)).
3170             #+nil
3171             ((csubtypep cdr-type1 cdr-type2)
3172              (frob-cdr car-type1 car-type2 cdr-type1 cdr-type2))
3173             #+nil
3174             ((csubtypep cdr-type2 cdr-type1)
3175              (frob-cdr car-type2 car-type1 cdr-type2 cdr-type1))))))
3176
3177 (!define-type-method (cons :simple-intersection2) (type1 type2)
3178   (declare (type cons-type type1 type2))
3179   (let ((car-int2 (type-intersection2 (cons-type-car-type type1)
3180                                       (cons-type-car-type type2)))
3181         (cdr-int2 (type-intersection2 (cons-type-cdr-type type1)
3182                                       (cons-type-cdr-type type2))))
3183     (cond
3184       ((and car-int2 cdr-int2) (make-cons-type car-int2 cdr-int2))
3185       (car-int2 (make-cons-type car-int2
3186                                 (type-intersection
3187                                  (cons-type-cdr-type type1)
3188                                  (cons-type-cdr-type type2))))
3189       (cdr-int2 (make-cons-type
3190                  (type-intersection (cons-type-car-type type1)
3191                                     (cons-type-car-type type2))
3192                  cdr-int2)))))
3193
3194 (!define-superclasses cons ((cons)) !cold-init-forms)
3195 \f
3196 ;;;; CHARACTER-SET types
3197
3198 (!define-type-class character-set)
3199
3200 (!def-type-translator character-set
3201     (&optional (pairs '((0 . #.(1- sb!xc:char-code-limit)))))
3202   (make-character-set-type :pairs pairs))
3203
3204 (!define-type-method (character-set :negate) (type)
3205   (let ((pairs (character-set-type-pairs type)))
3206     (if (and (= (length pairs) 1)
3207              (= (caar pairs) 0)
3208              (= (cdar pairs) (1- sb!xc:char-code-limit)))
3209         (make-negation-type :type type)
3210         (let ((not-character
3211                (make-negation-type
3212                 :type (make-character-set-type
3213                        :pairs '((0 . #.(1- sb!xc:char-code-limit)))))))
3214           (type-union
3215            not-character
3216            (make-character-set-type
3217             :pairs (let (not-pairs)
3218                      (when (> (caar pairs) 0)
3219                        (push (cons 0 (1- (caar pairs))) not-pairs))
3220                      (do* ((tail pairs (cdr tail))
3221                            (high1 (cdar tail) (cdar tail))
3222                            (low2 (caadr tail) (caadr tail)))
3223                           ((null (cdr tail))
3224                            (when (< (cdar tail) (1- sb!xc:char-code-limit))
3225                              (push (cons (1+ (cdar tail))
3226                                          (1- sb!xc:char-code-limit))
3227                                    not-pairs))
3228                            (nreverse not-pairs))
3229                        (push (cons (1+ high1) (1- low2)) not-pairs)))))))))
3230
3231 (!define-type-method (character-set :unparse) (type)
3232   (cond
3233     ((type= type (specifier-type 'character)) 'character)
3234     ((type= type (specifier-type 'base-char)) 'base-char)
3235     ((type= type (specifier-type 'extended-char)) 'extended-char)
3236     ((type= type (specifier-type 'standard-char)) 'standard-char)
3237     (t (let ((pairs (character-set-type-pairs type)))
3238         `(member ,@(loop for (low . high) in pairs
3239                          nconc (loop for code from low upto high
3240                                      collect (sb!xc:code-char code))))))))
3241
3242 (!define-type-method (character-set :simple-=) (type1 type2)
3243   (let ((pairs1 (character-set-type-pairs type1))
3244        (pairs2 (character-set-type-pairs type2)))
3245     (values (equal pairs1 pairs2) t)))
3246
3247 (!define-type-method (character-set :simple-subtypep) (type1 type2)
3248   (values
3249    (dolist (pair (character-set-type-pairs type1) t)
3250      (unless (position pair (character-set-type-pairs type2)
3251                       :test (lambda (x y) (and (>= (car x) (car y))
3252                                                (<= (cdr x) (cdr y)))))
3253        (return nil)))
3254    t))
3255
3256 (!define-type-method (character-set :simple-union2) (type1 type2)
3257   ;; KLUDGE: the canonizing in the MAKE-CHARACTER-SET-TYPE function
3258   ;; actually does the union for us.  It might be a little fragile to
3259   ;; rely on it.
3260   (make-character-set-type
3261    :pairs (merge 'list
3262                 (copy-alist (character-set-type-pairs type1))
3263                 (copy-alist (character-set-type-pairs type2))
3264                 #'< :key #'car)))
3265
3266 (!define-type-method (character-set :simple-intersection2) (type1 type2)
3267   ;; KLUDGE: brute force.
3268 #|
3269   (let (pairs)
3270     (dolist (pair1 (character-set-type-pairs type1)
3271             (make-character-set-type
3272              :pairs (sort pairs #'< :key #'car)))
3273       (dolist (pair2 (character-set-type-pairs type2))
3274        (cond
3275          ((<= (car pair1) (car pair2) (cdr pair1))
3276           (push (cons (car pair2) (min (cdr pair1) (cdr pair2))) pairs))
3277          ((<= (car pair2) (car pair1) (cdr pair2))
3278           (push (cons (car pair1) (min (cdr pair1) (cdr pair2))) pairs))))))
3279 |#
3280   (make-character-set-type
3281    :pairs (intersect-type-pairs
3282            (character-set-type-pairs type1)
3283            (character-set-type-pairs type2))))
3284
3285 ;;;
3286 ;;; Intersect two ordered lists of pairs
3287 ;;; Each list is of the form ((start1 . end1) ... (startn . endn)),
3288 ;;; where start1 <= end1 < start2 <= end2 < ... < startn <= endn.
3289 ;;; Each pair represents the integer interval start..end.
3290 ;;;
3291 (defun intersect-type-pairs (alist1 alist2)
3292   (if (and alist1 alist2)
3293       (let ((res nil)
3294             (pair1 (pop alist1))
3295             (pair2 (pop alist2)))
3296         (loop
3297          (when (> (car pair1) (car pair2))
3298            (rotatef pair1 pair2)
3299            (rotatef alist1 alist2))
3300          (let ((pair1-cdr (cdr pair1)))
3301            (cond
3302             ((> (car pair2) pair1-cdr)
3303              ;; No over lap -- discard pair1
3304              (unless alist1 (return))
3305              (setq pair1 (pop alist1)))
3306             ((<= (cdr pair2) pair1-cdr)
3307              (push (cons (car pair2) (cdr pair2)) res)
3308              (cond
3309               ((= (cdr pair2) pair1-cdr)
3310                (unless alist1 (return))
3311                (unless alist2 (return))
3312                (setq pair1 (pop alist1)
3313                      pair2 (pop alist2)))
3314               (t ;; (< (cdr pair2) pair1-cdr)
3315                (unless alist2 (return))
3316                (setq pair1 (cons (1+ (cdr pair2)) pair1-cdr))
3317                (setq pair2 (pop alist2)))))
3318             (t ;; (> (cdr pair2) (cdr pair1))
3319              (push (cons (car pair2) pair1-cdr) res)
3320              (unless alist1 (return))
3321              (setq pair2 (cons (1+ pair1-cdr) (cdr pair2)))
3322              (setq pair1 (pop alist1))))))
3323         (nreverse res))
3324     nil))
3325
3326 \f
3327 ;;; Return the type that describes all objects that are in X but not
3328 ;;; in Y. If we can't determine this type, then return NIL.
3329 ;;;
3330 ;;; For now, we only are clever dealing with union and member types.
3331 ;;; If either type is not a union type, then we pretend that it is a
3332 ;;; union of just one type. What we do is remove from X all the types
3333 ;;; that are a subtype any type in Y. If any type in X intersects with
3334 ;;; a type in Y but is not a subtype, then we give up.
3335 ;;;
3336 ;;; We must also special-case any member type that appears in the
3337 ;;; union. We remove from X's members all objects that are TYPEP to Y.
3338 ;;; If Y has any members, we must be careful that none of those
3339 ;;; members are CTYPEP to any of Y's non-member types. We give up in
3340 ;;; this case, since to compute that difference we would have to break
3341 ;;; the type from X into some collection of types that represents the
3342 ;;; type without that particular element. This seems too hairy to be
3343 ;;; worthwhile, given its low utility.
3344 (defun type-difference (x y)
3345   (let ((x-types (if (union-type-p x) (union-type-types x) (list x)))
3346         (y-types (if (union-type-p y) (union-type-types y) (list y))))
3347     (collect ((res))
3348       (dolist (x-type x-types)
3349         (if (member-type-p x-type)
3350             (let ((xset (alloc-xset))
3351                   (fp-zeroes nil))
3352               (mapc-member-type-members
3353                (lambda (elt)
3354                  (multiple-value-bind (ok sure) (ctypep elt y)
3355                    (unless sure
3356                      (return-from type-difference nil))
3357                    (unless ok
3358                      (if (fp-zero-p elt)
3359                          (pushnew elt fp-zeroes)
3360                          (add-to-xset elt xset)))))
3361                x-type)
3362               (unless (and (xset-empty-p xset) (not fp-zeroes))
3363                 (res (make-member-type :xset xset :fp-zeroes fp-zeroes))))
3364             (dolist (y-type y-types (res x-type))
3365               (multiple-value-bind (val win) (csubtypep x-type y-type)
3366                 (unless win (return-from type-difference nil))
3367                 (when val (return))
3368                 (when (types-equal-or-intersect x-type y-type)
3369                   (return-from type-difference nil))))))
3370       (let ((y-mem (find-if #'member-type-p y-types)))
3371         (when y-mem
3372           (dolist (x-type x-types)
3373             (unless (member-type-p x-type)
3374               (mapc-member-type-members
3375                (lambda (member)
3376                  (multiple-value-bind (ok sure) (ctypep member x-type)
3377                    (when (or (not sure) ok)
3378                      (return-from type-difference nil))))
3379                y-mem)))))
3380       (apply #'type-union (res)))))
3381 \f
3382 (!def-type-translator array (&optional (element-type '*)
3383                                        (dimensions '*))
3384   (specialize-array-type
3385    (make-array-type :dimensions (canonical-array-dimensions dimensions)
3386                     :complexp :maybe
3387                     :element-type (if (eq element-type '*)
3388                                       *wild-type*
3389                                       (specifier-type element-type)))))
3390
3391 (!def-type-translator simple-array (&optional (element-type '*)
3392                                               (dimensions '*))
3393   (specialize-array-type
3394    (make-array-type :dimensions (canonical-array-dimensions dimensions)
3395                     :complexp nil
3396                     :element-type (if (eq element-type '*)
3397                                       *wild-type*
3398                                       (specifier-type element-type)))))
3399 \f
3400 ;;;; utilities shared between cross-compiler and target system
3401
3402 ;;; Does the type derived from compilation of an actual function
3403 ;;; definition satisfy declarations of a function's type?
3404 (defun defined-ftype-matches-declared-ftype-p (defined-ftype declared-ftype)
3405   (declare (type ctype defined-ftype declared-ftype))
3406   (flet ((is-built-in-class-function-p (ctype)
3407            (and (built-in-classoid-p ctype)
3408                 (eq (built-in-classoid-name ctype) 'function))))
3409     (cond (;; DECLARED-FTYPE could certainly be #<BUILT-IN-CLASS FUNCTION>;
3410            ;; that's what happens when we (DECLAIM (FTYPE FUNCTION FOO)).
3411            (is-built-in-class-function-p declared-ftype)
3412            ;; In that case, any definition satisfies the declaration.
3413            t)
3414           (;; It's not clear whether or how DEFINED-FTYPE might be
3415            ;; #<BUILT-IN-CLASS FUNCTION>, but it's not obviously
3416            ;; invalid, so let's handle that case too, just in case.
3417            (is-built-in-class-function-p defined-ftype)
3418            ;; No matter what DECLARED-FTYPE might be, we can't prove
3419            ;; that an object of type FUNCTION doesn't satisfy it, so
3420            ;; we return success no matter what.
3421            t)
3422           (;; Otherwise both of them must be FUN-TYPE objects.
3423            t
3424            ;; FIXME: For now we only check compatibility of the return
3425            ;; type, not argument types, and we don't even check the
3426            ;; return type very precisely (as per bug 94a). It would be
3427            ;; good to do a better job. Perhaps to check the
3428            ;; compatibility of the arguments, we should (1) redo
3429            ;; VALUES-TYPES-EQUAL-OR-INTERSECT as
3430            ;; ARGS-TYPES-EQUAL-OR-INTERSECT, and then (2) apply it to
3431            ;; the ARGS-TYPE slices of the FUN-TYPEs. (ARGS-TYPE
3432            ;; is a base class both of VALUES-TYPE and of FUN-TYPE.)
3433            (values-types-equal-or-intersect
3434             (fun-type-returns defined-ftype)
3435             (fun-type-returns declared-ftype))))))
3436
3437 ;;; This messy case of CTYPE for NUMBER is shared between the
3438 ;;; cross-compiler and the target system.
3439 (defun ctype-of-number (x)
3440   (let ((num (if (complexp x) (realpart x) x)))
3441     (multiple-value-bind (complexp low high)
3442         (if (complexp x)
3443             (let ((imag (imagpart x)))
3444               (values :complex (min num imag) (max num imag)))
3445             (values :real num num))
3446       (make-numeric-type :class (etypecase num
3447                                   (integer (if (complexp x)
3448                                                (if (integerp (imagpart x))
3449                                                    'integer
3450                                                    'rational)
3451                                                'integer))
3452                                   (rational 'rational)
3453                                   (float 'float))
3454                          :format (and (floatp num) (float-format-name num))
3455                          :complexp complexp
3456                          :low low
3457                          :high high))))
3458 \f
3459 (locally
3460   ;; Why SAFETY 0? To suppress the is-it-the-right-structure-type
3461   ;; checking for declarations in structure accessors. Otherwise we
3462   ;; can get caught in a chicken-and-egg bootstrapping problem, whose
3463   ;; symptom on x86 OpenBSD sbcl-0.pre7.37.flaky5.22 is an illegal
3464   ;; instruction trap. I haven't tracked it down, but I'm guessing it
3465   ;; has to do with setting LAYOUTs when the LAYOUT hasn't been set
3466   ;; yet. -- WHN
3467   (declare (optimize (safety 0)))
3468   (!defun-from-collected-cold-init-forms !late-type-cold-init))
3469
3470 (/show0 "late-type.lisp end of file")