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