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