0.7.1.32:
[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 ;;; TYPE-UNION (and the OR type) doesn't properly canonicalize an
26 ;;; exhaustive partition or coalesce contiguous ranges of numeric
27 ;;; types.
28 ;;;
29 ;;; There are all sorts of nasty problems with open bounds on FLOAT
30 ;;; types (and probably FLOAT types in general.)
31 ;;;
32 ;;; RATIO and BIGNUM are not recognized as numeric types.
33
34 ;;; FIXME: This really should go away. Alas, it doesn't seem to be so
35 ;;; simple to make it go away.. (See bug 123 in BUGS file.)
36 (defvar *use-implementation-types* t ; actually initialized in cold init
37   #!+sb-doc
38   "*USE-IMPLEMENTATION-TYPES* is a semi-public flag which determines how
39    restrictive we are in determining type membership. If two types are the
40    same in the implementation, then we will consider them them the same when
41    this switch is on. When it is off, we try to be as restrictive as the
42    language allows, allowing us to detect more errors. Currently, this only
43    affects array types.")
44 (!cold-init-forms (setq *use-implementation-types* t))
45
46 ;;; These functions are used as method for types which need a complex
47 ;;; subtypep method to handle some superclasses, but cover a subtree
48 ;;; of the type graph (i.e. there is no simple way for any other type
49 ;;; class to be a subtype.) There are always still complex ways,
50 ;;; namely UNION and MEMBER types, so we must give TYPE1's method a
51 ;;; chance to run, instead of immediately returning NIL, T.
52 (defun delegate-complex-subtypep-arg2 (type1 type2)
53   (let ((subtypep-arg1
54          (type-class-complex-subtypep-arg1
55           (type-class-info type1))))
56     (if subtypep-arg1
57         (funcall subtypep-arg1 type1 type2)
58         (values nil t))))
59 (defun delegate-complex-intersection2 (type1 type2)
60   (let ((method (type-class-complex-intersection2 (type-class-info type1))))
61     (if (and method (not (eq method #'delegate-complex-intersection2)))
62         (funcall method type2 type1)
63         (hierarchical-intersection2 type1 type2))))
64
65 ;;; This is used by !DEFINE-SUPERCLASSES to define the SUBTYPE-ARG1
66 ;;; method. INFO is a list of conses
67 ;;;   (SUPERCLASS-CLASS . {GUARD-TYPE-SPECIFIER | NIL}).
68 ;;; This will never be called with a hairy type as TYPE2, since the
69 ;;; hairy type TYPE2 method gets first crack.
70 (defun !has-superclasses-complex-subtypep-arg1 (type1 type2 info)
71   (values
72    (and (sb!xc:typep type2 'sb!xc:class)
73         (dolist (x info nil)
74           (when (or (not (cdr x))
75                     (csubtypep type1 (specifier-type (cdr x))))
76             (return
77              (or (eq type2 (car x))
78                  (let ((inherits (layout-inherits (class-layout (car x)))))
79                    (dotimes (i (length inherits) nil)
80                      (when (eq type2 (layout-class (svref inherits i)))
81                        (return t)))))))))
82    t))
83
84 ;;; This function takes a list of specs, each of the form
85 ;;;    (SUPERCLASS-NAME &OPTIONAL GUARD).
86 ;;; Consider one spec (with no guard): any instance of the named
87 ;;; TYPE-CLASS is also a subtype of the named superclass and of any of
88 ;;; its superclasses. If there are multiple specs, then some will have
89 ;;; guards. We choose the first spec whose guard is a supertype of
90 ;;; TYPE1 and use its superclass. In effect, a sequence of guards
91 ;;;    G0, G1, G2
92 ;;; is actually
93 ;;;    G0,(and G1 (not G0)), (and G2 (not (or G0 G1))).
94 ;;;
95 ;;; WHEN controls when the forms are executed.
96 (defmacro !define-superclasses (type-class-name specs when)
97   (let ((type-class (gensym "TYPE-CLASS-"))
98         (info (gensym "INFO")))
99     `(,when
100        (let ((,type-class (type-class-or-lose ',type-class-name))
101              (,info (mapcar (lambda (spec)
102                               (destructuring-bind
103                                   (super &optional guard)
104                                   spec
105                                 (cons (sb!xc:find-class super) guard)))
106                             ',specs)))
107          (setf (type-class-complex-subtypep-arg1 ,type-class)
108                (lambda (type1 type2)
109                  (!has-superclasses-complex-subtypep-arg1 type1 type2 ,info)))
110          (setf (type-class-complex-subtypep-arg2 ,type-class)
111                #'delegate-complex-subtypep-arg2)
112          (setf (type-class-complex-intersection2 ,type-class)
113                #'delegate-complex-intersection2)))))
114 \f
115 ;;;; FUNCTION and VALUES types
116 ;;;;
117 ;;;; Pretty much all of the general type operations are illegal on
118 ;;;; VALUES types, since we can't discriminate using them, do
119 ;;;; SUBTYPEP, etc. FUNCTION types are acceptable to the normal type
120 ;;;; operations, but are generally considered to be equivalent to
121 ;;;; FUNCTION. These really aren't true types in any type theoretic
122 ;;;; sense, but we still parse them into CTYPE structures for two
123 ;;;; reasons:
124
125 ;;;; -- Parsing and unparsing work the same way, and indeed we can't
126 ;;;;    tell whether a type is a function or values type without
127 ;;;;    parsing it.
128 ;;;; -- Many of the places that can be annotated with real types can
129 ;;;;    also be annotated with function or values types.
130
131 ;;; the description of a &KEY argument
132 (defstruct (key-info #-sb-xc-host (:pure t)
133                      (:copier nil))
134   ;; the key (not necessarily a keyword in ANSI Common Lisp)
135   (name (missing-arg) :type symbol)
136   ;; the type of the argument value
137   (type (missing-arg) :type ctype))
138
139 (!define-type-method (values :simple-subtypep :complex-subtypep-arg1)
140                      (type1 type2)
141   (declare (ignore type2))
142   ;; FIXME: should be TYPE-ERROR, here and in next method
143   (error "SUBTYPEP is illegal on this type:~%  ~S" (type-specifier type1)))
144
145 (!define-type-method (values :complex-subtypep-arg2)
146                      (type1 type2)
147   (declare (ignore type1))
148   (error "SUBTYPEP is illegal on this type:~%  ~S" (type-specifier type2)))
149
150 (!define-type-method (values :unparse) (type)
151   (cons 'values (unparse-args-types type)))
152
153 ;;; Return true if LIST1 and LIST2 have the same elements in the same
154 ;;; positions according to TYPE=. We return NIL, NIL if there is an
155 ;;; uncertain comparison.
156 (defun type=-list (list1 list2)
157   (declare (list list1 list2))
158   (do ((types1 list1 (cdr types1))
159        (types2 list2 (cdr types2)))
160       ((or (null types1) (null types2))
161        (if (or types1 types2)
162            (values nil t)
163            (values t t)))
164     (multiple-value-bind (val win)
165         (type= (first types1) (first types2))
166       (unless win
167         (return (values nil nil)))
168       (unless val
169         (return (values nil t))))))
170
171 (!define-type-method (values :simple-=) (type1 type2)
172   (let ((rest1 (args-type-rest type1))
173         (rest2 (args-type-rest type2)))
174     (cond ((or (args-type-keyp type1) (args-type-keyp type2)
175                (args-type-allowp type1) (args-type-allowp type2))
176            (values nil nil))
177           ((and rest1 rest2 (type/= rest1 rest2))
178            (type= rest1 rest2))
179           ((or rest1 rest2)
180            (values nil t))
181           (t
182            (multiple-value-bind (req-val req-win)
183                (type=-list (values-type-required type1)
184                            (values-type-required type2))
185              (multiple-value-bind (opt-val opt-win)
186                  (type=-list (values-type-optional type1)
187                              (values-type-optional type2))
188                (values (and req-val opt-val) (and req-win opt-win))))))))
189
190 (!define-type-class function)
191
192 ;;; a flag that we can bind to cause complex function types to be
193 ;;; unparsed as FUNCTION. This is useful when we want a type that we
194 ;;; can pass to TYPEP.
195 (defvar *unparse-fun-type-simplify*)
196 (!cold-init-forms (setq *unparse-fun-type-simplify* nil))
197
198 (!define-type-method (function :unparse) (type)
199   (if *unparse-fun-type-simplify*
200       'function
201       (list 'function
202             (if (fun-type-wild-args type)
203                 '*
204                 (unparse-args-types type))
205             (type-specifier
206              (fun-type-returns type)))))
207
208 ;;; Since all function types are equivalent to FUNCTION, they are all
209 ;;; subtypes of each other.
210 (!define-type-method (function :simple-subtypep) (type1 type2)
211   (declare (ignore type1 type2))
212   (values t t))
213
214 (!define-superclasses function ((function)) !cold-init-forms)
215
216 ;;; The union or intersection of two FUNCTION types is FUNCTION.
217 (!define-type-method (function :simple-union2) (type1 type2)
218   (declare (ignore type1 type2))
219   (specifier-type 'function))
220 (!define-type-method (function :simple-intersection2) (type1 type2)
221   (declare (ignore type1 type2))
222   (specifier-type 'function))
223
224 ;;; ### Not very real, but good enough for redefining transforms
225 ;;; according to type:
226 (!define-type-method (function :simple-=) (type1 type2)
227   (values (equalp type1 type2) t))
228
229 (!define-type-class constant :inherits values)
230
231 (!define-type-method (constant :unparse) (type)
232   `(constant-arg ,(type-specifier (constant-type-type type))))
233
234 (!define-type-method (constant :simple-=) (type1 type2)
235   (type= (constant-type-type type1) (constant-type-type type2)))
236
237 (!def-type-translator constant-arg (type)
238   (make-constant-type :type (specifier-type type)))
239
240 ;;; Given a LAMBDA-LIST-like values type specification and an ARGS-TYPE
241 ;;; structure, fill in the slots in the structure accordingly. This is
242 ;;; used for both FUNCTION and VALUES types.
243 (declaim (ftype (function (list args-type) (values)) parse-args-types))
244 (defun parse-args-types (lambda-list result)
245   (multiple-value-bind (required optional restp rest keyp keys allowp aux)
246       (parse-lambda-list lambda-list)
247     (when aux
248       (error "&AUX in a FUNCTION or VALUES type: ~S." lambda-list))
249     (setf (args-type-required result) (mapcar #'specifier-type required))
250     (setf (args-type-optional result) (mapcar #'specifier-type optional))
251     (setf (args-type-rest result) (if restp (specifier-type rest) nil))
252     (setf (args-type-keyp result) keyp)
253     (collect ((key-info))
254       (dolist (key keys)
255         (unless (proper-list-of-length-p key 2)
256           (error "Keyword type description is not a two-list: ~S." key))
257         (let ((kwd (first key)))
258           (when (find kwd (key-info) :key #'key-info-name)
259             (error "~@<repeated keyword ~S in lambda list: ~2I~_~S~:>"
260                    kwd lambda-list))
261           (key-info (make-key-info :name kwd
262                                    :type (specifier-type (second key))))))
263       (setf (args-type-keywords result) (key-info)))
264     (setf (args-type-allowp result) allowp)
265     (values)))
266
267 ;;; Return the lambda-list-like type specification corresponding
268 ;;; to an ARGS-TYPE.
269 (declaim (ftype (function (args-type) list) unparse-args-types))
270 (defun unparse-args-types (type)
271   (collect ((result))
272
273     (dolist (arg (args-type-required type))
274       (result (type-specifier arg)))
275
276     (when (args-type-optional type)
277       (result '&optional)
278       (dolist (arg (args-type-optional type))
279         (result (type-specifier arg))))
280
281     (when (args-type-rest type)
282       (result '&rest)
283       (result (type-specifier (args-type-rest type))))
284
285     (when (args-type-keyp type)
286       (result '&key)
287       (dolist (key (args-type-keywords type))
288         (result (list (key-info-name key)
289                       (type-specifier (key-info-type key))))))
290
291     (when (args-type-allowp type)
292       (result '&allow-other-keys))
293
294     (result)))
295
296 (!def-type-translator function (&optional (args '*) (result '*))
297   (let ((res (make-fun-type :returns (values-specifier-type result))))
298     (if (eq args '*)
299         (setf (fun-type-wild-args res) t)
300         (parse-args-types args res))
301     res))
302
303 (!def-type-translator values (&rest values)
304   (let ((res (make-values-type)))
305     (parse-args-types values res)
306     res))
307 \f
308 ;;;; VALUES types interfaces
309 ;;;;
310 ;;;; We provide a few special operations that can be meaningfully used
311 ;;;; on VALUES types (as well as on any other type).
312
313 ;;; Return the type of the first value indicated by TYPE. This is used
314 ;;; by people who don't want to have to deal with VALUES types.
315 #!-sb-fluid (declaim (freeze-type values-type))
316 ; (inline single-value-type))
317 (defun single-value-type (type)
318   (declare (type ctype type))
319   (cond ((values-type-p type)
320          (or (car (args-type-required type))
321              (if (args-type-optional type)
322                  (type-union (car (args-type-optional type))
323                              (specifier-type 'null)))
324              (args-type-rest type)
325              (specifier-type 'null)))
326         ((eq type *wild-type*)
327          *universal-type*)
328         (t
329          type)))
330
331 ;;; Return the minimum number of arguments that a function can be
332 ;;; called with, and the maximum number or NIL. If not a function
333 ;;; type, return NIL, NIL.
334 (defun fun-type-nargs (type)
335   (declare (type ctype type))
336   (if (fun-type-p type)
337       (let ((fixed (length (args-type-required type))))
338         (if (or (args-type-rest type)
339                 (args-type-keyp type)
340                 (args-type-allowp type))
341             (values fixed nil)
342             (values fixed (+ fixed (length (args-type-optional type))))))
343       (values nil nil)))
344
345 ;;; Determine whether TYPE corresponds to a definite number of values.
346 ;;; The first value is a list of the types for each value, and the
347 ;;; second value is the number of values. If the number of values is
348 ;;; not fixed, then return NIL and :UNKNOWN.
349 (defun values-types (type)
350   (declare (type ctype type))
351   (cond ((eq type *wild-type*)
352          (values nil :unknown))
353         ((not (values-type-p type))
354          (values (list type) 1))
355         ((or (args-type-optional type)
356              (args-type-rest type)
357              (args-type-keyp type)
358              (args-type-allowp type))
359          (values nil :unknown))
360         (t
361          (let ((req (args-type-required type)))
362            (values (mapcar #'single-value-type req) (length req))))))
363
364 ;;; Return two values:
365 ;;; 1. A list of all the positional (fixed and optional) types.
366 ;;; 2. The &REST type (if any). If keywords allowed, *UNIVERSAL-TYPE*.
367 ;;;    If no keywords or &REST, then the DEFAULT-TYPE.
368 (defun values-type-types (type &optional (default-type *empty-type*))
369   (declare (type values-type type))
370   (values (append (args-type-required type)
371                   (args-type-optional type))
372           (cond ((args-type-keyp type) *universal-type*)
373                 ((args-type-rest type))
374                 (t
375                  default-type))))
376
377 ;;; Return a list of OPERATION applied to the types in TYPES1 and
378 ;;; TYPES2, padding with REST2 as needed. TYPES1 must not be shorter
379 ;;; than TYPES2. The second value is T if OPERATION always returned a
380 ;;; true second value.
381 (defun fixed-values-op (types1 types2 rest2 operation)
382   (declare (list types1 types2) (type ctype rest2) (type function operation))
383   (let ((exact t))
384     (values (mapcar (lambda (t1 t2)
385                       (multiple-value-bind (res win)
386                           (funcall operation t1 t2)
387                         (unless win
388                           (setq exact nil))
389                         res))
390                     types1
391                     (append types2
392                             (make-list (- (length types1) (length types2))
393                                        :initial-element rest2)))
394             exact)))
395
396 ;;; If Type isn't a values type, then make it into one:
397 ;;;    <type>  ==>  (values type &rest t)
398 (defun coerce-to-values (type)
399   (declare (type ctype type))
400   (if (values-type-p type)
401       type
402       (make-values-type :required (list type) :rest *universal-type*)))
403
404 ;;; Do the specified OPERATION on TYPE1 and TYPE2, which may be any
405 ;;; type, including VALUES types. With VALUES types such as:
406 ;;;    (VALUES a0 a1)
407 ;;;    (VALUES b0 b1)
408 ;;; we compute the more useful result
409 ;;;    (VALUES (<operation> a0 b0) (<operation> a1 b1))
410 ;;; rather than the precise result
411 ;;;    (<operation> (values a0 a1) (values b0 b1))
412 ;;; This has the virtue of always keeping the VALUES type specifier
413 ;;; outermost, and retains all of the information that is really
414 ;;; useful for static type analysis. We want to know what is always
415 ;;; true of each value independently. It is worthless to know that if
416 ;;; the first value is B0 then the second will be B1.
417 ;;;
418 ;;; If the VALUES count signatures differ, then we produce a result with
419 ;;; the required VALUE count chosen by NREQ when applied to the number
420 ;;; of required values in TYPE1 and TYPE2. Any &KEY values become
421 ;;; &REST T (anyone who uses keyword values deserves to lose.)
422 ;;;
423 ;;; The second value is true if the result is definitely empty or if
424 ;;; OPERATION returned true as its second value each time we called
425 ;;; it. Since we approximate the intersection of VALUES types, the
426 ;;; second value being true doesn't mean the result is exact.
427 (defun args-type-op (type1 type2 operation nreq default-type)
428   (declare (type ctype type1 type2 default-type)
429            (type function operation nreq))
430   (if (or (values-type-p type1) (values-type-p type2))
431       (let ((type1 (coerce-to-values type1))
432             (type2 (coerce-to-values type2)))
433         (multiple-value-bind (types1 rest1)
434             (values-type-types type1 default-type)
435           (multiple-value-bind (types2 rest2)
436               (values-type-types type2 default-type)
437             (multiple-value-bind (rest rest-exact)
438                 (funcall operation rest1 rest2)
439               (multiple-value-bind (res res-exact)
440                   (if (< (length types1) (length types2))
441                       (fixed-values-op types2 types1 rest1 operation)
442                       (fixed-values-op types1 types2 rest2 operation))
443                 (let* ((req (funcall nreq
444                                      (length (args-type-required type1))
445                                      (length (args-type-required type2))))
446                        (required (subseq res 0 req))
447                        (opt (subseq res req))
448                        (opt-last (position rest opt :test-not #'type=
449                                            :from-end t)))
450                   (if (find *empty-type* required :test #'type=)
451                       (values *empty-type* t)
452                       (values (make-values-type
453                                :required required
454                                :optional (if opt-last
455                                              (subseq opt 0 (1+ opt-last))
456                                              ())
457                                :rest (if (eq rest default-type) nil rest))
458                               (and rest-exact res-exact)))))))))
459       (funcall operation type1 type2)))
460
461 ;;; Do a union or intersection operation on types that might be values
462 ;;; types. The result is optimized for utility rather than exactness,
463 ;;; but it is guaranteed that it will be no smaller (more restrictive)
464 ;;; than the precise result.
465 ;;;
466 ;;; The return convention seems to be analogous to
467 ;;; TYPES-EQUAL-OR-INTERSECT. -- WHN 19990910.
468 (defun-cached (values-type-union :hash-function type-cache-hash
469                                  :hash-bits 8
470                                  :default nil
471                                  :init-wrapper !cold-init-forms)
472               ((type1 eq) (type2 eq))
473   (declare (type ctype type1 type2))
474   (cond ((or (eq type1 *wild-type*) (eq type2 *wild-type*)) *wild-type*)
475         ((eq type1 *empty-type*) type2)
476         ((eq type2 *empty-type*) type1)
477         (t
478          (values (args-type-op type1 type2 #'type-union #'min *empty-type*)))))
479 (defun-cached (values-type-intersection :hash-function type-cache-hash
480                                         :hash-bits 8
481                                         :values 2
482                                         :default (values nil :empty)
483                                         :init-wrapper !cold-init-forms)
484               ((type1 eq) (type2 eq))
485   (declare (type ctype type1 type2))
486   (cond ((eq type1 *wild-type*) (values type2 t))
487         ((eq type2 *wild-type*) (values type1 t))
488         (t
489          (args-type-op type1 type2
490                        #'type-intersection
491                        #'max
492                        (specifier-type 'null)))))
493
494 ;;; This is like TYPES-EQUAL-OR-INTERSECT, except that it sort of
495 ;;; works on VALUES types. Note that due to the semantics of
496 ;;; VALUES-TYPE-INTERSECTION, this might return (VALUES T T) when
497 ;;; there isn't really any intersection.
498 (defun values-types-equal-or-intersect (type1 type2)
499   (cond ((or (eq type1 *empty-type*) (eq type2 *empty-type*))
500          (values t t))
501         ((or (values-type-p type1) (values-type-p type2))
502          (multiple-value-bind (res win) (values-type-intersection type1 type2)
503            (values (not (eq res *empty-type*))
504                    win)))
505         (t
506          (types-equal-or-intersect type1 type2))))
507
508 ;;; a SUBTYPEP-like operation that can be used on any types, including
509 ;;; VALUES types
510 (defun-cached (values-subtypep :hash-function type-cache-hash
511                                :hash-bits 8
512                                :values 2
513                                :default (values nil :empty)
514                                :init-wrapper !cold-init-forms)
515               ((type1 eq) (type2 eq))
516   (declare (type ctype type1 type2))
517   (cond ((eq type2 *wild-type*) (values t t))
518         ((eq type1 *wild-type*)
519          (values (eq type2 *universal-type*) t))
520         ((not (values-types-equal-or-intersect type1 type2))
521          (values nil t))
522         (t
523          (if (or (values-type-p type1) (values-type-p type2))
524              (let ((type1 (coerce-to-values type1))
525                    (type2 (coerce-to-values type2)))
526                (multiple-value-bind (types1 rest1) (values-type-types type1)
527                  (multiple-value-bind (types2 rest2) (values-type-types type2)
528                    (cond ((< (length (values-type-required type1))
529                              (length (values-type-required type2)))
530                           (values nil t))
531                          ((< (length types1) (length types2))
532                           (values nil nil))
533                          ((or (values-type-keyp type1)
534                               (values-type-keyp type2))
535                           (values nil nil))
536                          (t
537                           (do ((t1 types1 (rest t1))
538                                (t2 types2 (rest t2)))
539                               ((null t2)
540                                (csubtypep rest1 rest2))
541                             (multiple-value-bind (res win-p)
542                                 (csubtypep (first t1) (first t2))
543                               (unless win-p
544                                 (return (values nil nil)))
545                               (unless res
546                                 (return (values nil t))))))))))
547              (csubtypep type1 type2)))))
548 \f
549 ;;;; type method interfaces
550
551 ;;; like SUBTYPEP, only works on CTYPE structures
552 (defun-cached (csubtypep :hash-function type-cache-hash
553                          :hash-bits 8
554                          :values 2
555                          :default (values nil :empty)
556                          :init-wrapper !cold-init-forms)
557               ((type1 eq) (type2 eq))
558   (declare (type ctype type1 type2))
559   (cond ((or (eq type1 type2)
560              (eq type1 *empty-type*)
561              (eq type2 *wild-type*))
562          (values t t))
563         ((or (eq type1 *wild-type*)
564              (eq type2 *empty-type*))
565          (values nil t))
566         (t
567          (!invoke-type-method :simple-subtypep :complex-subtypep-arg2
568                               type1 type2
569                               :complex-arg1 :complex-subtypep-arg1))))
570
571 ;;; Just parse the type specifiers and call CSUBTYPE.
572 (defun sb!xc:subtypep (type1 type2)
573   #!+sb-doc
574   "Return two values indicating the relationship between type1 and type2.
575   If values are T and T, type1 definitely is a subtype of type2.
576   If values are NIL and T, type1 definitely is not a subtype of type2.
577   If values are NIL and NIL, it couldn't be determined."
578   (csubtypep (specifier-type type1) (specifier-type type2)))
579
580 ;;; If two types are definitely equivalent, return true. The second
581 ;;; value indicates whether the first value is definitely correct.
582 ;;; This should only fail in the presence of HAIRY types.
583 (defun-cached (type= :hash-function type-cache-hash
584                      :hash-bits 8
585                      :values 2
586                      :default (values nil :empty)
587                      :init-wrapper !cold-init-forms)
588               ((type1 eq) (type2 eq))
589   (declare (type ctype type1 type2))
590   (if (eq type1 type2)
591       (values t t)
592       (!invoke-type-method :simple-= :complex-= type1 type2)))
593
594 ;;; Not exactly the negation of TYPE=, since when the relationship is
595 ;;; uncertain, we still return NIL, NIL. This is useful in cases where
596 ;;; the conservative assumption is =.
597 (defun type/= (type1 type2)
598   (declare (type ctype type1 type2))
599   (multiple-value-bind (res win) (type= type1 type2)
600     (if win
601         (values (not res) t)
602         (values nil nil))))
603
604 ;;; the type method dispatch case of TYPE-UNION2
605 (defun %type-union2 (type1 type2)
606   ;; As in %TYPE-INTERSECTION2, it seems to be a good idea to give
607   ;; both argument orders a chance at COMPLEX-INTERSECTION2. Unlike
608   ;; %TYPE-INTERSECTION2, though, I don't have a specific case which
609   ;; demonstrates this is actually necessary. Also unlike
610   ;; %TYPE-INTERSECTION2, there seems to be no need to distinguish
611   ;; between not finding a method and having a method return NIL.
612   (flet ((1way (x y)
613            (!invoke-type-method :simple-union2 :complex-union2
614                                 x y
615                                 :default nil)))
616     (declare (inline 1way))
617     (or (1way type1 type2)
618         (1way type2 type1))))
619
620 ;;; Find a type which includes both types. Any inexactness is
621 ;;; represented by the fuzzy element types; we return a single value
622 ;;; that is precise to the best of our knowledge. This result is
623 ;;; simplified into the canonical form, thus is not a UNION-TYPE
624 ;;; unless we find no other way to represent the result.
625 (defun-cached (type-union2 :hash-function type-cache-hash
626                            :hash-bits 8
627                            :init-wrapper !cold-init-forms)
628               ((type1 eq) (type2 eq))
629   ;; KLUDGE: This was generated from TYPE-INTERSECTION2 by Ye Olde Cut And
630   ;; Paste technique of programming. If it stays around (as opposed to
631   ;; e.g. fading away in favor of some CLOS solution) the shared logic
632   ;; should probably become shared code. -- WHN 2001-03-16
633   (declare (type ctype type1 type2))
634   (cond ((eq type1 type2)
635          type1)
636         ((or (union-type-p type1)
637              (union-type-p type2))
638          ;; Unions of UNION-TYPE should have the UNION-TYPE-TYPES
639          ;; values broken out and united separately. The full TYPE-UNION
640          ;; function knows how to do this, so let it handle it.
641          (type-union type1 type2))
642         (t
643          ;; the ordinary case: we dispatch to type methods
644          (%type-union2 type1 type2))))
645
646 ;;; the type method dispatch case of TYPE-INTERSECTION2
647 (defun %type-intersection2 (type1 type2)
648   ;; We want to give both argument orders a chance at
649   ;; COMPLEX-INTERSECTION2. Without that, the old CMU CL type
650   ;; methods could give noncommutative results, e.g.
651   ;;   (TYPE-INTERSECTION2 *EMPTY-TYPE* SOME-HAIRY-TYPE)
652   ;;     => NIL, NIL
653   ;;   (TYPE-INTERSECTION2 SOME-HAIRY-TYPE *EMPTY-TYPE*)
654   ;;     => #<NAMED-TYPE NIL>, T
655   ;; We also need to distinguish between the case where we found a
656   ;; type method, and it returned NIL, and the case where we fell
657   ;; through without finding any type method. An example of the first
658   ;; case is the intersection of a HAIRY-TYPE with some ordinary type.
659   ;; An example of the second case is the intersection of two
660   ;; completely-unrelated types, e.g. CONS and NUMBER, or SYMBOL and
661   ;; ARRAY.
662   ;;
663   ;; (Why yes, CLOS probably *would* be nicer..)
664   (flet ((1way (x y)
665            (!invoke-type-method :simple-intersection2 :complex-intersection2
666                                 x y
667                                 :default :no-type-method-found)))
668     (declare (inline 1way))
669     (let ((xy (1way type1 type2)))
670       (or (and (not (eql xy :no-type-method-found)) xy)
671           (let ((yx (1way type2 type1)))
672             (or (and (not (eql yx :no-type-method-found)) yx)
673                 (cond ((and (eql xy :no-type-method-found)
674                             (eql yx :no-type-method-found))
675                        *empty-type*)
676                       (t
677                        (aver (and (not xy) (not yx))) ; else handled above
678                        nil))))))))
679
680 (defun-cached (type-intersection2 :hash-function type-cache-hash
681                                   :hash-bits 8
682                                   :values 1
683                                   :default nil
684                                   :init-wrapper !cold-init-forms)
685               ((type1 eq) (type2 eq))
686   (declare (type ctype type1 type2))
687   (cond ((eq type1 type2)
688          type1)
689         ((or (intersection-type-p type1)
690              (intersection-type-p type2))
691          ;; Intersections of INTERSECTION-TYPE should have the
692          ;; INTERSECTION-TYPE-TYPES values broken out and intersected
693          ;; separately. The full TYPE-INTERSECTION function knows how
694          ;; to do that, so let it handle it.
695          (type-intersection type1 type2))
696         (t
697          ;; the ordinary case: we dispatch to type methods
698          (%type-intersection2 type1 type2))))
699
700 ;;; Return as restrictive and simple a type as we can discover that is
701 ;;; no more restrictive than the intersection of TYPE1 and TYPE2. At
702 ;;; worst, we arbitrarily return one of the arguments as the first
703 ;;; value (trying not to return a hairy type).
704 (defun type-approx-intersection2 (type1 type2)
705   (cond ((type-intersection2 type1 type2))
706         ((hairy-type-p type1) type2)
707         (t type1)))
708
709 ;;; a test useful for checking whether a derived type matches a
710 ;;; declared type
711 ;;;
712 ;;; The first value is true unless the types don't intersect and
713 ;;; aren't equal. The second value is true if the first value is
714 ;;; definitely correct. NIL is considered to intersect with any type.
715 ;;; If T is a subtype of either type, then we also return T, T. This
716 ;;; way we recognize that hairy types might intersect with T.
717 (defun types-equal-or-intersect (type1 type2)
718   (declare (type ctype type1 type2))
719   (if (or (eq type1 *empty-type*) (eq type2 *empty-type*))
720       (values t t)
721       (let ((intersection2 (type-intersection2 type1 type2)))
722         (cond ((not intersection2)
723                (if (or (csubtypep *universal-type* type1)
724                        (csubtypep *universal-type* type2))
725                    (values t t)
726                    (values t nil)))
727               ((eq intersection2 *empty-type*) (values nil t))
728               (t (values t t))))))
729
730 ;;; Return a Common Lisp type specifier corresponding to the TYPE
731 ;;; object.
732 (defun type-specifier (type)
733   (declare (type ctype type))
734   (funcall (type-class-unparse (type-class-info type)) type))
735
736 ;;; (VALUES-SPECIFIER-TYPE and SPECIFIER-TYPE moved from here to
737 ;;; early-type.lisp by WHN ca. 19990201.)
738
739 ;;; Take a list of type specifiers, computing the translation of each
740 ;;; specifier and defining it as a builtin type.
741 (declaim (ftype (function (list) (values)) precompute-types))
742 (defun precompute-types (specs)
743   (dolist (spec specs)
744     (let ((res (specifier-type spec)))
745       (unless (unknown-type-p res)
746         (setf (info :type :builtin spec) res)
747         (setf (info :type :kind spec) :primitive))))
748   (values))
749 \f
750 ;;;; general TYPE-UNION and TYPE-INTERSECTION operations
751 ;;;;
752 ;;;; These are fully general operations on CTYPEs: they'll always
753 ;;;; return a CTYPE representing the result.
754
755 ;;; shared logic for unions and intersections: Stuff TYPE into the
756 ;;; vector TYPES, finding pairs of types which can be simplified by
757 ;;; SIMPLIFY2 (TYPE-UNION2 or TYPE-INTERSECTION2) and replacing them
758 ;;; by their simplified forms.
759 (defun accumulate1-compound-type (type types %compound-type-p simplify2)
760   (declare (type ctype type))
761   (declare (type (vector ctype) types))
762   (declare (type function simplify2))
763   ;; Any input object satisfying %COMPOUND-TYPE-P should've been
764   ;; broken into components before it reached us.
765   (aver (not (funcall %compound-type-p type)))
766   (dotimes (i (length types) (vector-push-extend type types))
767     (let ((simplified2 (funcall simplify2 type (aref types i))))
768       (when simplified2
769         ;; Discard the old (AREF TYPES I).
770         (setf (aref types i) (vector-pop types))
771         ;; Merge the new SIMPLIFIED2 into TYPES, by tail recursing.
772         ;; (Note that the tail recursion is indirect: we go through
773         ;; ACCUMULATE, not ACCUMULATE1, so that if SIMPLIFIED2 is
774         ;; handled properly if it satisfies %COMPOUND-TYPE-P.)
775         (return (accumulate-compound-type simplified2
776                                           types
777                                           %compound-type-p
778                                           simplify2)))))
779   ;; Voila.
780   (values))
781
782 ;;; shared logic for unions and intersections: Use
783 ;;; ACCUMULATE1-COMPOUND-TYPE to merge TYPE into TYPES, either
784 ;;; all in one step or, if %COMPOUND-TYPE-P is satisfied,
785 ;;; component by component.
786 (defun accumulate-compound-type (type types %compound-type-p simplify2)
787   (declare (type function %compound-type-p simplify2))
788   (flet ((accumulate1 (x)
789            (accumulate1-compound-type x types %compound-type-p simplify2)))
790     (declare (inline accumulate1))
791     (if (funcall %compound-type-p type)
792         (map nil #'accumulate1 (compound-type-types type))
793         (accumulate1 type)))
794   (values))
795
796 ;;; shared logic for unions and intersections: Return a vector of
797 ;;; types representing the same types as INPUT-TYPES, but with 
798 ;;; COMPOUND-TYPEs satisfying %COMPOUND-TYPE-P broken up into their
799 ;;; component types, and with any SIMPLY2 simplifications applied.
800 (defun simplified-compound-types (input-types %compound-type-p simplify2)
801   (let ((simplified-types (make-array (length input-types)
802                                       :fill-pointer 0
803                                       :adjustable t
804                                       :element-type 'ctype
805                                       ;; (This INITIAL-ELEMENT shouldn't
806                                       ;; matter, but helps avoid type
807                                       ;; warnings at compile time.)
808                                       :initial-element *empty-type*)))
809     (dolist (input-type input-types)
810       (accumulate-compound-type input-type
811                                 simplified-types
812                                 %compound-type-p
813                                 simplify2))
814     simplified-types))
815
816 ;;; shared logic for unions and intersections: Make a COMPOUND-TYPE
817 ;;; object whose components are the types in TYPES, or skip to special
818 ;;; cases when TYPES is short.
819 (defun make-compound-type-or-something (constructor types enumerable identity)
820   (declare (type function constructor))
821   (declare (type (vector ctype) types))
822   (declare (type ctype identity))
823   (case (length types)
824     (0 identity)
825     (1 (aref types 0))
826     (t (funcall constructor
827                 enumerable
828                 ;; FIXME: This should be just (COERCE TYPES 'LIST), but as
829                 ;; of sbcl-0.6.11.17 the COERCE optimizer is really
830                 ;; brain-dead, so that would generate a full call to
831                 ;; SPECIFIER-TYPE at runtime, so we get into bootstrap
832                 ;; problems in cold init because 'LIST is a compound
833                 ;; type, so we need to MAKE-COMPOUND-TYPE-OR-SOMETHING
834                 ;; before we know what 'LIST is. Once the COERCE
835                 ;; optimizer is less brain-dead, we can make this
836                 ;; (COERCE TYPES 'LIST) again.
837                 #+sb-xc-host (coerce types 'list)
838                 #-sb-xc-host (coerce-to-list types)))))
839
840 (defun type-intersection (&rest input-types)
841   (let ((simplified-types (simplified-compound-types input-types
842                                                      #'intersection-type-p
843                                                      #'type-intersection2)))
844     (declare (type (vector ctype) simplified-types))
845     ;; We want to have a canonical representation of types (or failing
846     ;; that, punt to HAIRY-TYPE). Canonical representation would have
847     ;; intersections inside unions but not vice versa, since you can
848     ;; always achieve that by the distributive rule. But we don't want
849     ;; to just apply the distributive rule, since it would be too easy
850     ;; to end up with unreasonably huge type expressions. So instead
851     ;; we punt to HAIRY-TYPE when this comes up.
852     (if (and (> (length simplified-types) 1)
853              (some #'union-type-p simplified-types))
854         (make-hairy-type
855          :specifier `(and ,@(map 'list #'type-specifier simplified-types)))
856         (make-compound-type-or-something #'%make-intersection-type
857                                          simplified-types
858                                          (some #'type-enumerable
859                                                simplified-types)
860                                          *universal-type*))))
861
862 (defun type-union (&rest input-types)
863   (let ((simplified-types (simplified-compound-types input-types
864                                                      #'union-type-p
865                                                      #'type-union2)))
866     (make-compound-type-or-something #'%make-union-type
867                                      simplified-types
868                                      (every #'type-enumerable simplified-types)
869                                      *empty-type*)))
870 \f
871 ;;;; built-in types
872
873 (!define-type-class named)
874
875 (defvar *wild-type*)
876 (defvar *empty-type*)
877 (defvar *universal-type*)
878 (defvar *universal-fun-type*)
879 (!cold-init-forms
880  (macrolet ((frob (name var)
881               `(progn
882                  (setq ,var (make-named-type :name ',name))
883                  (setf (info :type :kind ',name) :primitive)
884                  (setf (info :type :builtin ',name) ,var))))
885    ;; KLUDGE: In ANSI, * isn't really the name of a type, it's just a
886    ;; special symbol which can be stuck in some places where an
887    ;; ordinary type can go, e.g. (ARRAY * 1) instead of (ARRAY T 1).
888    ;; At some point, in order to become more standard, we should
889    ;; convert all the classic CMU CL legacy *s and *WILD-TYPE*s into
890    ;; Ts and *UNIVERSAL-TYPE*s.
891    (frob * *wild-type*)
892    (frob nil *empty-type*)
893    (frob t *universal-type*))
894  (setf *universal-fun-type*
895        (make-fun-type :wild-args t
896                            :returns *wild-type*)))
897
898 (!define-type-method (named :simple-=) (type1 type2)
899   ;; FIXME: BUG 85: This assertion failed when I added it in
900   ;; sbcl-0.6.11.13. It probably shouldn't fail; but for now it's
901   ;; just commented out.
902   ;;(aver (not (eq type1 *wild-type*))) ; * isn't really a type.
903   (values (eq type1 type2) t))
904
905 (!define-type-method (named :simple-subtypep) (type1 type2)
906   (aver (not (eq type1 *wild-type*))) ; * isn't really a type.
907   (values (or (eq type1 *empty-type*) (eq type2 *wild-type*)) t))
908
909 (!define-type-method (named :complex-subtypep-arg1) (type1 type2)
910   (aver (not (eq type1 *wild-type*))) ; * isn't really a type.
911   ;; FIXME: Why does this (old CMU CL) assertion hold? Perhaps 'cause
912   ;; the HAIRY-TYPE COMPLEX-SUBTYPEP-ARG2 method takes precedence over
913   ;; this COMPLEX-SUBTYPE-ARG1 method? (I miss CLOS..)
914   (aver (not (hairy-type-p type2))) 
915   ;; Besides the old CMU CL assertion above, we also need to avoid
916   ;; compound types, else we could get into trouble with
917   ;;   (SUBTYPEP T '(OR (SATISFIES FOO) (SATISFIES BAR)))
918   ;; or
919   ;;   (SUBTYPEP T '(AND (SATISFIES FOO) (SATISFIES BAR))).
920   (aver (not (compound-type-p type2))) 
921   ;; Then, since TYPE2 is reasonably tractable, we're good to go.
922   (values (eq type1 *empty-type*) t))
923
924 (!define-type-method (named :complex-subtypep-arg2) (type1 type2)
925   (aver (not (eq type2 *wild-type*))) ; * isn't really a type.
926   (cond ((eq type2 *universal-type*)
927          (values t t))
928         ((hairy-type-p type1)
929          (values nil nil))
930         (t
931          ;; FIXME: This seems to rely on there only being 2 or 3
932          ;; HAIRY-TYPE values, and the exclusion of various
933          ;; possibilities above. It would be good to explain it and/or
934          ;; rewrite it so that it's clearer.
935          (values (not (eq type2 *empty-type*)) t))))
936
937 (!define-type-method (named :complex-intersection2) (type1 type2)
938   ;; FIXME: This assertion failed when I added it in sbcl-0.6.11.13.
939   ;; Perhaps when bug 85 is fixed it can be reenabled.
940   ;;(aver (not (eq type2 *wild-type*))) ; * isn't really a type.
941   (hierarchical-intersection2 type1 type2))
942
943 (!define-type-method (named :complex-union2) (type1 type2)
944   ;; Perhaps when bug 85 is fixed this can be reenabled.
945   ;;(aver (not (eq type2 *wild-type*))) ; * isn't really a type.
946   (hierarchical-union2 type1 type2))
947
948 (!define-type-method (named :unparse) (x)
949   (named-type-name x))
950 \f
951 ;;;; hairy and unknown types
952
953 (!define-type-method (hairy :unparse) (x) (hairy-type-specifier x))
954
955 (!define-type-method (hairy :simple-subtypep) (type1 type2)
956   (let ((hairy-spec1 (hairy-type-specifier type1))
957         (hairy-spec2 (hairy-type-specifier type2)))
958     (cond ((and (consp hairy-spec1) (eq (car hairy-spec1) 'not)
959                 (consp hairy-spec2) (eq (car hairy-spec2) 'not))
960            (csubtypep (specifier-type (cadr hairy-spec2))
961                       (specifier-type (cadr hairy-spec1))))
962           ((equal hairy-spec1 hairy-spec2)
963            (values t t))
964           (t
965            (values nil nil)))))
966
967 (!define-type-method (hairy :complex-subtypep-arg2) (type1 type2)
968   (let ((hairy-spec (hairy-type-specifier type2)))
969     (cond ((and (consp hairy-spec) (eq (car hairy-spec) 'not))
970            (let* ((complement-type2 (specifier-type (cadr hairy-spec)))
971                   (intersection2 (type-intersection2 type1
972                                                      complement-type2)))
973              (if intersection2
974                  (values (eq intersection2 *empty-type*) t)
975                  (values nil nil))))
976           (t
977            (values nil nil)))))
978
979 (!define-type-method (hairy :complex-subtypep-arg1) (type1 type2)
980   (let ((hairy-spec (hairy-type-specifier type1)))
981      (cond ((and (consp hairy-spec) (eq (car hairy-spec) 'not))
982             ;; You may not believe this. I couldn't either. But then I
983             ;; sat down and drew lots of Venn diagrams. Comments
984             ;; involving a and b refer to the call (subtypep '(not a)
985             ;; 'b) -- CSR, 2002-02-27.
986             (block nil
987               ;; (Several logical truths in this block are true as
988               ;; long as b/=T. As of sbcl-0.7.1.28, it seems
989               ;; impossible to construct a case with b=T where we
990               ;; actually reach this type method, but we'll test for
991               ;; and exclude this case anyway, since future
992               ;; maintenance might make it possible for it to end up
993               ;; in this code.)
994               (multiple-value-bind (equal certain)
995                   (type= type2 (specifier-type t))
996                 (unless certain
997                   (return (values nil nil)))
998                 (when equal
999                   (return (values t t))))
1000               (let ((complement-type1 (specifier-type (cadr hairy-spec))))
1001                 ;; Do the special cases first, in order to give us a
1002                 ;; chance if subtype/supertype relationships are hairy.
1003                 (multiple-value-bind (equal certain) 
1004                     (type= complement-type1 type2)
1005                   ;; If a = b, ~a is not a subtype of b (unless b=T,
1006                   ;; which was excluded above).
1007                   (unless certain
1008                     (return (values nil nil)))
1009                   (when equal
1010                     (return (values nil t))))
1011                 ;; This (TYPE= TYPE1 TYPE2) branch would never be
1012                 ;; taken, as type1 and type2 will only be equal if
1013                 ;; they're both NOT types, and then the
1014                 ;; :SIMPLE-SUBTYPEP method would be used instead.
1015                 ;; ((type= type1 type2) (values t t))
1016                 (multiple-value-bind (equal certain)
1017                     (csubtypep complement-type1 type2)
1018                   ;; If a is a subtype of b, ~a is not a subtype of b
1019                   ;; (unless b=T, which was excluded above).
1020                   (unless certain
1021                     (return (values nil nil)))
1022                   (when equal
1023                     (return (values nil t))))
1024                 (multiple-value-bind (equal certain)
1025                     (csubtypep type2 complement-type1)
1026                   ;; If b is a subtype of a, ~a is not a subtype of b.
1027                   ;; (FIXME: That's not true if a=T. Do we know at
1028                   ;; this point that a is not T?)
1029                   (unless certain
1030                     (return (values nil nil)))
1031                   (when equal
1032                     (return (values nil t))))
1033                 ;; Other cases here would rely on being able to catch
1034                 ;; all possible cases, which the fragility of this
1035                 ;; type system doesn't inspire me; for instance, if a
1036                 ;; is type= to ~b, then we want T, T; if this is not
1037                 ;; the case and the types are disjoint (have an
1038                 ;; intersection of *empty-type*) then we want NIL, T;
1039                 ;; else if the union of a and b is the
1040                 ;; *universal-type* then we want T, T. So currently we
1041                 ;; still claim to be unsure about e.g. (subtypep '(not
1042                 ;; fixnum) 'single-float).
1043                 )))
1044            (t
1045             (values nil nil)))))
1046
1047 (!define-type-method (hairy :complex-=) (type1 type2)
1048   (declare (ignore type1 type2))
1049   (values nil nil))
1050
1051 (!define-type-method (hairy :simple-intersection2 :complex-intersection2)
1052                      (type1 type2)
1053   (declare (ignore type1 type2))
1054   nil)
1055
1056 (!define-type-method (hairy :simple-=) (type1 type2)
1057   (if (equal (hairy-type-specifier type1)
1058              (hairy-type-specifier type2))
1059       (values t t)
1060       (values nil nil)))
1061
1062 (!def-type-translator not (&whole whole type)
1063   (declare (ignore type))
1064   ;; Check legality of arguments.
1065   (destructuring-bind (not typespec) whole
1066     (declare (ignore not))
1067     (let ((spec (type-specifier (specifier-type typespec)))) ; must be legal typespec
1068       (if (and (listp spec) (eq (car spec) 'not))
1069           ;; canonicalize (not (not foo))
1070           (specifier-type (cadr spec))
1071           (make-hairy-type :specifier whole)))))
1072
1073 (!def-type-translator satisfies (&whole whole fun)
1074   (declare (ignore fun))
1075   ;; Check legality of arguments.
1076   (destructuring-bind (satisfies predicate-name) whole
1077     (declare (ignore satisfies))
1078     (unless (symbolp predicate-name)
1079       (error 'simple-type-error
1080              :datum predicate-name
1081              :expected-type 'symbol
1082              :format-control "~S is not a symbol."
1083              :format-arguments (list predicate-name))))
1084   ;; Create object.
1085   (make-hairy-type :specifier whole))
1086 \f
1087 ;;;; numeric types
1088
1089 (!define-type-class number)
1090
1091 (!define-type-method (number :simple-=) (type1 type2)
1092   (values
1093    (and (eq (numeric-type-class type1) (numeric-type-class type2))
1094         (eq (numeric-type-format type1) (numeric-type-format type2))
1095         (eq (numeric-type-complexp type1) (numeric-type-complexp type2))
1096         (equal (numeric-type-low type1) (numeric-type-low type2))
1097         (equal (numeric-type-high type1) (numeric-type-high type2)))
1098    t))
1099
1100 (!define-type-method (number :unparse) (type)
1101   (let* ((complexp (numeric-type-complexp type))
1102          (low (numeric-type-low type))
1103          (high (numeric-type-high type))
1104          (base (case (numeric-type-class type)
1105                  (integer 'integer)
1106                  (rational 'rational)
1107                  (float (or (numeric-type-format type) 'float))
1108                  (t 'real))))
1109     (let ((base+bounds
1110            (cond ((and (eq base 'integer) high low)
1111                   (let ((high-count (logcount high))
1112                         (high-length (integer-length high)))
1113                     (cond ((= low 0)
1114                            (cond ((= high 0) '(integer 0 0))
1115                                  ((= high 1) 'bit)
1116                                  ((and (= high-count high-length)
1117                                        (plusp high-length))
1118                                   `(unsigned-byte ,high-length))
1119                                  (t
1120                                   `(mod ,(1+ high)))))
1121                           ((and (= low sb!xc:most-negative-fixnum)
1122                                 (= high sb!xc:most-positive-fixnum))
1123                            'fixnum)
1124                           ((and (= low (lognot high))
1125                                 (= high-count high-length)
1126                                 (> high-count 0))
1127                            `(signed-byte ,(1+ high-length)))
1128                           (t
1129                            `(integer ,low ,high)))))
1130                  (high `(,base ,(or low '*) ,high))
1131                  (low
1132                   (if (and (eq base 'integer) (= low 0))
1133                       'unsigned-byte
1134                       `(,base ,low)))
1135                  (t base))))
1136       (ecase complexp
1137         (:real
1138          base+bounds)
1139         (:complex
1140          (if (eq base+bounds 'real)
1141              'complex
1142              `(complex ,base+bounds)))
1143         ((nil)
1144          (aver (eq base+bounds 'real))
1145          'number)))))
1146
1147 ;;; Return true if X is "less than or equal" to Y, taking open bounds
1148 ;;; into consideration. CLOSED is the predicate used to test the bound
1149 ;;; on a closed interval (e.g. <=), and OPEN is the predicate used on
1150 ;;; open bounds (e.g. <). Y is considered to be the outside bound, in
1151 ;;; the sense that if it is infinite (NIL), then the test succeeds,
1152 ;;; whereas if X is infinite, then the test fails (unless Y is also
1153 ;;; infinite).
1154 ;;;
1155 ;;; This is for comparing bounds of the same kind, e.g. upper and
1156 ;;; upper. Use NUMERIC-BOUND-TEST* for different kinds of bounds.
1157 #!-negative-zero-is-not-zero
1158 (defmacro numeric-bound-test (x y closed open)
1159   `(cond ((not ,y) t)
1160          ((not ,x) nil)
1161          ((consp ,x)
1162           (if (consp ,y)
1163               (,closed (car ,x) (car ,y))
1164               (,closed (car ,x) ,y)))
1165          (t
1166           (if (consp ,y)
1167               (,open ,x (car ,y))
1168               (,closed ,x ,y)))))
1169
1170 #!+negative-zero-is-not-zero
1171 (defmacro numeric-bound-test-zero (op x y)
1172   `(if (and (zerop ,x) (zerop ,y) (floatp ,x) (floatp ,y))
1173        (,op (float-sign ,x) (float-sign ,y))
1174        (,op ,x ,y)))
1175
1176 #!+negative-zero-is-not-zero
1177 (defmacro numeric-bound-test (x y closed open)
1178   `(cond ((not ,y) t)
1179          ((not ,x) nil)
1180          ((consp ,x)
1181           (if (consp ,y)
1182               (numeric-bound-test-zero ,closed (car ,x) (car ,y))
1183               (numeric-bound-test-zero ,closed (car ,x) ,y)))
1184          (t
1185           (if (consp ,y)
1186               (numeric-bound-test-zero ,open ,x (car ,y))
1187               (numeric-bound-test-zero ,closed ,x ,y)))))
1188
1189 ;;; This is used to compare upper and lower bounds. This is different
1190 ;;; from the same-bound case:
1191 ;;; -- Since X = NIL is -infinity, whereas y = NIL is +infinity, we
1192 ;;;    return true if *either* arg is NIL.
1193 ;;; -- an open inner bound is "greater" and also squeezes the interval,
1194 ;;;    causing us to use the OPEN test for those cases as well.
1195 #!-negative-zero-is-not-zero
1196 (defmacro numeric-bound-test* (x y closed open)
1197   `(cond ((not ,y) t)
1198          ((not ,x) t)
1199          ((consp ,x)
1200           (if (consp ,y)
1201               (,open (car ,x) (car ,y))
1202               (,open (car ,x) ,y)))
1203          (t
1204           (if (consp ,y)
1205               (,open ,x (car ,y))
1206               (,closed ,x ,y)))))
1207
1208 #!+negative-zero-is-not-zero
1209 (defmacro numeric-bound-test* (x y closed open)
1210   `(cond ((not ,y) t)
1211          ((not ,x) t)
1212          ((consp ,x)
1213           (if (consp ,y)
1214               (numeric-bound-test-zero ,open (car ,x) (car ,y))
1215               (numeric-bound-test-zero ,open (car ,x) ,y)))
1216          (t
1217           (if (consp ,y)
1218               (numeric-bound-test-zero ,open ,x (car ,y))
1219               (numeric-bound-test-zero ,closed ,x ,y)))))
1220
1221 ;;; Return whichever of the numeric bounds X and Y is "maximal"
1222 ;;; according to the predicates CLOSED (e.g. >=) and OPEN (e.g. >).
1223 ;;; This is only meaningful for maximizing like bounds, i.e. upper and
1224 ;;; upper. If MAX-P is true, then we return NIL if X or Y is NIL,
1225 ;;; otherwise we return the other arg.
1226 (defmacro numeric-bound-max (x y closed open max-p)
1227   (once-only ((n-x x)
1228               (n-y y))
1229     `(cond ((not ,n-x) ,(if max-p nil n-y))
1230            ((not ,n-y) ,(if max-p nil n-x))
1231            ((consp ,n-x)
1232             (if (consp ,n-y)
1233                 (if (,closed (car ,n-x) (car ,n-y)) ,n-x ,n-y)
1234                 (if (,open (car ,n-x) ,n-y) ,n-x ,n-y)))
1235            (t
1236             (if (consp ,n-y)
1237                 (if (,open (car ,n-y) ,n-x) ,n-y ,n-x)
1238                 (if (,closed ,n-y ,n-x) ,n-y ,n-x))))))
1239
1240 (!define-type-method (number :simple-subtypep) (type1 type2)
1241   (let ((class1 (numeric-type-class type1))
1242         (class2 (numeric-type-class type2))
1243         (complexp2 (numeric-type-complexp type2))
1244         (format2 (numeric-type-format type2))
1245         (low1 (numeric-type-low type1))
1246         (high1 (numeric-type-high type1))
1247         (low2 (numeric-type-low type2))
1248         (high2 (numeric-type-high type2)))
1249     ;; If one is complex and the other isn't, they are disjoint.
1250     (cond ((not (or (eq (numeric-type-complexp type1) complexp2)
1251                     (null complexp2)))
1252            (values nil t))
1253           ;; If the classes are specified and different, the types are
1254           ;; disjoint unless type2 is rational and type1 is integer.
1255           ((not (or (eq class1 class2)
1256                     (null class2)
1257                     (and (eq class1 'integer)
1258                          (eq class2 'rational))))
1259            (values nil t))
1260           ;; If the float formats are specified and different, the types
1261           ;; are disjoint.
1262           ((not (or (eq (numeric-type-format type1) format2)
1263                     (null format2)))
1264            (values nil t))
1265           ;; Check the bounds.
1266           ((and (numeric-bound-test low1 low2 >= >)
1267                 (numeric-bound-test high1 high2 <= <))
1268            (values t t))
1269           (t
1270            (values nil t)))))
1271
1272 (!define-superclasses number ((generic-number)) !cold-init-forms)
1273
1274 ;;; If the high bound of LOW is adjacent to the low bound of HIGH,
1275 ;;; then return true, otherwise NIL.
1276 (defun numeric-types-adjacent (low high)
1277   (let ((low-bound (numeric-type-high low))
1278         (high-bound (numeric-type-low high)))
1279     (cond ((not (and low-bound high-bound)) nil)
1280           ((and (consp low-bound) (consp high-bound)) nil)
1281           ((consp low-bound)
1282            #!-negative-zero-is-not-zero
1283            (let ((low-value (car low-bound)))
1284              (or (eql low-value high-bound)
1285                  (and (eql low-value -0f0) (eql high-bound 0f0))
1286                  (and (eql low-value 0f0) (eql high-bound -0f0))
1287                  (and (eql low-value -0d0) (eql high-bound 0d0))
1288                  (and (eql low-value 0d0) (eql high-bound -0d0))))
1289            #!+negative-zero-is-not-zero
1290            (eql (car low-bound) high-bound))
1291           ((consp high-bound)
1292            #!-negative-zero-is-not-zero
1293            (let ((high-value (car high-bound)))
1294              (or (eql high-value low-bound)
1295                  (and (eql high-value -0f0) (eql low-bound 0f0))
1296                  (and (eql high-value 0f0) (eql low-bound -0f0))
1297                  (and (eql high-value -0d0) (eql low-bound 0d0))
1298                  (and (eql high-value 0d0) (eql low-bound -0d0))))
1299            #!+negative-zero-is-not-zero
1300            (eql (car high-bound) low-bound))
1301           #!+negative-zero-is-not-zero
1302           ((or (and (eql low-bound -0f0) (eql high-bound 0f0))
1303                (and (eql low-bound -0d0) (eql high-bound 0d0))))
1304           ((and (eq (numeric-type-class low) 'integer)
1305                 (eq (numeric-type-class high) 'integer))
1306            (eql (1+ low-bound) high-bound))
1307           (t
1308            nil))))
1309
1310 ;;; Return a numeric type that is a supertype for both TYPE1 and TYPE2.
1311 ;;;
1312 ;;; ### Note: we give up early to keep from dropping lots of information on
1313 ;;; the floor by returning overly general types.
1314 (!define-type-method (number :simple-union2) (type1 type2)
1315   (declare (type numeric-type type1 type2))
1316   (cond ((csubtypep type1 type2) type2)
1317         ((csubtypep type2 type1) type1)
1318         (t
1319          (let ((class1 (numeric-type-class type1))
1320                (format1 (numeric-type-format type1))
1321                (complexp1 (numeric-type-complexp type1))
1322                (class2 (numeric-type-class type2))
1323                (format2 (numeric-type-format type2))
1324                (complexp2 (numeric-type-complexp type2)))
1325            (when (and (eq class1 class2)
1326                       (eq format1 format2)
1327                       (eq complexp1 complexp2)
1328                       (or (numeric-types-intersect type1 type2)
1329                           (numeric-types-adjacent type1 type2)
1330                           (numeric-types-adjacent type2 type1)))
1331              (make-numeric-type
1332               :class class1
1333               :format format1
1334               :complexp complexp1
1335               :low (numeric-bound-max (numeric-type-low type1)
1336                                       (numeric-type-low type2)
1337                                       <= < t)
1338               :high (numeric-bound-max (numeric-type-high type1)
1339                                        (numeric-type-high type2)
1340                                        >= > t)))))))
1341
1342 (!cold-init-forms
1343   (setf (info :type :kind 'number) :primitive)
1344   (setf (info :type :builtin 'number)
1345         (make-numeric-type :complexp nil)))
1346
1347 (!def-type-translator complex (&optional (typespec '*))
1348   (if (eq typespec '*)
1349       (make-numeric-type :complexp :complex)
1350       (labels ((not-numeric ()
1351                  (error "The component type for COMPLEX is not numeric: ~S"
1352                         typespec))
1353                (not-real ()
1354                  (error "The component type for COMPLEX is not real: ~S"
1355                         typespec))
1356                (complex1 (component-type)
1357                  (unless (numeric-type-p component-type)
1358                    (not-numeric))
1359                  (when (eq (numeric-type-complexp component-type) :complex)
1360                    (not-real))
1361                  (modified-numeric-type component-type :complexp :complex))
1362                (complex-union (component)
1363                  (unless (numberp component)
1364                    (not-numeric))
1365                  ;; KLUDGE: This TYPECASE more or less does
1366                  ;; (UPGRADED-COMPLEX-PART-TYPE (TYPE-OF COMPONENT)),
1367                  ;; (plus a small hack to treat (EQL COMPONENT 0) specially)
1368                  ;; but uses logic cut and pasted from the DEFUN of
1369                  ;; UPGRADED-COMPLEX-PART-TYPE. That's fragile, because
1370                  ;; changing the definition of UPGRADED-COMPLEX-PART-TYPE
1371                  ;; would tend to break the code here. Unfortunately,
1372                  ;; though, reusing UPGRADED-COMPLEX-PART-TYPE here
1373                  ;; would cause another kind of fragility, because
1374                  ;; ANSI's definition of TYPE-OF is so weak that e.g.
1375                  ;; (UPGRADED-COMPLEX-PART-TYPE (TYPE-OF 1/2)) could
1376                  ;; end up being (UPGRADED-COMPLEX-PART-TYPE 'REAL)
1377                  ;; instead of (UPGRADED-COMPLEX-PART-TYPE 'RATIONAL).
1378                  ;; So using TYPE-OF would mean that ANSI-conforming
1379                  ;; maintenance changes in TYPE-OF could break the code here.
1380                  ;; It's not clear how best to fix this. -- WHN 2002-01-21,
1381                  ;; trying to summarize CSR's concerns in his patch
1382                  (typecase component
1383                    (complex (error "The component type for COMPLEX (EQL X) ~
1384                                     is complex: ~S"
1385                                    component))
1386                    ((eql 0) (specifier-type nil)) ; as required by ANSI
1387                    (single-float (specifier-type '(complex single-float)))
1388                    (double-float (specifier-type '(complex double-float)))
1389                    #!+long-float
1390                    (long-float (specifier-type '(complex long-float)))
1391                    (rational (specifier-type '(complex rational)))
1392                    (t (specifier-type '(complex real))))))
1393         (let ((ctype (specifier-type typespec)))
1394           (typecase ctype
1395             (numeric-type (complex1 ctype))
1396             (union-type (apply #'type-union
1397                                ;; FIXME: This code could suffer from
1398                                ;; (admittedly very obscure) cases of
1399                                ;; bug 145 e.g. when TYPE is
1400                                ;;   (OR (AND INTEGER (SATISFIES ODDP))
1401                                ;;       (AND FLOAT (SATISFIES FOO))
1402                                ;; and not even report the problem very well.
1403                                (mapcar #'complex1
1404                                        (union-type-types ctype))))
1405             ;; MEMBER-TYPE is almost the same as UNION-TYPE, but
1406             ;; there's a gotcha: (COMPLEX (EQL 0)) is, according to
1407             ;; ANSI, equal to type NIL, the empty set.
1408             (member-type (apply #'type-union
1409                                 (mapcar #'complex-union
1410                                         (member-type-members ctype))))
1411             (t
1412              (multiple-value-bind (subtypep certainly)
1413                  (csubtypep ctype (specifier-type 'real))
1414                (if (and (not subtypep) certainly)
1415                    (not-real)
1416                    ;; ANSI just says that TYPESPEC is any subtype of
1417                    ;; type REAL, not necessarily a NUMERIC-TYPE. In
1418                    ;; particular, at this point TYPESPEC could legally be
1419                    ;; an intersection type like (AND REAL (SATISFIES ODDP)),
1420                    ;; in which case we fall through the logic above and
1421                    ;; end up here, stumped.
1422                    (bug "~@<(known bug #145): The type ~S is too hairy to be 
1423                          used for a COMPLEX component.~:@>"
1424                         typespec)))))))))
1425
1426 ;;; If X is *, return NIL, otherwise return the bound, which must be a
1427 ;;; member of TYPE or a one-element list of a member of TYPE.
1428 #!-sb-fluid (declaim (inline canonicalized-bound))
1429 (defun canonicalized-bound (bound type)
1430   (cond ((eq bound '*) nil)
1431         ((or (sb!xc:typep bound type)
1432              (and (consp bound)
1433                   (sb!xc:typep (car bound) type)
1434                   (null (cdr bound))))
1435           bound)
1436         (t
1437          (error "Bound is not ~S, a ~S or a list of a ~S: ~S"
1438                 '*
1439                 type
1440                 type
1441                 bound))))
1442
1443 (!def-type-translator integer (&optional (low '*) (high '*))
1444   (let* ((l (canonicalized-bound low 'integer))
1445          (lb (if (consp l) (1+ (car l)) l))
1446          (h (canonicalized-bound high 'integer))
1447          (hb (if (consp h) (1- (car h)) h)))
1448     (when (and hb lb (< hb lb))
1449       (error "Lower bound ~S is greater than upper bound ~S." l h))
1450     (make-numeric-type :class 'integer
1451                        :complexp :real
1452                        :enumerable (not (null (and l h)))
1453                        :low lb
1454                        :high hb)))
1455
1456 (defmacro !def-bounded-type (type class format)
1457   `(!def-type-translator ,type (&optional (low '*) (high '*))
1458      (let ((lb (canonicalized-bound low ',type))
1459            (hb (canonicalized-bound high ',type)))
1460        (unless (numeric-bound-test* lb hb <= <)
1461          (error "Lower bound ~S is not less than upper bound ~S." low high))
1462        (make-numeric-type :class ',class :format ',format :low lb :high hb))))
1463
1464 (!def-bounded-type rational rational nil)
1465
1466 ;;; Unlike CMU CL, we represent the types FLOAT and REAL as
1467 ;;; UNION-TYPEs of more primitive types, in order to make
1468 ;;; type representation more unique, avoiding problems in the
1469 ;;; simplification of things like
1470 ;;;   (subtypep '(or (single-float -1.0 1.0) (single-float 0.1))
1471 ;;;             '(or (real -1 7) (single-float 0.1) (single-float -1.0 1.0)))
1472 ;;; When we allowed REAL to remain as a separate NUMERIC-TYPE,
1473 ;;; it was too easy for the first argument to be simplified to
1474 ;;; '(SINGLE-FLOAT -1.0), and for the second argument to be simplified
1475 ;;; to '(OR (REAL -1 7) (SINGLE-FLOAT 0.1)) and then for the
1476 ;;; SUBTYPEP to fail (returning NIL,T instead of T,T) because
1477 ;;; the first argument can't be seen to be a subtype of any of the
1478 ;;; terms in the second argument.
1479 ;;;
1480 ;;; The old CMU CL way was:
1481 ;;;   (!def-bounded-type float float nil)
1482 ;;;   (!def-bounded-type real nil nil)
1483 ;;;
1484 ;;; FIXME: If this new way works for a while with no weird new
1485 ;;; problems, we can go back and rip out support for separate FLOAT
1486 ;;; and REAL flavors of NUMERIC-TYPE. The new way was added in
1487 ;;; sbcl-0.6.11.22, 2001-03-21.
1488 ;;;
1489 ;;; FIXME: It's probably necessary to do something to fix the
1490 ;;; analogous problem with INTEGER and RATIONAL types. Perhaps
1491 ;;; bounded RATIONAL types should be represented as (OR RATIO INTEGER).
1492 (defun coerce-bound (bound type inner-coerce-bound-fun)
1493   (declare (type function inner-coerce-bound-fun))
1494   (cond ((eql bound '*)
1495          bound)
1496         ((consp bound)
1497          (destructuring-bind (inner-bound) bound
1498            (list (funcall inner-coerce-bound-fun inner-bound type))))
1499         (t
1500          (funcall inner-coerce-bound-fun bound type))))
1501 (defun inner-coerce-real-bound (bound type)
1502   (ecase type
1503     (rational (rationalize bound))
1504     (float (if (floatp bound)
1505                bound
1506                ;; Coerce to the widest float format available, to
1507                ;; avoid unnecessary loss of precision:
1508                (coerce bound 'long-float)))))
1509 (defun coerced-real-bound (bound type)
1510   (coerce-bound bound type #'inner-coerce-real-bound))
1511 (defun coerced-float-bound (bound type)
1512   (coerce-bound bound type #'coerce))
1513 (!def-type-translator real (&optional (low '*) (high '*))
1514   (specifier-type `(or (float ,(coerced-real-bound  low 'float)
1515                               ,(coerced-real-bound high 'float))
1516                        (rational ,(coerced-real-bound  low 'rational)
1517                                  ,(coerced-real-bound high 'rational)))))
1518 (!def-type-translator float (&optional (low '*) (high '*))
1519   (specifier-type 
1520    `(or (single-float ,(coerced-float-bound  low 'single-float)
1521                       ,(coerced-float-bound high 'single-float))
1522         (double-float ,(coerced-float-bound  low 'double-float)
1523                       ,(coerced-float-bound high 'double-float))
1524         #!+long-float ,(error "stub: no long float support yet"))))
1525
1526 (defmacro !define-float-format (f)
1527   `(!def-bounded-type ,f float ,f))
1528
1529 (!define-float-format short-float)
1530 (!define-float-format single-float)
1531 (!define-float-format double-float)
1532 (!define-float-format long-float)
1533
1534 (defun numeric-types-intersect (type1 type2)
1535   (declare (type numeric-type type1 type2))
1536   (let* ((class1 (numeric-type-class type1))
1537          (class2 (numeric-type-class type2))
1538          (complexp1 (numeric-type-complexp type1))
1539          (complexp2 (numeric-type-complexp type2))
1540          (format1 (numeric-type-format type1))
1541          (format2 (numeric-type-format type2))
1542          (low1 (numeric-type-low type1))
1543          (high1 (numeric-type-high type1))
1544          (low2 (numeric-type-low type2))
1545          (high2 (numeric-type-high type2)))
1546     ;; If one is complex and the other isn't, then they are disjoint.
1547     (cond ((not (or (eq complexp1 complexp2)
1548                     (null complexp1) (null complexp2)))
1549            nil)
1550           ;; If either type is a float, then the other must either be
1551           ;; specified to be a float or unspecified. Otherwise, they
1552           ;; are disjoint.
1553           ((and (eq class1 'float)
1554                 (not (member class2 '(float nil)))) nil)
1555           ((and (eq class2 'float)
1556                 (not (member class1 '(float nil)))) nil)
1557           ;; If the float formats are specified and different, the
1558           ;; types are disjoint.
1559           ((not (or (eq format1 format2) (null format1) (null format2)))
1560            nil)
1561           (t
1562            ;; Check the bounds. This is a bit odd because we must
1563            ;; always have the outer bound of the interval as the
1564            ;; second arg.
1565            (if (numeric-bound-test high1 high2 <= <)
1566                (or (and (numeric-bound-test low1 low2 >= >)
1567                         (numeric-bound-test* low1 high2 <= <))
1568                    (and (numeric-bound-test low2 low1 >= >)
1569                         (numeric-bound-test* low2 high1 <= <)))
1570                (or (and (numeric-bound-test* low2 high1 <= <)
1571                         (numeric-bound-test low2 low1 >= >))
1572                    (and (numeric-bound-test high2 high1 <= <)
1573                         (numeric-bound-test* high2 low1 >= >))))))))
1574
1575 ;;; Take the numeric bound X and convert it into something that can be
1576 ;;; used as a bound in a numeric type with the specified CLASS and
1577 ;;; FORMAT. If UP-P is true, then we round up as needed, otherwise we
1578 ;;; round down. UP-P true implies that X is a lower bound, i.e. (N) > N.
1579 ;;;
1580 ;;; This is used by NUMERIC-TYPE-INTERSECTION to mash the bound into
1581 ;;; the appropriate type number. X may only be a float when CLASS is
1582 ;;; FLOAT.
1583 ;;;
1584 ;;; ### Note: it is possible for the coercion to a float to overflow
1585 ;;; or underflow. This happens when the bound doesn't fit in the
1586 ;;; specified format. In this case, we should really return the
1587 ;;; appropriate {Most | Least}-{Positive | Negative}-XXX-Float float
1588 ;;; of desired format. But these conditions aren't currently signalled
1589 ;;; in any useful way.
1590 ;;;
1591 ;;; Also, when converting an open rational bound into a float we
1592 ;;; should probably convert it to a closed bound of the closest float
1593 ;;; in the specified format. KLUDGE: In general, open float bounds are
1594 ;;; screwed up. -- (comment from original CMU CL)
1595 (defun round-numeric-bound (x class format up-p)
1596   (if x
1597       (let ((cx (if (consp x) (car x) x)))
1598         (ecase class
1599           ((nil rational) x)
1600           (integer
1601            (if (and (consp x) (integerp cx))
1602                (if up-p (1+ cx) (1- cx))
1603                (if up-p (ceiling cx) (floor cx))))
1604           (float
1605            (let ((res (if format (coerce cx format) (float cx))))
1606              (if (consp x) (list res) res)))))
1607       nil))
1608
1609 ;;; Handle the case of type intersection on two numeric types. We use
1610 ;;; TYPES-EQUAL-OR-INTERSECT to throw out the case of types with no
1611 ;;; intersection. If an attribute in TYPE1 is unspecified, then we use
1612 ;;; TYPE2's attribute, which must be at least as restrictive. If the
1613 ;;; types intersect, then the only attributes that can be specified
1614 ;;; and different are the class and the bounds.
1615 ;;;
1616 ;;; When the class differs, we use the more restrictive class. The
1617 ;;; only interesting case is RATIONAL/INTEGER, since RATIONAL includes
1618 ;;; INTEGER.
1619 ;;;
1620 ;;; We make the result lower (upper) bound the maximum (minimum) of
1621 ;;; the argument lower (upper) bounds. We convert the bounds into the
1622 ;;; appropriate numeric type before maximizing. This avoids possible
1623 ;;; confusion due to mixed-type comparisons (but I think the result is
1624 ;;; the same).
1625 (!define-type-method (number :simple-intersection2) (type1 type2)
1626   (declare (type numeric-type type1 type2))
1627   (if (numeric-types-intersect type1 type2)
1628       (let* ((class1 (numeric-type-class type1))
1629              (class2 (numeric-type-class type2))
1630              (class (ecase class1
1631                       ((nil) class2)
1632                       ((integer float) class1)
1633                       (rational (if (eq class2 'integer)
1634                                        'integer
1635                                        'rational))))
1636              (format (or (numeric-type-format type1)
1637                          (numeric-type-format type2))))
1638         (make-numeric-type
1639          :class class
1640          :format format
1641          :complexp (or (numeric-type-complexp type1)
1642                        (numeric-type-complexp type2))
1643          :low (numeric-bound-max
1644                (round-numeric-bound (numeric-type-low type1)
1645                                     class format t)
1646                (round-numeric-bound (numeric-type-low type2)
1647                                     class format t)
1648                > >= nil)
1649          :high (numeric-bound-max
1650                 (round-numeric-bound (numeric-type-high type1)
1651                                      class format nil)
1652                 (round-numeric-bound (numeric-type-high type2)
1653                                      class format nil)
1654                 < <= nil)))
1655       *empty-type*))
1656
1657 ;;; Given two float formats, return the one with more precision. If
1658 ;;; either one is null, return NIL.
1659 (defun float-format-max (f1 f2)
1660   (when (and f1 f2)
1661     (dolist (f *float-formats* (error "bad float format: ~S" f1))
1662       (when (or (eq f f1) (eq f f2))
1663         (return f)))))
1664
1665 ;;; Return the result of an operation on TYPE1 and TYPE2 according to
1666 ;;; the rules of numeric contagion. This is always NUMBER, some float
1667 ;;; format (possibly complex) or RATIONAL. Due to rational
1668 ;;; canonicalization, there isn't much we can do here with integers or
1669 ;;; rational complex numbers.
1670 ;;;
1671 ;;; If either argument is not a NUMERIC-TYPE, then return NUMBER. This
1672 ;;; is useful mainly for allowing types that are technically numbers,
1673 ;;; but not a NUMERIC-TYPE.
1674 (defun numeric-contagion (type1 type2)
1675   (if (and (numeric-type-p type1) (numeric-type-p type2))
1676       (let ((class1 (numeric-type-class type1))
1677             (class2 (numeric-type-class type2))
1678             (format1 (numeric-type-format type1))
1679             (format2 (numeric-type-format type2))
1680             (complexp1 (numeric-type-complexp type1))
1681             (complexp2 (numeric-type-complexp type2)))
1682         (cond ((or (null complexp1)
1683                    (null complexp2))
1684                (specifier-type 'number))
1685               ((eq class1 'float)
1686                (make-numeric-type
1687                 :class 'float
1688                 :format (ecase class2
1689                           (float (float-format-max format1 format2))
1690                           ((integer rational) format1)
1691                           ((nil)
1692                            ;; A double-float with any real number is a
1693                            ;; double-float.
1694                            #!-long-float
1695                            (if (eq format1 'double-float)
1696                              'double-float
1697                              nil)
1698                            ;; A long-float with any real number is a
1699                            ;; long-float.
1700                            #!+long-float
1701                            (if (eq format1 'long-float)
1702                              'long-float
1703                              nil)))
1704                 :complexp (if (or (eq complexp1 :complex)
1705                                   (eq complexp2 :complex))
1706                               :complex
1707                               :real)))
1708               ((eq class2 'float) (numeric-contagion type2 type1))
1709               ((and (eq complexp1 :real) (eq complexp2 :real))
1710                (make-numeric-type
1711                 :class (and class1 class2 'rational)
1712                 :complexp :real))
1713               (t
1714                (specifier-type 'number))))
1715       (specifier-type 'number)))
1716 \f
1717 ;;;; array types
1718
1719 (!define-type-class array)
1720
1721 ;;; What this does depends on the setting of the
1722 ;;; *USE-IMPLEMENTATION-TYPES* switch. If true, return the specialized
1723 ;;; element type, otherwise return the original element type.
1724 (defun specialized-element-type-maybe (type)
1725   (declare (type array-type type))
1726   (if *use-implementation-types*
1727       (array-type-specialized-element-type type)
1728       (array-type-element-type type)))
1729
1730 (!define-type-method (array :simple-=) (type1 type2)
1731   (values (and (equal (array-type-dimensions type1)
1732                       (array-type-dimensions type2))
1733                (eq (array-type-complexp type1)
1734                    (array-type-complexp type2))
1735                (type= (specialized-element-type-maybe type1)
1736                       (specialized-element-type-maybe type2)))
1737           t))
1738
1739 (!define-type-method (array :unparse) (type)
1740   (let ((dims (array-type-dimensions type))
1741         (eltype (type-specifier (array-type-element-type type)))
1742         (complexp (array-type-complexp type)))
1743     (cond ((eq dims '*)
1744            (if (eq eltype '*)
1745                (if complexp 'array 'simple-array)
1746                (if complexp `(array ,eltype) `(simple-array ,eltype))))
1747           ((= (length dims) 1)
1748            (if complexp
1749                (if (eq (car dims) '*)
1750                    (case eltype
1751                      (bit 'bit-vector)
1752                      (base-char 'base-string)
1753                      (character 'string)
1754                      (* 'vector)
1755                      (t `(vector ,eltype)))
1756                    (case eltype
1757                      (bit `(bit-vector ,(car dims)))
1758                      (base-char `(base-string ,(car dims)))
1759                      (character `(string ,(car dims)))
1760                      (t `(vector ,eltype ,(car dims)))))
1761                (if (eq (car dims) '*)
1762                    (case eltype
1763                      (bit 'simple-bit-vector)
1764                      (base-char 'simple-base-string)
1765                      (character 'simple-string)
1766                      ((t) 'simple-vector)
1767                      (t `(simple-array ,eltype (*))))
1768                    (case eltype
1769                      (bit `(simple-bit-vector ,(car dims)))
1770                      (base-char `(simple-base-string ,(car dims)))
1771                      (character `(simple-string ,(car dims)))
1772                      ((t) `(simple-vector ,(car dims)))
1773                      (t `(simple-array ,eltype ,dims))))))
1774           (t
1775            (if complexp
1776                `(array ,eltype ,dims)
1777                `(simple-array ,eltype ,dims))))))
1778
1779 (!define-type-method (array :simple-subtypep) (type1 type2)
1780   (let ((dims1 (array-type-dimensions type1))
1781         (dims2 (array-type-dimensions type2))
1782         (complexp2 (array-type-complexp type2)))
1783     (cond (;; not subtypep unless dimensions are compatible
1784            (not (or (eq dims2 '*)
1785                     (and (not (eq dims1 '*))
1786                          ;; (sbcl-0.6.4 has trouble figuring out that
1787                          ;; DIMS1 and DIMS2 must be lists at this
1788                          ;; point, and knowing that is important to
1789                          ;; compiling EVERY efficiently.)
1790                          (= (length (the list dims1))
1791                             (length (the list dims2)))
1792                          (every (lambda (x y)
1793                                   (or (eq y '*) (eql x y)))
1794                                 (the list dims1)
1795                                 (the list dims2)))))
1796            (values nil t))
1797           ;; not subtypep unless complexness is compatible
1798           ((not (or (eq complexp2 :maybe)
1799                     (eq (array-type-complexp type1) complexp2)))
1800            (values nil t))
1801           ;; Since we didn't fail any of the tests above, we win
1802           ;; if the TYPE2 element type is wild.
1803           ((eq (array-type-element-type type2) *wild-type*)
1804            (values t t))
1805           (;; Since we didn't match any of the special cases above, we
1806            ;; can't give a good answer unless both the element types
1807            ;; have been defined.
1808            (or (unknown-type-p (array-type-element-type type1))
1809                (unknown-type-p (array-type-element-type type2)))
1810            (values nil nil))
1811           (;; Otherwise, the subtype relationship holds iff the
1812            ;; types are equal, and they're equal iff the specialized
1813            ;; element types are identical.
1814            t
1815            (values (type= (specialized-element-type-maybe type1)
1816                           (specialized-element-type-maybe type2))
1817                    t)))))
1818
1819 (!define-superclasses array
1820   ((string string)
1821    (vector vector)
1822    (array))
1823   !cold-init-forms)
1824
1825 (defun array-types-intersect (type1 type2)
1826   (declare (type array-type type1 type2))
1827   (let ((dims1 (array-type-dimensions type1))
1828         (dims2 (array-type-dimensions type2))
1829         (complexp1 (array-type-complexp type1))
1830         (complexp2 (array-type-complexp type2)))
1831     ;; See whether dimensions are compatible.
1832     (cond ((not (or (eq dims1 '*) (eq dims2 '*)
1833                     (and (= (length dims1) (length dims2))
1834                          (every (lambda (x y)
1835                                   (or (eq x '*) (eq y '*) (= x y)))
1836                                 dims1 dims2))))
1837            (values nil t))
1838           ;; See whether complexpness is compatible.
1839           ((not (or (eq complexp1 :maybe)
1840                     (eq complexp2 :maybe)
1841                     (eq complexp1 complexp2)))
1842            (values nil t))
1843           ;; If either element type is wild, then they intersect.
1844           ;; Otherwise, the types must be identical.
1845           ((or (eq (array-type-element-type type1) *wild-type*)
1846                (eq (array-type-element-type type2) *wild-type*)
1847                (type= (specialized-element-type-maybe type1)
1848                       (specialized-element-type-maybe type2)))
1849
1850            (values t t))
1851           (t
1852            (values nil t)))))
1853
1854 (!define-type-method (array :simple-intersection2) (type1 type2)
1855   (declare (type array-type type1 type2))
1856   (if (array-types-intersect type1 type2)
1857       (let ((dims1 (array-type-dimensions type1))
1858             (dims2 (array-type-dimensions type2))
1859             (complexp1 (array-type-complexp type1))
1860             (complexp2 (array-type-complexp type2))
1861             (eltype1 (array-type-element-type type1))
1862             (eltype2 (array-type-element-type type2)))
1863         (specialize-array-type
1864          (make-array-type
1865           :dimensions (cond ((eq dims1 '*) dims2)
1866                             ((eq dims2 '*) dims1)
1867                             (t
1868                              (mapcar (lambda (x y) (if (eq x '*) y x))
1869                                      dims1 dims2)))
1870           :complexp (if (eq complexp1 :maybe) complexp2 complexp1)
1871           :element-type (if (eq eltype1 *wild-type*) eltype2 eltype1))))
1872       *empty-type*))
1873
1874 ;;; Check a supplied dimension list to determine whether it is legal,
1875 ;;; and return it in canonical form (as either '* or a list).
1876 (defun canonical-array-dimensions (dims)
1877   (typecase dims
1878     ((member *) dims)
1879     (integer
1880      (when (minusp dims)
1881        (error "Arrays can't have a negative number of dimensions: ~S" dims))
1882      (when (>= dims sb!xc:array-rank-limit)
1883        (error "array type with too many dimensions: ~S" dims))
1884      (make-list dims :initial-element '*))
1885     (list
1886      (when (>= (length dims) sb!xc:array-rank-limit)
1887        (error "array type with too many dimensions: ~S" dims))
1888      (dolist (dim dims)
1889        (unless (eq dim '*)
1890          (unless (and (integerp dim)
1891                       (>= dim 0)
1892                       (< dim sb!xc:array-dimension-limit))
1893            (error "bad dimension in array type: ~S" dim))))
1894      dims)
1895     (t
1896      (error "Array dimensions is not a list, integer or *:~%  ~S" dims))))
1897 \f
1898 ;;;; MEMBER types
1899
1900 (!define-type-class member)
1901
1902 (!define-type-method (member :unparse) (type)
1903   (let ((members (member-type-members type)))
1904     (if (equal members '(nil))
1905         'null
1906         `(member ,@members))))
1907
1908 (!define-type-method (member :simple-subtypep) (type1 type2)
1909   (values (subsetp (member-type-members type1) (member-type-members type2))
1910           t))
1911
1912 (!define-type-method (member :complex-subtypep-arg1) (type1 type2)
1913   (every/type (swapped-args-fun #'ctypep)
1914               type2
1915               (member-type-members type1)))
1916
1917 ;;; We punt if the odd type is enumerable and intersects with the
1918 ;;; MEMBER type. If not enumerable, then it is definitely not a
1919 ;;; subtype of the MEMBER type.
1920 (!define-type-method (member :complex-subtypep-arg2) (type1 type2)
1921   (cond ((not (type-enumerable type1)) (values nil t))
1922         ((types-equal-or-intersect type1 type2) (values nil nil))
1923         (t (values nil t))))
1924
1925 (!define-type-method (member :simple-intersection2) (type1 type2)
1926   (let ((mem1 (member-type-members type1))
1927         (mem2 (member-type-members type2)))
1928     (cond ((subsetp mem1 mem2) type1)
1929           ((subsetp mem2 mem1) type2)
1930           (t
1931            (let ((res (intersection mem1 mem2)))
1932              (if res
1933                  (make-member-type :members res)
1934                  *empty-type*))))))
1935
1936 (!define-type-method (member :complex-intersection2) (type1 type2)
1937   (block punt                
1938     (collect ((members))
1939       (let ((mem2 (member-type-members type2)))
1940         (dolist (member mem2)
1941           (multiple-value-bind (val win) (ctypep member type1)
1942             (unless win
1943               (return-from punt nil))
1944             (when val (members member))))
1945         (cond ((subsetp mem2 (members)) type2)
1946               ((null (members)) *empty-type*)
1947               (t
1948                (make-member-type :members (members))))))))
1949
1950 ;;; We don't need a :COMPLEX-UNION2, since the only interesting case is
1951 ;;; a union type, and the member/union interaction is handled by the
1952 ;;; union type method.
1953 (!define-type-method (member :simple-union2) (type1 type2)
1954   (let ((mem1 (member-type-members type1))
1955         (mem2 (member-type-members type2)))
1956     (cond ((subsetp mem1 mem2) type2)
1957           ((subsetp mem2 mem1) type1)
1958           (t
1959            (make-member-type :members (union mem1 mem2))))))
1960
1961 (!define-type-method (member :simple-=) (type1 type2)
1962   (let ((mem1 (member-type-members type1))
1963         (mem2 (member-type-members type2)))
1964     (values (and (subsetp mem1 mem2)
1965                  (subsetp mem2 mem1))
1966             t)))
1967
1968 (!define-type-method (member :complex-=) (type1 type2)
1969   (if (type-enumerable type1)
1970       (multiple-value-bind (val win) (csubtypep type2 type1)
1971         (if (or val (not win))
1972             (values nil nil)
1973             (values nil t)))
1974       (values nil t)))
1975
1976 (!def-type-translator member (&rest members)
1977   (if members
1978     (make-member-type :members (remove-duplicates members))
1979     *empty-type*))
1980 \f
1981 ;;;; intersection types
1982 ;;;;
1983 ;;;; Until version 0.6.10.6, SBCL followed the original CMU CL approach
1984 ;;;; of punting on all AND types, not just the unreasonably complicated
1985 ;;;; ones. The change was motivated by trying to get the KEYWORD type
1986 ;;;; to behave sensibly:
1987 ;;;;    ;; reasonable definition
1988 ;;;;    (DEFTYPE KEYWORD () '(AND SYMBOL (SATISFIES KEYWORDP)))
1989 ;;;;    ;; reasonable behavior
1990 ;;;;    (AVER (SUBTYPEP 'KEYWORD 'SYMBOL))
1991 ;;;; Without understanding a little about the semantics of AND, we'd
1992 ;;;; get (SUBTYPEP 'KEYWORD 'SYMBOL)=>NIL,NIL and, for entirely
1993 ;;;; parallel reasons, (SUBTYPEP 'RATIO 'NUMBER)=>NIL,NIL. That's
1994 ;;;; not so good..)
1995 ;;;;
1996 ;;;; We still follow the example of CMU CL to some extent, by punting
1997 ;;;; (to the opaque HAIRY-TYPE) on sufficiently complicated types
1998 ;;;; involving AND.
1999
2000 (!define-type-class intersection)
2001
2002 ;;; A few intersection types have special names. The others just get
2003 ;;; mechanically unparsed.
2004 (!define-type-method (intersection :unparse) (type)
2005   (declare (type ctype type))
2006   (or (find type '(ratio bignum keyword) :key #'specifier-type :test #'type=)
2007       `(and ,@(mapcar #'type-specifier (intersection-type-types type)))))
2008
2009 ;;; shared machinery for type equality: true if every type in the set
2010 ;;; TYPES1 matches a type in the set TYPES2 and vice versa
2011 (defun type=-set (types1 types2)
2012   (flet (;; true if every type in the set X matches a type in the set Y
2013          (type<=-set (x y)
2014            (declare (type list x y))
2015            (every (lambda (xelement)
2016                     (position xelement y :test #'type=))
2017                   x)))
2018     (values (and (type<=-set types1 types2)
2019                  (type<=-set types2 types1))
2020             t)))
2021
2022 ;;; Two intersection types are equal if their subtypes are equal sets.
2023 ;;;
2024 ;;; FIXME: Might it be better to use
2025 ;;;   (AND (SUBTYPEP X Y) (SUBTYPEP Y X))
2026 ;;; instead, since SUBTYPEP is the usual relationship that we care
2027 ;;; most about, so it would be good to leverage any ingenuity there
2028 ;;; in this more obscure method?
2029 (!define-type-method (intersection :simple-=) (type1 type2)
2030   (type=-set (intersection-type-types type1)
2031              (intersection-type-types type2)))
2032
2033 (defun %intersection-complex-subtypep-arg1 (type1 type2)
2034   (any/type (swapped-args-fun #'csubtypep)
2035             type2
2036             (intersection-type-types type1)))
2037
2038 (!define-type-method (intersection :simple-subtypep) (type1 type2)
2039   (every/type #'%intersection-complex-subtypep-arg1
2040               type1
2041               (intersection-type-types type2)))
2042
2043 (!define-type-method (intersection :complex-subtypep-arg1) (type1 type2)
2044   (%intersection-complex-subtypep-arg1 type1 type2))
2045
2046 (!define-type-method (intersection :complex-subtypep-arg2) (type1 type2)
2047   (every/type #'csubtypep type1 (intersection-type-types type2)))
2048
2049 (!def-type-translator and (&whole whole &rest type-specifiers)
2050   (apply #'type-intersection
2051          (mapcar #'specifier-type
2052                  type-specifiers)))
2053 \f
2054 ;;;; union types
2055
2056 (!define-type-class union)
2057
2058 ;;; The LIST type has a special name. Other union types just get
2059 ;;; mechanically unparsed.
2060 (!define-type-method (union :unparse) (type)
2061   (declare (type ctype type))
2062   (if (type= type (specifier-type 'list))
2063       'list
2064       `(or ,@(mapcar #'type-specifier (union-type-types type)))))
2065
2066 ;;; Two union types are equal if their subtypes are equal sets.
2067 (!define-type-method (union :simple-=) (type1 type2)
2068   (type=-set (union-type-types type1)
2069              (union-type-types type2)))
2070
2071 ;;; Similarly, a union type is a subtype of another if every element
2072 ;;; of TYPE1 is a subtype of some element of TYPE2.
2073 (!define-type-method (union :simple-subtypep) (type1 type2)
2074   (every/type (swapped-args-fun #'union-complex-subtypep-arg2)
2075               type2
2076               (union-type-types type1)))
2077
2078 (defun union-complex-subtypep-arg1 (type1 type2)
2079   (every/type (swapped-args-fun #'csubtypep)
2080               type2
2081               (union-type-types type1)))
2082 (!define-type-method (union :complex-subtypep-arg1) (type1 type2)
2083   (union-complex-subtypep-arg1 type1 type2))
2084
2085 (defun union-complex-subtypep-arg2 (type1 type2)
2086   (any/type #'csubtypep type1 (union-type-types type2)))
2087 (!define-type-method (union :complex-subtypep-arg2) (type1 type2)
2088   (union-complex-subtypep-arg2 type1 type2))
2089
2090 (!define-type-method (union :simple-intersection2 :complex-intersection2)
2091                      (type1 type2)
2092   ;; The CSUBTYPEP clauses here let us simplify e.g.
2093   ;;   (TYPE-INTERSECTION2 (SPECIFIER-TYPE 'LIST)
2094   ;;                       (SPECIFIER-TYPE '(OR LIST VECTOR)))
2095   ;; (where LIST is (OR CONS NULL)).
2096   ;;
2097   ;; The tests are more or less (CSUBTYPEP TYPE1 TYPE2) and vice
2098   ;; versa, but it's important that we pre-expand them into
2099   ;; specialized operations on individual elements of
2100   ;; UNION-TYPE-TYPES, instead of using the ordinary call to
2101   ;; CSUBTYPEP, in order to avoid possibly invoking any methods which
2102   ;; might in turn invoke (TYPE-INTERSECTION2 TYPE1 TYPE2) and thus
2103   ;; cause infinite recursion.
2104   (cond ((union-complex-subtypep-arg2 type1 type2)
2105          type1)
2106         ((union-complex-subtypep-arg1 type2 type1)
2107          type2)
2108         (t 
2109          ;; KLUDGE: This code accumulates a sequence of TYPE-UNION2
2110          ;; operations in a particular order, and gives up if any of
2111          ;; the sub-unions turn out not to be simple. In other cases
2112          ;; ca. sbcl-0.6.11.15, that approach to taking a union was a
2113          ;; bad idea, since it can overlook simplifications which
2114          ;; might occur if the terms were accumulated in a different
2115          ;; order. It's possible that that will be a problem here too.
2116          ;; However, I can't think of a good example to demonstrate
2117          ;; it, and without an example to demonstrate it I can't write
2118          ;; test cases, and without test cases I don't want to
2119          ;; complicate the code to address what's still a hypothetical
2120          ;; problem. So I punted. -- WHN 2001-03-20
2121          (let ((accumulator *empty-type*))
2122            (dolist (t2 (union-type-types type2) accumulator)
2123              (setf accumulator
2124                    (type-union2 accumulator
2125                                 (type-intersection type1 t2)))
2126              ;; When our result isn't simple any more (because
2127              ;; TYPE-UNION2 was unable to give us a simple result)
2128              (unless accumulator
2129                (return nil)))))))
2130
2131 (!def-type-translator or (&rest type-specifiers)
2132   (apply #'type-union
2133          (mapcar #'specifier-type
2134                  type-specifiers)))
2135 \f
2136 ;;;; CONS types
2137
2138 (!define-type-class cons)
2139
2140 (!def-type-translator cons (&optional (car-type-spec '*) (cdr-type-spec '*))
2141   (make-cons-type (specifier-type car-type-spec)
2142                   (specifier-type cdr-type-spec)))
2143  
2144 (!define-type-method (cons :unparse) (type)
2145   (let ((car-eltype (type-specifier (cons-type-car-type type)))
2146         (cdr-eltype (type-specifier (cons-type-cdr-type type))))
2147     (if (and (member car-eltype '(t *))
2148              (member cdr-eltype '(t *)))
2149         'cons
2150         `(cons ,car-eltype ,cdr-eltype))))
2151  
2152 (!define-type-method (cons :simple-=) (type1 type2)
2153   (declare (type cons-type type1 type2))
2154   (and (type= (cons-type-car-type type1) (cons-type-car-type type2))
2155        (type= (cons-type-cdr-type type1) (cons-type-cdr-type type2))))
2156  
2157 (!define-type-method (cons :simple-subtypep) (type1 type2)
2158   (declare (type cons-type type1 type2))
2159   (multiple-value-bind (val-car win-car)
2160       (csubtypep (cons-type-car-type type1) (cons-type-car-type type2))
2161     (multiple-value-bind (val-cdr win-cdr)
2162         (csubtypep (cons-type-cdr-type type1) (cons-type-cdr-type type2))
2163       (if (and val-car val-cdr)
2164           (values t (and win-car win-cdr))
2165           (values nil (or win-car win-cdr))))))
2166  
2167 ;;; Give up if a precise type is not possible, to avoid returning
2168 ;;; overly general types.
2169 (!define-type-method (cons :simple-union2) (type1 type2)
2170   (declare (type cons-type type1 type2))
2171   (let ((car-type1 (cons-type-car-type type1))
2172         (car-type2 (cons-type-car-type type2))
2173         (cdr-type1 (cons-type-cdr-type type1))
2174         (cdr-type2 (cons-type-cdr-type type2)))
2175     (cond ((type= car-type1 car-type2)
2176            (make-cons-type car-type1
2177                            (type-union cdr-type1 cdr-type2)))
2178           ((type= cdr-type1 cdr-type2)
2179            (make-cons-type (type-union cdr-type1 cdr-type2)
2180                            cdr-type1)))))
2181
2182 (!define-type-method (cons :simple-intersection2) (type1 type2)
2183   (declare (type cons-type type1 type2))
2184   (let (car-int2
2185         cdr-int2)
2186     (and (setf car-int2 (type-intersection2 (cons-type-car-type type1)
2187                                             (cons-type-car-type type2)))
2188          (setf cdr-int2 (type-intersection2 (cons-type-cdr-type type1)
2189                                             (cons-type-cdr-type type2)))
2190          (make-cons-type car-int2 cdr-int2))))
2191 \f
2192 ;;; Return the type that describes all objects that are in X but not
2193 ;;; in Y. If we can't determine this type, then return NIL.
2194 ;;;
2195 ;;; For now, we only are clever dealing with union and member types.
2196 ;;; If either type is not a union type, then we pretend that it is a
2197 ;;; union of just one type. What we do is remove from X all the types
2198 ;;; that are a subtype any type in Y. If any type in X intersects with
2199 ;;; a type in Y but is not a subtype, then we give up.
2200 ;;;
2201 ;;; We must also special-case any member type that appears in the
2202 ;;; union. We remove from X's members all objects that are TYPEP to Y.
2203 ;;; If Y has any members, we must be careful that none of those
2204 ;;; members are CTYPEP to any of Y's non-member types. We give up in
2205 ;;; this case, since to compute that difference we would have to break
2206 ;;; the type from X into some collection of types that represents the
2207 ;;; type without that particular element. This seems too hairy to be
2208 ;;; worthwhile, given its low utility.
2209 (defun type-difference (x y)
2210   (let ((x-types (if (union-type-p x) (union-type-types x) (list x)))
2211         (y-types (if (union-type-p y) (union-type-types y) (list y))))
2212     (collect ((res))
2213       (dolist (x-type x-types)
2214         (if (member-type-p x-type)
2215             (collect ((members))
2216               (dolist (mem (member-type-members x-type))
2217                 (multiple-value-bind (val win) (ctypep mem y)
2218                   (unless win (return-from type-difference nil))
2219                   (unless val
2220                     (members mem))))
2221               (when (members)
2222                 (res (make-member-type :members (members)))))
2223             (dolist (y-type y-types (res x-type))
2224               (multiple-value-bind (val win) (csubtypep x-type y-type)
2225                 (unless win (return-from type-difference nil))
2226                 (when val (return))
2227                 (when (types-equal-or-intersect x-type y-type)
2228                   (return-from type-difference nil))))))
2229       (let ((y-mem (find-if #'member-type-p y-types)))
2230         (when y-mem
2231           (let ((members (member-type-members y-mem)))
2232             (dolist (x-type x-types)
2233               (unless (member-type-p x-type)
2234                 (dolist (member members)
2235                   (multiple-value-bind (val win) (ctypep member x-type)
2236                     (when (or (not win) val)
2237                       (return-from type-difference nil)))))))))
2238       (apply #'type-union (res)))))
2239 \f
2240 (!def-type-translator array (&optional (element-type '*)
2241                                        (dimensions '*))
2242   (specialize-array-type
2243    (make-array-type :dimensions (canonical-array-dimensions dimensions)
2244                     :element-type (specifier-type element-type))))
2245
2246 (!def-type-translator simple-array (&optional (element-type '*)
2247                                               (dimensions '*))
2248   (specialize-array-type
2249    (make-array-type :dimensions (canonical-array-dimensions dimensions)
2250                     :element-type (specifier-type element-type)
2251                     :complexp nil)))
2252 \f
2253 ;;;; utilities shared between cross-compiler and target system
2254
2255 ;;; Does the type derived from compilation of an actual function
2256 ;;; definition satisfy declarations of a function's type?
2257 (defun defined-ftype-matches-declared-ftype-p (defined-ftype declared-ftype)
2258   (declare (type ctype defined-ftype declared-ftype))
2259   (flet ((is-built-in-class-function-p (ctype)
2260            (and (built-in-class-p ctype)
2261                 (eq (built-in-class-%name ctype) 'function))))
2262     (cond (;; DECLARED-FTYPE could certainly be #<BUILT-IN-CLASS FUNCTION>;
2263            ;; that's what happens when we (DECLAIM (FTYPE FUNCTION FOO)).
2264            (is-built-in-class-function-p declared-ftype)
2265            ;; In that case, any definition satisfies the declaration.
2266            t)
2267           (;; It's not clear whether or how DEFINED-FTYPE might be
2268            ;; #<BUILT-IN-CLASS FUNCTION>, but it's not obviously
2269            ;; invalid, so let's handle that case too, just in case.
2270            (is-built-in-class-function-p defined-ftype)
2271            ;; No matter what DECLARED-FTYPE might be, we can't prove
2272            ;; that an object of type FUNCTION doesn't satisfy it, so
2273            ;; we return success no matter what.
2274            t)
2275           (;; Otherwise both of them must be FUN-TYPE objects.
2276            t
2277            ;; FIXME: For now we only check compatibility of the return
2278            ;; type, not argument types, and we don't even check the
2279            ;; return type very precisely (as per bug 94a). It would be
2280            ;; good to do a better job. Perhaps to check the
2281            ;; compatibility of the arguments, we should (1) redo
2282            ;; VALUES-TYPES-EQUAL-OR-INTERSECT as
2283            ;; ARGS-TYPES-EQUAL-OR-INTERSECT, and then (2) apply it to
2284            ;; the ARGS-TYPE slices of the FUN-TYPEs. (ARGS-TYPE
2285            ;; is a base class both of VALUES-TYPE and of FUN-TYPE.)
2286            (values-types-equal-or-intersect
2287             (fun-type-returns defined-ftype)
2288             (fun-type-returns declared-ftype))))))
2289            
2290 ;;; This messy case of CTYPE for NUMBER is shared between the
2291 ;;; cross-compiler and the target system.
2292 (defun ctype-of-number (x)
2293   (let ((num (if (complexp x) (realpart x) x)))
2294     (multiple-value-bind (complexp low high)
2295         (if (complexp x)
2296             (let ((imag (imagpart x)))
2297               (values :complex (min num imag) (max num imag)))
2298             (values :real num num))
2299       (make-numeric-type :class (etypecase num
2300                                   (integer 'integer)
2301                                   (rational 'rational)
2302                                   (float 'float))
2303                          :format (and (floatp num) (float-format-name num))
2304                          :complexp complexp
2305                          :low low
2306                          :high high))))
2307 \f
2308 (locally
2309   ;; Why SAFETY 0? To suppress the is-it-the-right-structure-type
2310   ;; checking for declarations in structure accessors. Otherwise we
2311   ;; can get caught in a chicken-and-egg bootstrapping problem, whose
2312   ;; symptom on x86 OpenBSD sbcl-0.pre7.37.flaky5.22 is an illegal
2313   ;; instruction trap. I haven't tracked it down, but I'm guessing it
2314   ;; has to do with setting LAYOUTs when the LAYOUT hasn't been set
2315   ;; yet. -- WHN
2316   (declare (optimize (safety 0)))
2317   (!defun-from-collected-cold-init-forms !late-type-cold-init))
2318
2319 (/show0 "late-type.lisp end of file")