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