0.8alpha.0.8:
[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 (defmacro numeric-bound-test (x y closed open)
1457   `(cond ((not ,y) t)
1458          ((not ,x) nil)
1459          ((consp ,x)
1460           (if (consp ,y)
1461               (,closed (car ,x) (car ,y))
1462               (,closed (car ,x) ,y)))
1463          (t
1464           (if (consp ,y)
1465               (,open ,x (car ,y))
1466               (,closed ,x ,y)))))
1467
1468 ;;; This is used to compare upper and lower bounds. This is different
1469 ;;; from the same-bound case:
1470 ;;; -- Since X = NIL is -infinity, whereas y = NIL is +infinity, we
1471 ;;;    return true if *either* arg is NIL.
1472 ;;; -- an open inner bound is "greater" and also squeezes the interval,
1473 ;;;    causing us to use the OPEN test for those cases as well.
1474 (defmacro numeric-bound-test* (x y closed open)
1475   `(cond ((not ,y) t)
1476          ((not ,x) t)
1477          ((consp ,x)
1478           (if (consp ,y)
1479               (,open (car ,x) (car ,y))
1480               (,open (car ,x) ,y)))
1481          (t
1482           (if (consp ,y)
1483               (,open ,x (car ,y))
1484               (,closed ,x ,y)))))
1485
1486 ;;; Return whichever of the numeric bounds X and Y is "maximal"
1487 ;;; according to the predicates CLOSED (e.g. >=) and OPEN (e.g. >).
1488 ;;; This is only meaningful for maximizing like bounds, i.e. upper and
1489 ;;; upper. If MAX-P is true, then we return NIL if X or Y is NIL,
1490 ;;; otherwise we return the other arg.
1491 (defmacro numeric-bound-max (x y closed open max-p)
1492   (once-only ((n-x x)
1493               (n-y y))
1494     `(cond ((not ,n-x) ,(if max-p nil n-y))
1495            ((not ,n-y) ,(if max-p nil n-x))
1496            ((consp ,n-x)
1497             (if (consp ,n-y)
1498                 (if (,closed (car ,n-x) (car ,n-y)) ,n-x ,n-y)
1499                 (if (,open (car ,n-x) ,n-y) ,n-x ,n-y)))
1500            (t
1501             (if (consp ,n-y)
1502                 (if (,open (car ,n-y) ,n-x) ,n-y ,n-x)
1503                 (if (,closed ,n-y ,n-x) ,n-y ,n-x))))))
1504
1505 (!define-type-method (number :simple-subtypep) (type1 type2)
1506   (let ((class1 (numeric-type-class type1))
1507         (class2 (numeric-type-class type2))
1508         (complexp2 (numeric-type-complexp type2))
1509         (format2 (numeric-type-format type2))
1510         (low1 (numeric-type-low type1))
1511         (high1 (numeric-type-high type1))
1512         (low2 (numeric-type-low type2))
1513         (high2 (numeric-type-high type2)))
1514     ;; If one is complex and the other isn't, they are disjoint.
1515     (cond ((not (or (eq (numeric-type-complexp type1) complexp2)
1516                     (null complexp2)))
1517            (values nil t))
1518           ;; If the classes are specified and different, the types are
1519           ;; disjoint unless type2 is RATIONAL and type1 is INTEGER.
1520           ;; [ or type1 is INTEGER and type2 is of the form (RATIONAL
1521           ;; X X) for integral X, but this is dealt with in the
1522           ;; canonicalization inside MAKE-NUMERIC-TYPE ]
1523           ((not (or (eq class1 class2)
1524                     (null class2)
1525                     (and (eq class1 'integer) (eq class2 'rational))))
1526            (values nil t))
1527           ;; If the float formats are specified and different, the types
1528           ;; are disjoint.
1529           ((not (or (eq (numeric-type-format type1) format2)
1530                     (null format2)))
1531            (values nil t))
1532           ;; Check the bounds.
1533           ((and (numeric-bound-test low1 low2 >= >)
1534                 (numeric-bound-test high1 high2 <= <))
1535            (values t t))
1536           (t
1537            (values nil t)))))
1538
1539 (!define-superclasses number ((number)) !cold-init-forms)
1540
1541 ;;; If the high bound of LOW is adjacent to the low bound of HIGH,
1542 ;;; then return true, otherwise NIL.
1543 (defun numeric-types-adjacent (low high)
1544   (let ((low-bound (numeric-type-high low))
1545         (high-bound (numeric-type-low high)))
1546     (cond ((not (and low-bound high-bound)) nil)
1547           ((and (consp low-bound) (consp high-bound)) nil)
1548           ((consp low-bound)
1549            (let ((low-value (car low-bound)))
1550              (or (eql low-value high-bound)
1551                  (and (eql low-value -0f0) (eql high-bound 0f0))
1552                  (and (eql low-value 0f0) (eql high-bound -0f0))
1553                  (and (eql low-value -0d0) (eql high-bound 0d0))
1554                  (and (eql low-value 0d0) (eql high-bound -0d0)))))
1555           ((consp high-bound)
1556            (let ((high-value (car high-bound)))
1557              (or (eql high-value low-bound)
1558                  (and (eql high-value -0f0) (eql low-bound 0f0))
1559                  (and (eql high-value 0f0) (eql low-bound -0f0))
1560                  (and (eql high-value -0d0) (eql low-bound 0d0))
1561                  (and (eql high-value 0d0) (eql low-bound -0d0)))))
1562           ((and (eq (numeric-type-class low) 'integer)
1563                 (eq (numeric-type-class high) 'integer))
1564            (eql (1+ low-bound) high-bound))
1565           (t
1566            nil))))
1567
1568 ;;; Return a numeric type that is a supertype for both TYPE1 and TYPE2.
1569 ;;;
1570 ;;; Old comment, probably no longer applicable:
1571 ;;;
1572 ;;;   ### Note: we give up early to keep from dropping lots of
1573 ;;;   information on the floor by returning overly general types.
1574 (!define-type-method (number :simple-union2) (type1 type2)
1575   (declare (type numeric-type type1 type2))
1576   (cond ((csubtypep type1 type2) type2)
1577         ((csubtypep type2 type1) type1)
1578         (t
1579          (let ((class1 (numeric-type-class type1))
1580                (format1 (numeric-type-format type1))
1581                (complexp1 (numeric-type-complexp type1))
1582                (class2 (numeric-type-class type2))
1583                (format2 (numeric-type-format type2))
1584                (complexp2 (numeric-type-complexp type2)))
1585            (cond
1586              ((and (eq class1 class2)
1587                    (eq format1 format2)
1588                    (eq complexp1 complexp2)
1589                    (or (numeric-types-intersect type1 type2)
1590                        (numeric-types-adjacent type1 type2)
1591                        (numeric-types-adjacent type2 type1)))
1592               (make-numeric-type
1593                :class class1
1594                :format format1
1595                :complexp complexp1
1596                :low (numeric-bound-max (numeric-type-low type1)
1597                                        (numeric-type-low type2)
1598                                        <= < t)
1599                :high (numeric-bound-max (numeric-type-high type1)
1600                                         (numeric-type-high type2)
1601                                         >= > t)))
1602              ;; FIXME: These two clauses are almost identical, and the
1603              ;; consequents are in fact identical in every respect.
1604              ((and (eq class1 'rational)
1605                    (eq class2 'integer)
1606                    (eq format1 format2)
1607                    (eq complexp1 complexp2)
1608                    (integerp (numeric-type-low type2))
1609                    (integerp (numeric-type-high type2))
1610                    (= (numeric-type-low type2) (numeric-type-high type2))
1611                    (or (numeric-types-adjacent type1 type2)
1612                        (numeric-types-adjacent type2 type1)))
1613               (make-numeric-type
1614                :class 'rational
1615                :format format1
1616                :complexp complexp1
1617                :low (numeric-bound-max (numeric-type-low type1)
1618                                        (numeric-type-low type2)
1619                                        <= < t)
1620                :high (numeric-bound-max (numeric-type-high type1)
1621                                         (numeric-type-high type2)
1622                                         >= > t)))
1623              ((and (eq class1 'integer)
1624                    (eq class2 'rational)
1625                    (eq format1 format2)
1626                    (eq complexp1 complexp2)
1627                    (integerp (numeric-type-low type1))
1628                    (integerp (numeric-type-high type1))
1629                    (= (numeric-type-low type1) (numeric-type-high type1))
1630                    (or (numeric-types-adjacent type1 type2)
1631                        (numeric-types-adjacent type2 type1)))
1632               (make-numeric-type
1633                :class 'rational
1634                :format format1
1635                :complexp complexp1
1636                :low (numeric-bound-max (numeric-type-low type1)
1637                                        (numeric-type-low type2)
1638                                        <= < t)
1639                :high (numeric-bound-max (numeric-type-high type1)
1640                                         (numeric-type-high type2)
1641                                         >= > t)))
1642              (t nil))))))
1643               
1644
1645 (!cold-init-forms
1646   (setf (info :type :kind 'number)
1647         #+sb-xc-host :defined #-sb-xc-host :primitive)
1648   (setf (info :type :builtin 'number)
1649         (make-numeric-type :complexp nil)))
1650
1651 (!def-type-translator complex (&optional (typespec '*))
1652   (if (eq typespec '*)
1653       (make-numeric-type :complexp :complex)
1654       (labels ((not-numeric ()
1655                  (error "The component type for COMPLEX is not numeric: ~S"
1656                         typespec))
1657                (not-real ()
1658                  (error "The component type for COMPLEX is not real: ~S"
1659                         typespec))
1660                (complex1 (component-type)
1661                  (unless (numeric-type-p component-type)
1662                    (not-numeric))
1663                  (when (eq (numeric-type-complexp component-type) :complex)
1664                    (not-real))
1665                  (modified-numeric-type component-type :complexp :complex))
1666                (complex-union (component)
1667                  (unless (numberp component)
1668                    (not-numeric))
1669                  ;; KLUDGE: This TYPECASE more or less does
1670                  ;; (UPGRADED-COMPLEX-PART-TYPE (TYPE-OF COMPONENT)),
1671                  ;; (plus a small hack to treat (EQL COMPONENT 0) specially)
1672                  ;; but uses logic cut and pasted from the DEFUN of
1673                  ;; UPGRADED-COMPLEX-PART-TYPE. That's fragile, because
1674                  ;; changing the definition of UPGRADED-COMPLEX-PART-TYPE
1675                  ;; would tend to break the code here. Unfortunately,
1676                  ;; though, reusing UPGRADED-COMPLEX-PART-TYPE here
1677                  ;; would cause another kind of fragility, because
1678                  ;; ANSI's definition of TYPE-OF is so weak that e.g.
1679                  ;; (UPGRADED-COMPLEX-PART-TYPE (TYPE-OF 1/2)) could
1680                  ;; end up being (UPGRADED-COMPLEX-PART-TYPE 'REAL)
1681                  ;; instead of (UPGRADED-COMPLEX-PART-TYPE 'RATIONAL).
1682                  ;; So using TYPE-OF would mean that ANSI-conforming
1683                  ;; maintenance changes in TYPE-OF could break the code here.
1684                  ;; It's not clear how best to fix this. -- WHN 2002-01-21,
1685                  ;; trying to summarize CSR's concerns in his patch
1686                  (typecase component
1687                    (complex (error "The component type for COMPLEX (EQL X) ~
1688                                     is complex: ~S"
1689                                    component))
1690                    ((eql 0) (specifier-type nil)) ; as required by ANSI
1691                    (single-float (specifier-type '(complex single-float)))
1692                    (double-float (specifier-type '(complex double-float)))
1693                    #!+long-float
1694                    (long-float (specifier-type '(complex long-float)))
1695                    (rational (specifier-type '(complex rational)))
1696                    (t (specifier-type '(complex real))))))
1697         (let ((ctype (specifier-type typespec)))
1698           (typecase ctype
1699             (numeric-type (complex1 ctype))
1700             (union-type (apply #'type-union
1701                                ;; FIXME: This code could suffer from
1702                                ;; (admittedly very obscure) cases of
1703                                ;; bug 145 e.g. when TYPE is
1704                                ;;   (OR (AND INTEGER (SATISFIES ODDP))
1705                                ;;       (AND FLOAT (SATISFIES FOO))
1706                                ;; and not even report the problem very well.
1707                                (mapcar #'complex1
1708                                        (union-type-types ctype))))
1709             ;; MEMBER-TYPE is almost the same as UNION-TYPE, but
1710             ;; there's a gotcha: (COMPLEX (EQL 0)) is, according to
1711             ;; ANSI, equal to type NIL, the empty set.
1712             (member-type (apply #'type-union
1713                                 (mapcar #'complex-union
1714                                         (member-type-members ctype))))
1715             (t
1716              (multiple-value-bind (subtypep certainly)
1717                  (csubtypep ctype (specifier-type 'real))
1718                (if (and (not subtypep) certainly)
1719                    (not-real)
1720                    ;; ANSI just says that TYPESPEC is any subtype of
1721                    ;; type REAL, not necessarily a NUMERIC-TYPE. In
1722                    ;; particular, at this point TYPESPEC could legally be
1723                    ;; an intersection type like (AND REAL (SATISFIES ODDP)),
1724                    ;; in which case we fall through the logic above and
1725                    ;; end up here, stumped.
1726                    (bug "~@<(known bug #145): The type ~S is too hairy to be 
1727                          used for a COMPLEX component.~:@>"
1728                         typespec)))))))))
1729
1730 ;;; If X is *, return NIL, otherwise return the bound, which must be a
1731 ;;; member of TYPE or a one-element list of a member of TYPE.
1732 #!-sb-fluid (declaim (inline canonicalized-bound))
1733 (defun canonicalized-bound (bound type)
1734   (cond ((eq bound '*) nil)
1735         ((or (sb!xc:typep bound type)
1736              (and (consp bound)
1737                   (sb!xc:typep (car bound) type)
1738                   (null (cdr bound))))
1739           bound)
1740         (t
1741          (error "Bound is not ~S, a ~S or a list of a ~S: ~S"
1742                 '*
1743                 type
1744                 type
1745                 bound))))
1746
1747 (!def-type-translator integer (&optional (low '*) (high '*))
1748   (let* ((l (canonicalized-bound low 'integer))
1749          (lb (if (consp l) (1+ (car l)) l))
1750          (h (canonicalized-bound high 'integer))
1751          (hb (if (consp h) (1- (car h)) h)))
1752     (if (and hb lb (< hb lb))
1753         *empty-type*
1754       (make-numeric-type :class 'integer
1755                          :complexp :real
1756                          :enumerable (not (null (and l h)))
1757                          :low lb
1758                          :high hb))))
1759
1760 (defmacro !def-bounded-type (type class format)
1761   `(!def-type-translator ,type (&optional (low '*) (high '*))
1762      (let ((lb (canonicalized-bound low ',type))
1763            (hb (canonicalized-bound high ',type)))
1764        (if (not (numeric-bound-test* lb hb <= <))
1765            *empty-type*
1766          (make-numeric-type :class ',class
1767                             :format ',format
1768                             :low lb
1769                             :high hb)))))
1770
1771 (!def-bounded-type rational rational nil)
1772
1773 ;;; Unlike CMU CL, we represent the types FLOAT and REAL as
1774 ;;; UNION-TYPEs of more primitive types, in order to make
1775 ;;; type representation more unique, avoiding problems in the
1776 ;;; simplification of things like
1777 ;;;   (subtypep '(or (single-float -1.0 1.0) (single-float 0.1))
1778 ;;;             '(or (real -1 7) (single-float 0.1) (single-float -1.0 1.0)))
1779 ;;; When we allowed REAL to remain as a separate NUMERIC-TYPE,
1780 ;;; it was too easy for the first argument to be simplified to
1781 ;;; '(SINGLE-FLOAT -1.0), and for the second argument to be simplified
1782 ;;; to '(OR (REAL -1 7) (SINGLE-FLOAT 0.1)) and then for the
1783 ;;; SUBTYPEP to fail (returning NIL,T instead of T,T) because
1784 ;;; the first argument can't be seen to be a subtype of any of the
1785 ;;; terms in the second argument.
1786 ;;;
1787 ;;; The old CMU CL way was:
1788 ;;;   (!def-bounded-type float float nil)
1789 ;;;   (!def-bounded-type real nil nil)
1790 ;;;
1791 ;;; FIXME: If this new way works for a while with no weird new
1792 ;;; problems, we can go back and rip out support for separate FLOAT
1793 ;;; and REAL flavors of NUMERIC-TYPE. The new way was added in
1794 ;;; sbcl-0.6.11.22, 2001-03-21.
1795 ;;;
1796 ;;; FIXME: It's probably necessary to do something to fix the
1797 ;;; analogous problem with INTEGER and RATIONAL types. Perhaps
1798 ;;; bounded RATIONAL types should be represented as (OR RATIO INTEGER).
1799 (defun coerce-bound (bound type inner-coerce-bound-fun)
1800   (declare (type function inner-coerce-bound-fun))
1801   (cond ((eql bound '*)
1802          bound)
1803         ((consp bound)
1804          (destructuring-bind (inner-bound) bound
1805            (list (funcall inner-coerce-bound-fun inner-bound type))))
1806         (t
1807          (funcall inner-coerce-bound-fun bound type))))
1808 (defun inner-coerce-real-bound (bound type)
1809   (ecase type
1810     (rational (rationalize bound))
1811     (float (if (floatp bound)
1812                bound
1813                ;; Coerce to the widest float format available, to
1814                ;; avoid unnecessary loss of precision:
1815                (coerce bound 'long-float)))))
1816 (defun coerced-real-bound (bound type)
1817   (coerce-bound bound type #'inner-coerce-real-bound))
1818 (defun coerced-float-bound (bound type)
1819   (coerce-bound bound type #'coerce))
1820 (!def-type-translator real (&optional (low '*) (high '*))
1821   (specifier-type `(or (float ,(coerced-real-bound  low 'float)
1822                               ,(coerced-real-bound high 'float))
1823                        (rational ,(coerced-real-bound  low 'rational)
1824                                  ,(coerced-real-bound high 'rational)))))
1825 (!def-type-translator float (&optional (low '*) (high '*))
1826   (specifier-type 
1827    `(or (single-float ,(coerced-float-bound  low 'single-float)
1828                       ,(coerced-float-bound high 'single-float))
1829         (double-float ,(coerced-float-bound  low 'double-float)
1830                       ,(coerced-float-bound high 'double-float))
1831         #!+long-float ,(error "stub: no long float support yet"))))
1832
1833 (defmacro !define-float-format (f)
1834   `(!def-bounded-type ,f float ,f))
1835
1836 (!define-float-format short-float)
1837 (!define-float-format single-float)
1838 (!define-float-format double-float)
1839 (!define-float-format long-float)
1840
1841 (defun numeric-types-intersect (type1 type2)
1842   (declare (type numeric-type type1 type2))
1843   (let* ((class1 (numeric-type-class type1))
1844          (class2 (numeric-type-class type2))
1845          (complexp1 (numeric-type-complexp type1))
1846          (complexp2 (numeric-type-complexp type2))
1847          (format1 (numeric-type-format type1))
1848          (format2 (numeric-type-format type2))
1849          (low1 (numeric-type-low type1))
1850          (high1 (numeric-type-high type1))
1851          (low2 (numeric-type-low type2))
1852          (high2 (numeric-type-high type2)))
1853     ;; If one is complex and the other isn't, then they are disjoint.
1854     (cond ((not (or (eq complexp1 complexp2)
1855                     (null complexp1) (null complexp2)))
1856            nil)
1857           ;; If either type is a float, then the other must either be
1858           ;; specified to be a float or unspecified. Otherwise, they
1859           ;; are disjoint.
1860           ((and (eq class1 'float)
1861                 (not (member class2 '(float nil)))) nil)
1862           ((and (eq class2 'float)
1863                 (not (member class1 '(float nil)))) nil)
1864           ;; If the float formats are specified and different, the
1865           ;; types are disjoint.
1866           ((not (or (eq format1 format2) (null format1) (null format2)))
1867            nil)
1868           (t
1869            ;; Check the bounds. This is a bit odd because we must
1870            ;; always have the outer bound of the interval as the
1871            ;; second arg.
1872            (if (numeric-bound-test high1 high2 <= <)
1873                (or (and (numeric-bound-test low1 low2 >= >)
1874                         (numeric-bound-test* low1 high2 <= <))
1875                    (and (numeric-bound-test low2 low1 >= >)
1876                         (numeric-bound-test* low2 high1 <= <)))
1877                (or (and (numeric-bound-test* low2 high1 <= <)
1878                         (numeric-bound-test low2 low1 >= >))
1879                    (and (numeric-bound-test high2 high1 <= <)
1880                         (numeric-bound-test* high2 low1 >= >))))))))
1881
1882 ;;; Take the numeric bound X and convert it into something that can be
1883 ;;; used as a bound in a numeric type with the specified CLASS and
1884 ;;; FORMAT. If UP-P is true, then we round up as needed, otherwise we
1885 ;;; round down. UP-P true implies that X is a lower bound, i.e. (N) > N.
1886 ;;;
1887 ;;; This is used by NUMERIC-TYPE-INTERSECTION to mash the bound into
1888 ;;; the appropriate type number. X may only be a float when CLASS is
1889 ;;; FLOAT.
1890 ;;;
1891 ;;; ### Note: it is possible for the coercion to a float to overflow
1892 ;;; or underflow. This happens when the bound doesn't fit in the
1893 ;;; specified format. In this case, we should really return the
1894 ;;; appropriate {Most | Least}-{Positive | Negative}-XXX-Float float
1895 ;;; of desired format. But these conditions aren't currently signalled
1896 ;;; in any useful way.
1897 ;;;
1898 ;;; Also, when converting an open rational bound into a float we
1899 ;;; should probably convert it to a closed bound of the closest float
1900 ;;; in the specified format. KLUDGE: In general, open float bounds are
1901 ;;; screwed up. -- (comment from original CMU CL)
1902 (defun round-numeric-bound (x class format up-p)
1903   (if x
1904       (let ((cx (if (consp x) (car x) x)))
1905         (ecase class
1906           ((nil rational) x)
1907           (integer
1908            (if (and (consp x) (integerp cx))
1909                (if up-p (1+ cx) (1- cx))
1910                (if up-p (ceiling cx) (floor cx))))
1911           (float
1912            (let ((res (if format (coerce cx format) (float cx))))
1913              (if (consp x) (list res) res)))))
1914       nil))
1915
1916 ;;; Handle the case of type intersection on two numeric types. We use
1917 ;;; TYPES-EQUAL-OR-INTERSECT to throw out the case of types with no
1918 ;;; intersection. If an attribute in TYPE1 is unspecified, then we use
1919 ;;; TYPE2's attribute, which must be at least as restrictive. If the
1920 ;;; types intersect, then the only attributes that can be specified
1921 ;;; and different are the class and the bounds.
1922 ;;;
1923 ;;; When the class differs, we use the more restrictive class. The
1924 ;;; only interesting case is RATIONAL/INTEGER, since RATIONAL includes
1925 ;;; INTEGER.
1926 ;;;
1927 ;;; We make the result lower (upper) bound the maximum (minimum) of
1928 ;;; the argument lower (upper) bounds. We convert the bounds into the
1929 ;;; appropriate numeric type before maximizing. This avoids possible
1930 ;;; confusion due to mixed-type comparisons (but I think the result is
1931 ;;; the same).
1932 (!define-type-method (number :simple-intersection2) (type1 type2)
1933   (declare (type numeric-type type1 type2))
1934   (if (numeric-types-intersect type1 type2)
1935       (let* ((class1 (numeric-type-class type1))
1936              (class2 (numeric-type-class type2))
1937              (class (ecase class1
1938                       ((nil) class2)
1939                       ((integer float) class1)
1940                       (rational (if (eq class2 'integer)
1941                                        'integer
1942                                        'rational))))
1943              (format (or (numeric-type-format type1)
1944                          (numeric-type-format type2))))
1945         (make-numeric-type
1946          :class class
1947          :format format
1948          :complexp (or (numeric-type-complexp type1)
1949                        (numeric-type-complexp type2))
1950          :low (numeric-bound-max
1951                (round-numeric-bound (numeric-type-low type1)
1952                                     class format t)
1953                (round-numeric-bound (numeric-type-low type2)
1954                                     class format t)
1955                > >= nil)
1956          :high (numeric-bound-max
1957                 (round-numeric-bound (numeric-type-high type1)
1958                                      class format nil)
1959                 (round-numeric-bound (numeric-type-high type2)
1960                                      class format nil)
1961                 < <= nil)))
1962       *empty-type*))
1963
1964 ;;; Given two float formats, return the one with more precision. If
1965 ;;; either one is null, return NIL.
1966 (defun float-format-max (f1 f2)
1967   (when (and f1 f2)
1968     (dolist (f *float-formats* (error "bad float format: ~S" f1))
1969       (when (or (eq f f1) (eq f f2))
1970         (return f)))))
1971
1972 ;;; Return the result of an operation on TYPE1 and TYPE2 according to
1973 ;;; the rules of numeric contagion. This is always NUMBER, some float
1974 ;;; format (possibly complex) or RATIONAL. Due to rational
1975 ;;; canonicalization, there isn't much we can do here with integers or
1976 ;;; rational complex numbers.
1977 ;;;
1978 ;;; If either argument is not a NUMERIC-TYPE, then return NUMBER. This
1979 ;;; is useful mainly for allowing types that are technically numbers,
1980 ;;; but not a NUMERIC-TYPE.
1981 (defun numeric-contagion (type1 type2)
1982   (if (and (numeric-type-p type1) (numeric-type-p type2))
1983       (let ((class1 (numeric-type-class type1))
1984             (class2 (numeric-type-class type2))
1985             (format1 (numeric-type-format type1))
1986             (format2 (numeric-type-format type2))
1987             (complexp1 (numeric-type-complexp type1))
1988             (complexp2 (numeric-type-complexp type2)))
1989         (cond ((or (null complexp1)
1990                    (null complexp2))
1991                (specifier-type 'number))
1992               ((eq class1 'float)
1993                (make-numeric-type
1994                 :class 'float
1995                 :format (ecase class2
1996                           (float (float-format-max format1 format2))
1997                           ((integer rational) format1)
1998                           ((nil)
1999                            ;; A double-float with any real number is a
2000                            ;; double-float.
2001                            #!-long-float
2002                            (if (eq format1 'double-float)
2003                              'double-float
2004                              nil)
2005                            ;; A long-float with any real number is a
2006                            ;; long-float.
2007                            #!+long-float
2008                            (if (eq format1 'long-float)
2009                              'long-float
2010                              nil)))
2011                 :complexp (if (or (eq complexp1 :complex)
2012                                   (eq complexp2 :complex))
2013                               :complex
2014                               :real)))
2015               ((eq class2 'float) (numeric-contagion type2 type1))
2016               ((and (eq complexp1 :real) (eq complexp2 :real))
2017                (make-numeric-type
2018                 :class (and class1 class2 'rational)
2019                 :complexp :real))
2020               (t
2021                (specifier-type 'number))))
2022       (specifier-type 'number)))
2023 \f
2024 ;;;; array types
2025
2026 (!define-type-class array)
2027
2028 ;;; What this does depends on the setting of the
2029 ;;; *USE-IMPLEMENTATION-TYPES* switch. If true, return the specialized
2030 ;;; element type, otherwise return the original element type.
2031 (defun specialized-element-type-maybe (type)
2032   (declare (type array-type type))
2033   (if *use-implementation-types*
2034       (array-type-specialized-element-type type)
2035       (array-type-element-type type)))
2036
2037 (!define-type-method (array :simple-=) (type1 type2)
2038   (if (or (unknown-type-p (array-type-element-type type1))
2039           (unknown-type-p (array-type-element-type type2)))
2040       (multiple-value-bind (equalp certainp)
2041           (type= (array-type-element-type type1)
2042                  (array-type-element-type type2))
2043         ;; by its nature, the call to TYPE= should never return NIL,
2044         ;; T, as we don't know what the UNKNOWN-TYPE will grow up to
2045         ;; be.  -- CSR, 2002-08-19
2046         (aver (not (and (not equalp) certainp)))
2047         (values equalp certainp))
2048       (values (and (equal (array-type-dimensions type1)
2049                           (array-type-dimensions type2))
2050                    (eq (array-type-complexp type1)
2051                        (array-type-complexp type2))
2052                    (type= (specialized-element-type-maybe type1)
2053                           (specialized-element-type-maybe type2)))
2054               t)))
2055
2056 (!define-type-method (array :unparse) (type)
2057   (let ((dims (array-type-dimensions type))
2058         (eltype (type-specifier (array-type-element-type type)))
2059         (complexp (array-type-complexp type)))
2060     (cond ((eq dims '*)
2061            (if (eq eltype '*)
2062                (if complexp 'array 'simple-array)
2063                (if complexp `(array ,eltype) `(simple-array ,eltype))))
2064           ((= (length dims) 1)
2065            (if complexp
2066                (if (eq (car dims) '*)
2067                    (case eltype
2068                      (bit 'bit-vector)
2069                      (base-char 'base-string)
2070                      (character 'string)
2071                      (* 'vector)
2072                      (t `(vector ,eltype)))
2073                    (case eltype
2074                      (bit `(bit-vector ,(car dims)))
2075                      (base-char `(base-string ,(car dims)))
2076                      (character `(string ,(car dims)))
2077                      (t `(vector ,eltype ,(car dims)))))
2078                (if (eq (car dims) '*)
2079                    (case eltype
2080                      (bit 'simple-bit-vector)
2081                      (base-char 'simple-base-string)
2082                      (character 'simple-string)
2083                      ((t) 'simple-vector)
2084                      (t `(simple-array ,eltype (*))))
2085                    (case eltype
2086                      (bit `(simple-bit-vector ,(car dims)))
2087                      (base-char `(simple-base-string ,(car dims)))
2088                      (character `(simple-string ,(car dims)))
2089                      ((t) `(simple-vector ,(car dims)))
2090                      (t `(simple-array ,eltype ,dims))))))
2091           (t
2092            (if complexp
2093                `(array ,eltype ,dims)
2094                `(simple-array ,eltype ,dims))))))
2095
2096 (!define-type-method (array :simple-subtypep) (type1 type2)
2097   (let ((dims1 (array-type-dimensions type1))
2098         (dims2 (array-type-dimensions type2))
2099         (complexp2 (array-type-complexp type2)))
2100     (cond (;; not subtypep unless dimensions are compatible
2101            (not (or (eq dims2 '*)
2102                     (and (not (eq dims1 '*))
2103                          ;; (sbcl-0.6.4 has trouble figuring out that
2104                          ;; DIMS1 and DIMS2 must be lists at this
2105                          ;; point, and knowing that is important to
2106                          ;; compiling EVERY efficiently.)
2107                          (= (length (the list dims1))
2108                             (length (the list dims2)))
2109                          (every (lambda (x y)
2110                                   (or (eq y '*) (eql x y)))
2111                                 (the list dims1)
2112                                 (the list dims2)))))
2113            (values nil t))
2114           ;; not subtypep unless complexness is compatible
2115           ((not (or (eq complexp2 :maybe)
2116                     (eq (array-type-complexp type1) complexp2)))
2117            (values nil t))
2118           ;; Since we didn't fail any of the tests above, we win
2119           ;; if the TYPE2 element type is wild.
2120           ((eq (array-type-element-type type2) *wild-type*)
2121            (values t t))
2122           (;; Since we didn't match any of the special cases above, we
2123            ;; can't give a good answer unless both the element types
2124            ;; have been defined.
2125            (or (unknown-type-p (array-type-element-type type1))
2126                (unknown-type-p (array-type-element-type type2)))
2127            (values nil nil))
2128           (;; Otherwise, the subtype relationship holds iff the
2129            ;; types are equal, and they're equal iff the specialized
2130            ;; element types are identical.
2131            t
2132            (values (type= (specialized-element-type-maybe type1)
2133                           (specialized-element-type-maybe type2))
2134                    t)))))
2135
2136 (!define-superclasses array
2137   ((string string)
2138    (vector vector)
2139    (array))
2140   !cold-init-forms)
2141
2142 (defun array-types-intersect (type1 type2)
2143   (declare (type array-type type1 type2))
2144   (let ((dims1 (array-type-dimensions type1))
2145         (dims2 (array-type-dimensions type2))
2146         (complexp1 (array-type-complexp type1))
2147         (complexp2 (array-type-complexp type2)))
2148     ;; See whether dimensions are compatible.
2149     (cond ((not (or (eq dims1 '*) (eq dims2 '*)
2150                     (and (= (length dims1) (length dims2))
2151                          (every (lambda (x y)
2152                                   (or (eq x '*) (eq y '*) (= x y)))
2153                                 dims1 dims2))))
2154            (values nil t))
2155           ;; See whether complexpness is compatible.
2156           ((not (or (eq complexp1 :maybe)
2157                     (eq complexp2 :maybe)
2158                     (eq complexp1 complexp2)))
2159            (values nil t))
2160           ;; Old comment:
2161           ;;
2162           ;;   If either element type is wild, then they intersect.
2163           ;;   Otherwise, the types must be identical.
2164           ;;
2165           ;; FIXME: There seems to have been a fair amount of
2166           ;; confusion about the distinction between requested element
2167           ;; type and specialized element type; here is one of
2168           ;; them. If we request an array to hold objects of an
2169           ;; unknown type, we can do no better than represent that
2170           ;; type as an array specialized on wild-type.  We keep the
2171           ;; requested element-type in the -ELEMENT-TYPE slot, and
2172           ;; *WILD-TYPE* in the -SPECIALIZED-ELEMENT-TYPE.  So, here,
2173           ;; we must test for the SPECIALIZED slot being *WILD-TYPE*,
2174           ;; not just the ELEMENT-TYPE slot.  Maybe the return value
2175           ;; in that specific case should be T, NIL?  Or maybe this
2176           ;; function should really be called
2177           ;; ARRAY-TYPES-COULD-POSSIBLY-INTERSECT?  In any case, this
2178           ;; was responsible for bug #123, and this whole issue could
2179           ;; do with a rethink and/or a rewrite.  -- CSR, 2002-08-21
2180           ((or (eq (array-type-specialized-element-type type1) *wild-type*)
2181                (eq (array-type-specialized-element-type type2) *wild-type*)
2182                (type= (specialized-element-type-maybe type1)
2183                       (specialized-element-type-maybe type2)))
2184
2185            (values t t))
2186           (t
2187            (values nil t)))))
2188
2189 (!define-type-method (array :simple-intersection2) (type1 type2)
2190   (declare (type array-type type1 type2))
2191   (if (array-types-intersect type1 type2)
2192       (let ((dims1 (array-type-dimensions type1))
2193             (dims2 (array-type-dimensions type2))
2194             (complexp1 (array-type-complexp type1))
2195             (complexp2 (array-type-complexp type2))
2196             (eltype1 (array-type-element-type type1))
2197             (eltype2 (array-type-element-type type2)))
2198         (specialize-array-type
2199          (make-array-type
2200           :dimensions (cond ((eq dims1 '*) dims2)
2201                             ((eq dims2 '*) dims1)
2202                             (t
2203                              (mapcar (lambda (x y) (if (eq x '*) y x))
2204                                      dims1 dims2)))
2205           :complexp (if (eq complexp1 :maybe) complexp2 complexp1)
2206           :element-type (if (eq eltype1 *wild-type*) eltype2 eltype1))))
2207       *empty-type*))
2208
2209 ;;; Check a supplied dimension list to determine whether it is legal,
2210 ;;; and return it in canonical form (as either '* or a list).
2211 (defun canonical-array-dimensions (dims)
2212   (typecase dims
2213     ((member *) dims)
2214     (integer
2215      (when (minusp dims)
2216        (error "Arrays can't have a negative number of dimensions: ~S" dims))
2217      (when (>= dims sb!xc:array-rank-limit)
2218        (error "array type with too many dimensions: ~S" dims))
2219      (make-list dims :initial-element '*))
2220     (list
2221      (when (>= (length dims) sb!xc:array-rank-limit)
2222        (error "array type with too many dimensions: ~S" dims))
2223      (dolist (dim dims)
2224        (unless (eq dim '*)
2225          (unless (and (integerp dim)
2226                       (>= dim 0)
2227                       (< dim sb!xc:array-dimension-limit))
2228            (error "bad dimension in array type: ~S" dim))))
2229      dims)
2230     (t
2231      (error "Array dimensions is not a list, integer or *:~%  ~S" dims))))
2232 \f
2233 ;;;; MEMBER types
2234
2235 (!define-type-class member)
2236
2237 (!define-type-method (member :unparse) (type)
2238   (let ((members (member-type-members type)))
2239     (cond
2240       ((equal members '(nil)) 'null)
2241       ((type= type (specifier-type 'standard-char)) 'standard-char)
2242       (t `(member ,@members)))))
2243
2244 (!define-type-method (member :simple-subtypep) (type1 type2)
2245   (values (subsetp (member-type-members type1) (member-type-members type2))
2246           t))
2247
2248 (!define-type-method (member :complex-subtypep-arg1) (type1 type2)
2249   (every/type (swapped-args-fun #'ctypep)
2250               type2
2251               (member-type-members type1)))
2252
2253 ;;; We punt if the odd type is enumerable and intersects with the
2254 ;;; MEMBER type. If not enumerable, then it is definitely not a
2255 ;;; subtype of the MEMBER type.
2256 (!define-type-method (member :complex-subtypep-arg2) (type1 type2)
2257   (cond ((not (type-enumerable type1)) (values nil t))
2258         ((types-equal-or-intersect type1 type2)
2259          (invoke-complex-subtypep-arg1-method type1 type2))
2260         (t (values nil t))))
2261
2262 (!define-type-method (member :simple-intersection2) (type1 type2)
2263   (let ((mem1 (member-type-members type1))
2264         (mem2 (member-type-members type2)))
2265     (cond ((subsetp mem1 mem2) type1)
2266           ((subsetp mem2 mem1) type2)
2267           (t
2268            (let ((res (intersection mem1 mem2)))
2269              (if res
2270                  (make-member-type :members res)
2271                  *empty-type*))))))
2272
2273 (!define-type-method (member :complex-intersection2) (type1 type2)
2274   (block punt
2275     (collect ((members))
2276       (let ((mem2 (member-type-members type2)))
2277         (dolist (member mem2)
2278           (multiple-value-bind (val win) (ctypep member type1)
2279             (unless win
2280               (return-from punt nil))
2281             (when val (members member))))
2282         (cond ((subsetp mem2 (members)) type2)
2283               ((null (members)) *empty-type*)
2284               (t
2285                (make-member-type :members (members))))))))
2286
2287 ;;; We don't need a :COMPLEX-UNION2, since the only interesting case is
2288 ;;; a union type, and the member/union interaction is handled by the
2289 ;;; union type method.
2290 (!define-type-method (member :simple-union2) (type1 type2)
2291   (let ((mem1 (member-type-members type1))
2292         (mem2 (member-type-members type2)))
2293     (cond ((subsetp mem1 mem2) type2)
2294           ((subsetp mem2 mem1) type1)
2295           (t
2296            (make-member-type :members (union mem1 mem2))))))
2297
2298 (!define-type-method (member :simple-=) (type1 type2)
2299   (let ((mem1 (member-type-members type1))
2300         (mem2 (member-type-members type2)))
2301     (values (and (subsetp mem1 mem2)
2302                  (subsetp mem2 mem1))
2303             t)))
2304
2305 (!define-type-method (member :complex-=) (type1 type2)
2306   (if (type-enumerable type1)
2307       (multiple-value-bind (val win) (csubtypep type2 type1)
2308         (if (or val (not win))
2309             (values nil nil)
2310             (values nil t)))
2311       (values nil t)))
2312
2313 (!def-type-translator member (&rest members)
2314   (if members
2315       (let (ms numbers)
2316         (dolist (m (remove-duplicates members))
2317           (typecase m
2318             (float (if (zerop m)
2319                        (push m ms)
2320                        (push (ctype-of m) numbers)))
2321             (number (push (ctype-of m) numbers))
2322             (t (push m ms))))
2323         (apply #'type-union
2324                (if ms
2325                    (make-member-type :members ms)
2326                    *empty-type*)
2327                (nreverse numbers)))
2328       *empty-type*))
2329 \f
2330 ;;;; intersection types
2331 ;;;;
2332 ;;;; Until version 0.6.10.6, SBCL followed the original CMU CL approach
2333 ;;;; of punting on all AND types, not just the unreasonably complicated
2334 ;;;; ones. The change was motivated by trying to get the KEYWORD type
2335 ;;;; to behave sensibly:
2336 ;;;;    ;; reasonable definition
2337 ;;;;    (DEFTYPE KEYWORD () '(AND SYMBOL (SATISFIES KEYWORDP)))
2338 ;;;;    ;; reasonable behavior
2339 ;;;;    (AVER (SUBTYPEP 'KEYWORD 'SYMBOL))
2340 ;;;; Without understanding a little about the semantics of AND, we'd
2341 ;;;; get (SUBTYPEP 'KEYWORD 'SYMBOL)=>NIL,NIL and, for entirely
2342 ;;;; parallel reasons, (SUBTYPEP 'RATIO 'NUMBER)=>NIL,NIL. That's
2343 ;;;; not so good..)
2344 ;;;;
2345 ;;;; We still follow the example of CMU CL to some extent, by punting
2346 ;;;; (to the opaque HAIRY-TYPE) on sufficiently complicated types
2347 ;;;; involving AND.
2348
2349 (!define-type-class intersection)
2350
2351 ;;; A few intersection types have special names. The others just get
2352 ;;; mechanically unparsed.
2353 (!define-type-method (intersection :unparse) (type)
2354   (declare (type ctype type))
2355   (or (find type '(ratio keyword) :key #'specifier-type :test #'type=)
2356       `(and ,@(mapcar #'type-specifier (intersection-type-types type)))))
2357
2358 ;;; shared machinery for type equality: true if every type in the set
2359 ;;; TYPES1 matches a type in the set TYPES2 and vice versa
2360 (defun type=-set (types1 types2)
2361   (flet ((type<=-set (x y)
2362            (declare (type list x y))
2363            (every/type (lambda (x y-element)
2364                          (any/type #'type= y-element x))
2365                        x y)))
2366     (and/type (type<=-set types1 types2)
2367               (type<=-set types2 types1))))
2368
2369 ;;; Two intersection types are equal if their subtypes are equal sets.
2370 ;;;
2371 ;;; FIXME: Might it be better to use
2372 ;;;   (AND (SUBTYPEP X Y) (SUBTYPEP Y X))
2373 ;;; instead, since SUBTYPEP is the usual relationship that we care
2374 ;;; most about, so it would be good to leverage any ingenuity there
2375 ;;; in this more obscure method?
2376 (!define-type-method (intersection :simple-=) (type1 type2)
2377   (type=-set (intersection-type-types type1)
2378              (intersection-type-types type2)))
2379
2380 (defun %intersection-complex-subtypep-arg1 (type1 type2)
2381   (type= type1 (type-intersection type1 type2)))
2382
2383 (defun %intersection-simple-subtypep (type1 type2)
2384   (every/type #'%intersection-complex-subtypep-arg1
2385               type1
2386               (intersection-type-types type2)))
2387
2388 (!define-type-method (intersection :simple-subtypep) (type1 type2)
2389   (%intersection-simple-subtypep type1 type2))
2390   
2391 (!define-type-method (intersection :complex-subtypep-arg1) (type1 type2)
2392   (%intersection-complex-subtypep-arg1 type1 type2))
2393
2394 (defun %intersection-complex-subtypep-arg2 (type1 type2)
2395   (every/type #'csubtypep type1 (intersection-type-types type2)))
2396
2397 (!define-type-method (intersection :complex-subtypep-arg2) (type1 type2)
2398   (%intersection-complex-subtypep-arg2 type1 type2))
2399
2400 ;;; FIXME: This will look eeriely familiar to readers of the UNION
2401 ;;; :SIMPLE-INTERSECTION2 :COMPLEX-INTERSECTION2 method.  That's
2402 ;;; because it was generated by cut'n'paste methods.  Given that
2403 ;;; intersections and unions have all sorts of symmetries known to
2404 ;;; mathematics, it shouldn't be beyond the ken of some programmers to
2405 ;;; reflect those symmetries in code in a way that ties them together
2406 ;;; more strongly than having two independent near-copies :-/
2407 (!define-type-method (intersection :simple-union2 :complex-union2)
2408                      (type1 type2)
2409   ;; Within this method, type2 is guaranteed to be an intersection
2410   ;; type:
2411   (aver (intersection-type-p type2))
2412   ;; Make sure to call only the applicable methods...
2413   (cond ((and (intersection-type-p type1)
2414               (%intersection-simple-subtypep type1 type2)) type2)
2415         ((and (intersection-type-p type1)
2416               (%intersection-simple-subtypep type2 type1)) type1)
2417         ((and (not (intersection-type-p type1))
2418               (%intersection-complex-subtypep-arg2 type1 type2))
2419          type2)
2420         ((and (not (intersection-type-p type1))
2421               (%intersection-complex-subtypep-arg1 type2 type1))
2422          type1)
2423         ;; KLUDGE: This special (and somewhat hairy) magic is required
2424         ;; to deal with the RATIONAL/INTEGER special case.  The UNION
2425         ;; of (INTEGER * -1) and (AND (RATIONAL * -1/2) (NOT INTEGER))
2426         ;; should be (RATIONAL * -1/2) -- CSR, 2003-02-28
2427         ((and (csubtypep type2 (specifier-type 'ratio))
2428               (numeric-type-p type1)
2429               (csubtypep type1 (specifier-type 'integer))
2430               (csubtypep type2
2431                          (make-numeric-type
2432                           :class 'rational
2433                           :complexp nil
2434                           :low (if (null (numeric-type-low type1))
2435                                    nil
2436                                    (list (1- (numeric-type-low type1))))
2437                           :high (if (null (numeric-type-high type1))
2438                                     nil
2439                                     (list (1+ (numeric-type-high type1)))))))
2440          (type-union type1
2441                      (apply #'type-intersection
2442                             (remove (specifier-type '(not integer))
2443                                     (intersection-type-types type2)
2444                                     :test #'type=))))
2445         (t
2446          (let ((accumulator *universal-type*))
2447            (do ((t2s (intersection-type-types type2) (cdr t2s)))
2448                ((null t2s) accumulator)
2449              (let ((union (type-union type1 (car t2s))))
2450                (when (union-type-p union)
2451                  ;; we have to give up here -- there are all sorts of
2452                  ;; ordering worries, but it's better than before.
2453                  ;; Doing exactly the same as in the UNION
2454                  ;; :SIMPLE/:COMPLEX-INTERSECTION2 method causes stack
2455                  ;; overflow with the mutual recursion never bottoming
2456                  ;; out.
2457                  (if (and (eq accumulator *universal-type*)
2458                           (null (cdr t2s)))
2459                      ;; KLUDGE: if we get here, we have a partially
2460                      ;; simplified result.  While this isn't by any
2461                      ;; means a universal simplification, including
2462                      ;; this logic here means that we can get (OR
2463                      ;; KEYWORD (NOT KEYWORD)) canonicalized to T.
2464                      (return union)
2465                      (return nil)))
2466                (setf accumulator
2467                      (type-intersection accumulator union))))))))
2468          
2469 (!def-type-translator and (&whole whole &rest type-specifiers)
2470   (apply #'type-intersection
2471          (mapcar #'specifier-type
2472                  type-specifiers)))
2473 \f
2474 ;;;; union types
2475
2476 (!define-type-class union)
2477
2478 ;;; The LIST, FLOAT and REAL types have special names.  Other union
2479 ;;; types just get mechanically unparsed.
2480 (!define-type-method (union :unparse) (type)
2481   (declare (type ctype type))
2482   (cond
2483     ((type= type (specifier-type 'list)) 'list)
2484     ((type= type (specifier-type 'float)) 'float)
2485     ((type= type (specifier-type 'real)) 'real)
2486     ((type= type (specifier-type 'sequence)) 'sequence)
2487     ((type= type (specifier-type 'bignum)) 'bignum)
2488     (t `(or ,@(mapcar #'type-specifier (union-type-types type))))))
2489
2490 ;;; Two union types are equal if they are each subtypes of each
2491 ;;; other. We need to be this clever because our complex subtypep
2492 ;;; methods are now more accurate; we don't get infinite recursion
2493 ;;; because the simple-subtypep method delegates to complex-subtypep
2494 ;;; of the individual types of type1. - CSR, 2002-04-09
2495 ;;;
2496 ;;; Previous comment, now obsolete, but worth keeping around because
2497 ;;; it is true, though too strong a condition:
2498 ;;;
2499 ;;; Two union types are equal if their subtypes are equal sets.
2500 (!define-type-method (union :simple-=) (type1 type2)
2501   (multiple-value-bind (subtype certain?)
2502       (csubtypep type1 type2)
2503     (if subtype
2504         (csubtypep type2 type1)
2505         ;; we might as well become as certain as possible.
2506         (if certain?
2507             (values nil t)
2508             (multiple-value-bind (subtype certain?)
2509                 (csubtypep type2 type1)
2510               (declare (ignore subtype))
2511               (values nil certain?))))))
2512
2513 (!define-type-method (union :complex-=) (type1 type2)
2514   (declare (ignore type1))
2515   (if (some #'type-might-contain-other-types-p 
2516             (union-type-types type2))
2517       (values nil nil)
2518       (values nil t)))
2519
2520 ;;; Similarly, a union type is a subtype of another if and only if
2521 ;;; every element of TYPE1 is a subtype of TYPE2.
2522 (defun union-simple-subtypep (type1 type2)
2523   (every/type (swapped-args-fun #'union-complex-subtypep-arg2)
2524               type2
2525               (union-type-types type1)))
2526
2527 (!define-type-method (union :simple-subtypep) (type1 type2)
2528   (union-simple-subtypep type1 type2))
2529   
2530 (defun union-complex-subtypep-arg1 (type1 type2)
2531   (every/type (swapped-args-fun #'csubtypep)
2532               type2
2533               (union-type-types type1)))
2534
2535 (!define-type-method (union :complex-subtypep-arg1) (type1 type2)
2536   (union-complex-subtypep-arg1 type1 type2))
2537
2538 (defun union-complex-subtypep-arg2 (type1 type2)
2539   (multiple-value-bind (sub-value sub-certain?)
2540       ;; was: (any/type #'csubtypep type1 (union-type-types type2)),
2541       ;; which turns out to be too restrictive, causing bug 91.
2542       ;;
2543       ;; the following reimplementation might look dodgy.  It is
2544       ;; dodgy. It depends on the union :complex-= method not doing
2545       ;; very much work -- certainly, not using subtypep. Reasoning:
2546       (progn
2547         ;; At this stage, we know that type2 is a union type and type1
2548         ;; isn't. We might as well check this, though:
2549         (aver (union-type-p type2))
2550         (aver (not (union-type-p type1)))
2551         ;;     A is a subset of (B1 u B2)
2552         ;; <=> A n (B1 u B2) = A
2553         ;; <=> (A n B1) u (A n B2) = A
2554         ;;
2555         ;; But, we have to be careful not to delegate this type= to
2556         ;; something that could invoke subtypep, which might get us
2557         ;; back here -> stack explosion. We therefore ensure that the
2558         ;; second type (which is the one that's dispatched on) is
2559         ;; either a union type (where we've ensured that the complex-=
2560         ;; method will not call subtypep) or something with no union
2561         ;; types involved, in which case we'll never come back here.
2562         ;;
2563         ;; If we don't do this, then e.g.
2564         ;; (SUBTYPEP '(MEMBER 3) '(OR (SATISFIES FOO) (SATISFIES BAR)))
2565         ;; would loop infinitely, as the member :complex-= method is
2566         ;; implemented in terms of subtypep.
2567         ;;
2568         ;; Ouch. - CSR, 2002-04-10
2569         (type= type1
2570                (apply #'type-union
2571                       (mapcar (lambda (x) (type-intersection type1 x))
2572                               (union-type-types type2)))))
2573     (if sub-certain?
2574         (values sub-value sub-certain?)
2575         ;; The ANY/TYPE expression above is a sufficient condition for
2576         ;; subsetness, but not a necessary one, so we might get a more
2577         ;; certain answer by this CALL-NEXT-METHOD-ish step when the
2578         ;; ANY/TYPE expression is uncertain.
2579         (invoke-complex-subtypep-arg1-method type1 type2))))
2580
2581 (!define-type-method (union :complex-subtypep-arg2) (type1 type2)
2582   (union-complex-subtypep-arg2 type1 type2))
2583
2584 (!define-type-method (union :simple-intersection2 :complex-intersection2)
2585                      (type1 type2)
2586   ;; The CSUBTYPEP clauses here let us simplify e.g.
2587   ;;   (TYPE-INTERSECTION2 (SPECIFIER-TYPE 'LIST)
2588   ;;                       (SPECIFIER-TYPE '(OR LIST VECTOR)))
2589   ;; (where LIST is (OR CONS NULL)).
2590   ;;
2591   ;; The tests are more or less (CSUBTYPEP TYPE1 TYPE2) and vice
2592   ;; versa, but it's important that we pre-expand them into
2593   ;; specialized operations on individual elements of
2594   ;; UNION-TYPE-TYPES, instead of using the ordinary call to
2595   ;; CSUBTYPEP, in order to avoid possibly invoking any methods which
2596   ;; might in turn invoke (TYPE-INTERSECTION2 TYPE1 TYPE2) and thus
2597   ;; cause infinite recursion.
2598   ;;
2599   ;; Within this method, type2 is guaranteed to be a union type:
2600   (aver (union-type-p type2))
2601   ;; Make sure to call only the applicable methods...
2602   (cond ((and (union-type-p type1)
2603               (union-simple-subtypep type1 type2)) type1)
2604         ((and (union-type-p type1)
2605               (union-simple-subtypep type2 type1)) type2)
2606         ((and (not (union-type-p type1))
2607               (union-complex-subtypep-arg2 type1 type2))
2608          type1)
2609         ((and (not (union-type-p type1))
2610               (union-complex-subtypep-arg1 type2 type1))
2611          type2)
2612         (t 
2613          ;; KLUDGE: This code accumulates a sequence of TYPE-UNION2
2614          ;; operations in a particular order, and gives up if any of
2615          ;; the sub-unions turn out not to be simple. In other cases
2616          ;; ca. sbcl-0.6.11.15, that approach to taking a union was a
2617          ;; bad idea, since it can overlook simplifications which
2618          ;; might occur if the terms were accumulated in a different
2619          ;; order. It's possible that that will be a problem here too.
2620          ;; However, I can't think of a good example to demonstrate
2621          ;; it, and without an example to demonstrate it I can't write
2622          ;; test cases, and without test cases I don't want to
2623          ;; complicate the code to address what's still a hypothetical
2624          ;; problem. So I punted. -- WHN 2001-03-20
2625          (let ((accumulator *empty-type*))
2626            (dolist (t2 (union-type-types type2) accumulator)
2627              (setf accumulator
2628                    (type-union accumulator
2629                                (type-intersection type1 t2))))))))
2630
2631 (!def-type-translator or (&rest type-specifiers)
2632   (apply #'type-union
2633          (mapcar #'specifier-type
2634                  type-specifiers)))
2635 \f
2636 ;;;; CONS types
2637
2638 (!define-type-class cons)
2639
2640 (!def-type-translator cons (&optional (car-type-spec '*) (cdr-type-spec '*))
2641   (let ((car-type (specifier-type car-type-spec))
2642         (cdr-type (specifier-type cdr-type-spec)))
2643     (make-cons-type car-type cdr-type)))
2644  
2645 (!define-type-method (cons :unparse) (type)
2646   (let ((car-eltype (type-specifier (cons-type-car-type type)))
2647         (cdr-eltype (type-specifier (cons-type-cdr-type type))))
2648     (if (and (member car-eltype '(t *))
2649              (member cdr-eltype '(t *)))
2650         'cons
2651         `(cons ,car-eltype ,cdr-eltype))))
2652  
2653 (!define-type-method (cons :simple-=) (type1 type2)
2654   (declare (type cons-type type1 type2))
2655   (and (type= (cons-type-car-type type1) (cons-type-car-type type2))
2656        (type= (cons-type-cdr-type type1) (cons-type-cdr-type type2))))
2657  
2658 (!define-type-method (cons :simple-subtypep) (type1 type2)
2659   (declare (type cons-type type1 type2))
2660   (multiple-value-bind (val-car win-car)
2661       (csubtypep (cons-type-car-type type1) (cons-type-car-type type2))
2662     (multiple-value-bind (val-cdr win-cdr)
2663         (csubtypep (cons-type-cdr-type type1) (cons-type-cdr-type type2))
2664       (if (and val-car val-cdr)
2665           (values t (and win-car win-cdr))
2666           (values nil (or win-car win-cdr))))))
2667  
2668 ;;; Give up if a precise type is not possible, to avoid returning
2669 ;;; overly general types.
2670 (!define-type-method (cons :simple-union2) (type1 type2)
2671   (declare (type cons-type type1 type2))
2672   (let ((car-type1 (cons-type-car-type type1))
2673         (car-type2 (cons-type-car-type type2))
2674         (cdr-type1 (cons-type-cdr-type type1))
2675         (cdr-type2 (cons-type-cdr-type type2)))
2676     ;; UGH.  -- CSR, 2003-02-24
2677     (macrolet ((frob-car (car1 car2 cdr1 cdr2)
2678                  `(type-union
2679                    (make-cons-type ,car1 (type-union ,cdr1 ,cdr2))
2680                    (make-cons-type
2681                     (type-intersection ,car2
2682                      (specifier-type
2683                       `(not ,(type-specifier ,car1))))
2684                     ,cdr2))))
2685       (cond ((type= car-type1 car-type2)
2686              (make-cons-type car-type1
2687                              (type-union cdr-type1 cdr-type2)))
2688             ((type= cdr-type1 cdr-type2)
2689              (make-cons-type (type-union car-type1 car-type2)
2690                              cdr-type1))
2691             ((csubtypep car-type1 car-type2)
2692              (frob-car car-type1 car-type2 cdr-type1 cdr-type2))
2693             ((csubtypep car-type2 car-type1)
2694              (frob-car car-type2 car-type1 cdr-type2 cdr-type1))
2695             ;; Don't put these in -- consider the effect of taking the
2696             ;; union of (CONS (INTEGER 0 2) (INTEGER 5 7)) and
2697             ;; (CONS (INTEGER 0 3) (INTEGER 5 6)).
2698             #+nil
2699             ((csubtypep cdr-type1 cdr-type2)
2700              (frob-cdr car-type1 car-type2 cdr-type1 cdr-type2))
2701             #+nil
2702             ((csubtypep cdr-type2 cdr-type1)
2703              (frob-cdr car-type2 car-type1 cdr-type2 cdr-type1))))))
2704             
2705 (!define-type-method (cons :simple-intersection2) (type1 type2)
2706   (declare (type cons-type type1 type2))
2707   (let (car-int2
2708         cdr-int2)
2709     (and (setf car-int2 (type-intersection2 (cons-type-car-type type1)
2710                                             (cons-type-car-type type2)))
2711          (setf cdr-int2 (type-intersection2 (cons-type-cdr-type type1)
2712                                             (cons-type-cdr-type type2)))
2713          (make-cons-type car-int2 cdr-int2))))
2714 \f
2715 ;;; Return the type that describes all objects that are in X but not
2716 ;;; in Y. If we can't determine this type, then return NIL.
2717 ;;;
2718 ;;; For now, we only are clever dealing with union and member types.
2719 ;;; If either type is not a union type, then we pretend that it is a
2720 ;;; union of just one type. What we do is remove from X all the types
2721 ;;; that are a subtype any type in Y. If any type in X intersects with
2722 ;;; a type in Y but is not a subtype, then we give up.
2723 ;;;
2724 ;;; We must also special-case any member type that appears in the
2725 ;;; union. We remove from X's members all objects that are TYPEP to Y.
2726 ;;; If Y has any members, we must be careful that none of those
2727 ;;; members are CTYPEP to any of Y's non-member types. We give up in
2728 ;;; this case, since to compute that difference we would have to break
2729 ;;; the type from X into some collection of types that represents the
2730 ;;; type without that particular element. This seems too hairy to be
2731 ;;; worthwhile, given its low utility.
2732 (defun type-difference (x y)
2733   (let ((x-types (if (union-type-p x) (union-type-types x) (list x)))
2734         (y-types (if (union-type-p y) (union-type-types y) (list y))))
2735     (collect ((res))
2736       (dolist (x-type x-types)
2737         (if (member-type-p x-type)
2738             (collect ((members))
2739               (dolist (mem (member-type-members x-type))
2740                 (multiple-value-bind (val win) (ctypep mem y)
2741                   (unless win (return-from type-difference nil))
2742                   (unless val
2743                     (members mem))))
2744               (when (members)
2745                 (res (make-member-type :members (members)))))
2746             (dolist (y-type y-types (res x-type))
2747               (multiple-value-bind (val win) (csubtypep x-type y-type)
2748                 (unless win (return-from type-difference nil))
2749                 (when val (return))
2750                 (when (types-equal-or-intersect x-type y-type)
2751                   (return-from type-difference nil))))))
2752       (let ((y-mem (find-if #'member-type-p y-types)))
2753         (when y-mem
2754           (let ((members (member-type-members y-mem)))
2755             (dolist (x-type x-types)
2756               (unless (member-type-p x-type)
2757                 (dolist (member members)
2758                   (multiple-value-bind (val win) (ctypep member x-type)
2759                     (when (or (not win) val)
2760                       (return-from type-difference nil)))))))))
2761       (apply #'type-union (res)))))
2762 \f
2763 (!def-type-translator array (&optional (element-type '*)
2764                                        (dimensions '*))
2765   (specialize-array-type
2766    (make-array-type :dimensions (canonical-array-dimensions dimensions)
2767                     :complexp :maybe
2768                     :element-type (specifier-type element-type))))
2769
2770 (!def-type-translator simple-array (&optional (element-type '*)
2771                                               (dimensions '*))
2772   (specialize-array-type
2773    (make-array-type :dimensions (canonical-array-dimensions dimensions)
2774                     :complexp nil
2775                     :element-type (specifier-type element-type))))
2776 \f
2777 ;;;; utilities shared between cross-compiler and target system
2778
2779 ;;; Does the type derived from compilation of an actual function
2780 ;;; definition satisfy declarations of a function's type?
2781 (defun defined-ftype-matches-declared-ftype-p (defined-ftype declared-ftype)
2782   (declare (type ctype defined-ftype declared-ftype))
2783   (flet ((is-built-in-class-function-p (ctype)
2784            (and (built-in-classoid-p ctype)
2785                 (eq (built-in-classoid-name ctype) 'function))))
2786     (cond (;; DECLARED-FTYPE could certainly be #<BUILT-IN-CLASS FUNCTION>;
2787            ;; that's what happens when we (DECLAIM (FTYPE FUNCTION FOO)).
2788            (is-built-in-class-function-p declared-ftype)
2789            ;; In that case, any definition satisfies the declaration.
2790            t)
2791           (;; It's not clear whether or how DEFINED-FTYPE might be
2792            ;; #<BUILT-IN-CLASS FUNCTION>, but it's not obviously
2793            ;; invalid, so let's handle that case too, just in case.
2794            (is-built-in-class-function-p defined-ftype)
2795            ;; No matter what DECLARED-FTYPE might be, we can't prove
2796            ;; that an object of type FUNCTION doesn't satisfy it, so
2797            ;; we return success no matter what.
2798            t)
2799           (;; Otherwise both of them must be FUN-TYPE objects.
2800            t
2801            ;; FIXME: For now we only check compatibility of the return
2802            ;; type, not argument types, and we don't even check the
2803            ;; return type very precisely (as per bug 94a). It would be
2804            ;; good to do a better job. Perhaps to check the
2805            ;; compatibility of the arguments, we should (1) redo
2806            ;; VALUES-TYPES-EQUAL-OR-INTERSECT as
2807            ;; ARGS-TYPES-EQUAL-OR-INTERSECT, and then (2) apply it to
2808            ;; the ARGS-TYPE slices of the FUN-TYPEs. (ARGS-TYPE
2809            ;; is a base class both of VALUES-TYPE and of FUN-TYPE.)
2810            (values-types-equal-or-intersect
2811             (fun-type-returns defined-ftype)
2812             (fun-type-returns declared-ftype))))))
2813            
2814 ;;; This messy case of CTYPE for NUMBER is shared between the
2815 ;;; cross-compiler and the target system.
2816 (defun ctype-of-number (x)
2817   (let ((num (if (complexp x) (realpart x) x)))
2818     (multiple-value-bind (complexp low high)
2819         (if (complexp x)
2820             (let ((imag (imagpart x)))
2821               (values :complex (min num imag) (max num imag)))
2822             (values :real num num))
2823       (make-numeric-type :class (etypecase num
2824                                   (integer 'integer)
2825                                   (rational 'rational)
2826                                   (float 'float))
2827                          :format (and (floatp num) (float-format-name num))
2828                          :complexp complexp
2829                          :low low
2830                          :high high))))
2831 \f
2832 (locally
2833   ;; Why SAFETY 0? To suppress the is-it-the-right-structure-type
2834   ;; checking for declarations in structure accessors. Otherwise we
2835   ;; can get caught in a chicken-and-egg bootstrapping problem, whose
2836   ;; symptom on x86 OpenBSD sbcl-0.pre7.37.flaky5.22 is an illegal
2837   ;; instruction trap. I haven't tracked it down, but I'm guessing it
2838   ;; has to do with setting LAYOUTs when the LAYOUT hasn't been set
2839   ;; yet. -- WHN
2840   (declare (optimize (safety 0)))
2841   (!defun-from-collected-cold-init-forms !late-type-cold-init))
2842
2843 (/show0 "late-type.lisp end of file")