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