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