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