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