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