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