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