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