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