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