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