0.8.3.2:
[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                                         :values 2
631                                         :default (values nil :empty)
632                                         :init-wrapper !cold-init-forms)
633     ((type1 eq) (type2 eq))
634   (declare (type ctype type1 type2))
635   (cond ((eq type1 *wild-type*) (values (coerce-to-values type2) t))
636         ((or (eq type2 *wild-type*) (eq type2 *universal-type*))
637          (values type1 t))
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-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          (multiple-value-bind (res win) (values-type-intersection type1 type2)
664            (values (not (eq res *empty-type*))
665                    win)))))
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 vector 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 (declaim (inline simplified-compound-types))
935 (defun simplified-compound-types (input-types %compound-type-p simplify2)
936   (declare (function %compound-type-p simplify2))
937   (let ((types (make-array (length input-types)
938                            :fill-pointer 0
939                            :adjustable t
940                            :element-type 'ctype)))
941     (labels ((accumulate-compound-type (type)
942                (if (funcall %compound-type-p type)
943                    (dolist (type (compound-type-types type))
944                      (accumulate1-compound-type type))
945                    (accumulate1-compound-type type)))
946              (accumulate1-compound-type (type)
947                (declare (type ctype type))
948                ;; Any input object satisfying %COMPOUND-TYPE-P should've been
949                ;; broken into components before it reached us.
950                (aver (not (funcall %compound-type-p type)))
951                (dotimes (i (length types) (vector-push-extend type types))
952                  (let ((simplified2 (funcall simplify2 type (aref types i))))
953                    (when simplified2
954                      ;; Discard the old (AREF TYPES I).
955                      (setf (aref types i) (vector-pop types))
956                      ;; Merge the new SIMPLIFIED2 into TYPES, by tail recursing.
957                      ;; (Note that the tail recursion is indirect: we go through
958                      ;; ACCUMULATE, not ACCUMULATE1, so that if SIMPLIFIED2 is
959                      ;; handled properly if it satisfies %COMPOUND-TYPE-P.)
960                      (return (accumulate-compound-type simplified2)))))))
961       (dolist (input-type input-types)
962         (accumulate-compound-type input-type)))
963     types))
964
965 ;;; shared logic for unions and intersections: Make a COMPOUND-TYPE
966 ;;; object whose components are the types in TYPES, or skip to special
967 ;;; cases when TYPES is short.
968 (defun make-probably-compound-type (constructor types enumerable identity)
969   (declare (type function constructor))
970   (declare (type (vector ctype) types))
971   (declare (type ctype identity))
972   (case (length types)
973     (0 identity)
974     (1 (aref types 0))
975     (t (funcall constructor
976                 enumerable
977                 ;; FIXME: This should be just (COERCE TYPES 'LIST), but as
978                 ;; of sbcl-0.6.11.17 the COERCE optimizer is really
979                 ;; brain-dead, so that would generate a full call to
980                 ;; SPECIFIER-TYPE at runtime, so we get into bootstrap
981                 ;; problems in cold init because 'LIST is a compound
982                 ;; type, so we need to MAKE-PROBABLY-COMPOUND-TYPE
983                 ;; before we know what 'LIST is. Once the COERCE
984                 ;; optimizer is less brain-dead, we can make this
985                 ;; (COERCE TYPES 'LIST) again.
986                 #+sb-xc-host (coerce types 'list)
987                 #-sb-xc-host (coerce-to-list types)))))
988
989 (defun maybe-distribute-one-union (union-type types)
990   (let* ((intersection (apply #'type-intersection types))
991          (union (mapcar (lambda (x) (type-intersection x intersection))
992                         (union-type-types union-type))))
993     (if (notany (lambda (x) (or (hairy-type-p x)
994                                 (intersection-type-p x)))
995                 union)
996         union
997         nil)))
998
999 (defun type-intersection (&rest input-types)
1000   (%type-intersection input-types))
1001 (defun-cached (%type-intersection :hash-bits 8
1002                                   :hash-function (lambda (x)
1003                                                    (logand (sxhash x) #xff)))
1004     ((input-types equal))
1005   (let ((simplified-types (simplified-compound-types input-types
1006                                                      #'intersection-type-p
1007                                                      #'type-intersection2)))
1008     (declare (type (vector ctype) simplified-types))
1009     ;; We want to have a canonical representation of types (or failing
1010     ;; that, punt to HAIRY-TYPE). Canonical representation would have
1011     ;; intersections inside unions but not vice versa, since you can
1012     ;; always achieve that by the distributive rule. But we don't want
1013     ;; to just apply the distributive rule, since it would be too easy
1014     ;; to end up with unreasonably huge type expressions. So instead
1015     ;; we try to generate a simple type by distributing the union; if
1016     ;; the type can't be made simple, we punt to HAIRY-TYPE.
1017     (if (and (> (length simplified-types) 1)
1018              (some #'union-type-p simplified-types))
1019         (let* ((first-union (find-if #'union-type-p simplified-types))
1020                (other-types (coerce (remove first-union simplified-types)
1021                                     'list))
1022                (distributed (maybe-distribute-one-union first-union
1023                                                         other-types)))
1024           (if distributed
1025               (apply #'type-union distributed)
1026               (make-hairy-type
1027                :specifier `(and ,@(map 'list
1028                                        #'type-specifier
1029                                        simplified-types)))))
1030         (make-probably-compound-type #'%make-intersection-type
1031                                      simplified-types
1032                                      (some #'type-enumerable
1033                                            simplified-types)
1034                                      *universal-type*))))
1035
1036 (defun type-union (&rest input-types)
1037   (%type-union input-types))
1038 (defun-cached (%type-union :hash-bits 8
1039                            :hash-function (lambda (x)
1040                                             (logand (sxhash x) #xff)))
1041     ((input-types equal))
1042   (let ((simplified-types (simplified-compound-types input-types
1043                                                      #'union-type-p
1044                                                      #'type-union2)))
1045     (make-probably-compound-type #'make-union-type
1046                                  simplified-types
1047                                  (every #'type-enumerable simplified-types)
1048                                  *empty-type*)))
1049 \f
1050 ;;;; built-in types
1051
1052 (!define-type-class named)
1053
1054 (defvar *wild-type*)
1055 (defvar *empty-type*)
1056 (defvar *universal-type*)
1057 (defvar *universal-fun-type*)
1058
1059 (!cold-init-forms
1060  (macrolet ((frob (name var)
1061               `(progn
1062                  (setq ,var (make-named-type :name ',name))
1063                  (setf (info :type :kind ',name)
1064                        #+sb-xc-host :defined #-sb-xc-host :primitive)
1065                  (setf (info :type :builtin ',name) ,var))))
1066    ;; KLUDGE: In ANSI, * isn't really the name of a type, it's just a
1067    ;; special symbol which can be stuck in some places where an
1068    ;; ordinary type can go, e.g. (ARRAY * 1) instead of (ARRAY T 1).
1069    ;; In SBCL it also used to denote universal VALUES type.
1070    (frob * *wild-type*)
1071    (frob nil *empty-type*)
1072    (frob t *universal-type*))
1073  (setf *universal-fun-type*
1074        (make-fun-type :wild-args t
1075                       :returns *wild-type*)))
1076
1077 (!define-type-method (named :simple-=) (type1 type2)
1078   ;;(aver (not (eq type1 *wild-type*))) ; * isn't really a type.
1079   (values (eq type1 type2) t))
1080
1081 (!define-type-method (named :complex-=) (type1 type2)
1082   (cond
1083     ((and (eq type2 *empty-type*)
1084           (intersection-type-p type1)
1085           ;; not allowed to be unsure on these... FIXME: keep the list
1086           ;; of CL types that are intersection types once and only
1087           ;; once.
1088           (not (or (type= type1 (specifier-type 'ratio))
1089                    (type= type1 (specifier-type 'keyword)))))
1090      ;; things like (AND (EQL 0) (SATISFIES ODDP)) or (AND FUNCTION
1091      ;; STREAM) can get here.  In general, we can't really tell
1092      ;; whether these are equal to NIL or not, so
1093      (values nil nil))
1094     ((type-might-contain-other-types-p type1)
1095      (invoke-complex-=-other-method type1 type2))
1096     (t (values nil t))))
1097
1098 (!define-type-method (named :simple-subtypep) (type1 type2)
1099   (aver (not (eq type1 *wild-type*))) ; * isn't really a type.
1100   (values (or (eq type1 *empty-type*) (eq type2 *wild-type*)) t))
1101
1102 (!define-type-method (named :complex-subtypep-arg1) (type1 type2)
1103   ;; This AVER causes problems if we write accurate methods for the
1104   ;; union (and possibly intersection) types which then delegate to
1105   ;; us; while a user shouldn't get here, because of the odd status of
1106   ;; *wild-type* a type-intersection executed by the compiler can. -
1107   ;; CSR, 2002-04-10
1108   ;;
1109   ;; (aver (not (eq type1 *wild-type*))) ; * isn't really a type.
1110   (cond ((eq type1 *empty-type*)
1111          t)
1112         (;; When TYPE2 might be the universal type in disguise
1113          (type-might-contain-other-types-p type2)
1114          ;; Now that the UNION and HAIRY COMPLEX-SUBTYPEP-ARG2 methods
1115          ;; can delegate to us (more or less as CALL-NEXT-METHOD) when
1116          ;; they're uncertain, we can't just barf on COMPOUND-TYPE and
1117          ;; HAIRY-TYPEs as we used to. Instead we deal with the
1118          ;; problem (where at least part of the problem is cases like
1119          ;;   (SUBTYPEP T '(SATISFIES FOO))
1120          ;; or
1121          ;;   (SUBTYPEP T '(AND (SATISFIES FOO) (SATISFIES BAR)))
1122          ;; where the second type is a hairy type like SATISFIES, or
1123          ;; is a compound type which might contain a hairy type) by
1124          ;; returning uncertainty.
1125          (values nil nil))
1126         (t
1127          ;; By elimination, TYPE1 is the universal type.
1128          (aver (eq type1 *universal-type*))
1129          ;; This case would have been picked off by the SIMPLE-SUBTYPEP
1130          ;; method, and so shouldn't appear here.
1131          (aver (not (eq type2 *universal-type*)))
1132          ;; Since TYPE2 is not EQ *UNIVERSAL-TYPE* and is not the
1133          ;; universal type in disguise, TYPE2 is not a superset of TYPE1.
1134          (values nil t))))
1135
1136 (!define-type-method (named :complex-subtypep-arg2) (type1 type2)
1137   (aver (not (eq type2 *wild-type*))) ; * isn't really a type.
1138   (cond ((eq type2 *universal-type*)
1139          (values t t))
1140         ((type-might-contain-other-types-p type1)
1141          ;; those types can be *EMPTY-TYPE* or *UNIVERSAL-TYPE* in
1142          ;; disguise.  So we'd better delegate.
1143          (invoke-complex-subtypep-arg1-method type1 type2))
1144         (t
1145          ;; FIXME: This seems to rely on there only being 2 or 3
1146          ;; NAMED-TYPE values, and the exclusion of various
1147          ;; possibilities above. It would be good to explain it and/or
1148          ;; rewrite it so that it's clearer.
1149          (values (not (eq type2 *empty-type*)) t))))
1150
1151 (!define-type-method (named :complex-intersection2) (type1 type2)
1152   ;; FIXME: This assertion failed when I added it in sbcl-0.6.11.13.
1153   ;; Perhaps when bug 85 is fixed it can be reenabled.
1154   ;;(aver (not (eq type2 *wild-type*))) ; * isn't really a type.
1155   (hierarchical-intersection2 type1 type2))
1156
1157 (!define-type-method (named :complex-union2) (type1 type2)
1158   ;; Perhaps when bug 85 is fixed this can be reenabled.
1159   ;;(aver (not (eq type2 *wild-type*))) ; * isn't really a type.
1160   (hierarchical-union2 type1 type2))
1161
1162 (!define-type-method (named :unparse) (x)
1163   (named-type-name x))
1164 \f
1165 ;;;; hairy and unknown types
1166
1167 (!define-type-method (hairy :unparse) (x)
1168   (hairy-type-specifier x))
1169
1170 (!define-type-method (hairy :simple-subtypep) (type1 type2)
1171   (let ((hairy-spec1 (hairy-type-specifier type1))
1172         (hairy-spec2 (hairy-type-specifier type2)))
1173     (cond ((equal-but-no-car-recursion hairy-spec1 hairy-spec2)
1174            (values t t))
1175           (t
1176            (values nil nil)))))
1177
1178 (!define-type-method (hairy :complex-subtypep-arg2) (type1 type2)
1179   (invoke-complex-subtypep-arg1-method type1 type2))
1180
1181 (!define-type-method (hairy :complex-subtypep-arg1) (type1 type2)
1182   (declare (ignore type1 type2))
1183   (values nil nil))
1184
1185 (!define-type-method (hairy :complex-=) (type1 type2)
1186   (if (and (unknown-type-p type2)
1187            (let* ((specifier2 (unknown-type-specifier type2))
1188                   (name2 (if (consp specifier2)
1189                              (car specifier2)
1190                              specifier2)))
1191              (info :type :kind name2)))
1192       (let ((type2 (specifier-type (unknown-type-specifier type2))))
1193         (if (unknown-type-p type2)
1194             (values nil nil)
1195             (type= type1 type2)))
1196   (values nil nil)))
1197
1198 (!define-type-method (hairy :simple-intersection2 :complex-intersection2) 
1199                      (type1 type2)
1200   (if (type= type1 type2)
1201       type1
1202       nil))
1203
1204 (!define-type-method (hairy :simple-union2) 
1205                      (type1 type2)
1206   (if (type= type1 type2)
1207       type1
1208       nil))
1209
1210 (!define-type-method (hairy :simple-=) (type1 type2)
1211   (if (equal-but-no-car-recursion (hairy-type-specifier type1)
1212                                   (hairy-type-specifier type2))
1213       (values t t)
1214       (values nil nil)))
1215
1216 (!def-type-translator satisfies (&whole whole fun)
1217   (declare (ignore fun))
1218   ;; Check legality of arguments.
1219   (destructuring-bind (satisfies predicate-name) whole
1220     (declare (ignore satisfies))
1221     (unless (symbolp predicate-name)
1222       (error 'simple-type-error
1223              :datum predicate-name
1224              :expected-type 'symbol
1225              :format-control "The SATISFIES predicate name is not a symbol: ~S"
1226              :format-arguments (list predicate-name))))
1227   ;; Create object.
1228   (make-hairy-type :specifier whole))
1229 \f
1230 ;;;; negation types
1231
1232 (!define-type-method (negation :unparse) (x)
1233   `(not ,(type-specifier (negation-type-type x))))
1234
1235 (!define-type-method (negation :simple-subtypep) (type1 type2)
1236   (csubtypep (negation-type-type type2) (negation-type-type type1)))
1237
1238 (!define-type-method (negation :complex-subtypep-arg2) (type1 type2)
1239   (let* ((complement-type2 (negation-type-type type2))
1240          (intersection2 (type-intersection2 type1
1241                                             complement-type2)))
1242     (if intersection2
1243         ;; FIXME: if uncertain, maybe try arg1?
1244         (type= intersection2 *empty-type*)
1245         (invoke-complex-subtypep-arg1-method type1 type2))))
1246
1247 (!define-type-method (negation :complex-subtypep-arg1) (type1 type2)
1248   ;; "Incrementally extended heuristic algorithms tend inexorably toward the
1249   ;; incomprehensible." -- http://www.unlambda.com/~james/lambda/lambda.txt
1250   ;;
1251   ;; You may not believe this. I couldn't either. But then I sat down
1252   ;; and drew lots of Venn diagrams. Comments involving a and b refer
1253   ;; to the call (subtypep '(not a) 'b) -- CSR, 2002-02-27.
1254   (block nil
1255     ;; (Several logical truths in this block are true as long as
1256     ;; b/=T. As of sbcl-0.7.1.28, it seems impossible to construct a
1257     ;; case with b=T where we actually reach this type method, but
1258     ;; we'll test for and exclude this case anyway, since future
1259     ;; maintenance might make it possible for it to end up in this
1260     ;; code.)
1261     (multiple-value-bind (equal certain)
1262         (type= type2 *universal-type*)
1263       (unless certain
1264         (return (values nil nil)))
1265       (when equal
1266         (return (values t t))))
1267     (let ((complement-type1 (negation-type-type type1)))
1268       ;; Do the special cases first, in order to give us a chance if
1269       ;; subtype/supertype relationships are hairy.
1270       (multiple-value-bind (equal certain)
1271           (type= complement-type1 type2)
1272         ;; If a = b, ~a is not a subtype of b (unless b=T, which was
1273         ;; excluded above).
1274         (unless certain
1275           (return (values nil nil)))
1276         (when equal
1277           (return (values nil t))))
1278       ;; KLUDGE: ANSI requires that the SUBTYPEP result between any
1279       ;; two built-in atomic type specifiers never be uncertain. This
1280       ;; is hard to do cleanly for the built-in types whose
1281       ;; definitions include (NOT FOO), i.e. CONS and RATIO. However,
1282       ;; we can do it with this hack, which uses our global knowledge
1283       ;; that our implementation of the type system uses disjoint
1284       ;; implementation types to represent disjoint sets (except when
1285       ;; types are contained in other types).  (This is a KLUDGE
1286       ;; because it's fragile. Various changes in internal
1287       ;; representation in the type system could make it start
1288       ;; confidently returning incorrect results.) -- WHN 2002-03-08
1289       (unless (or (type-might-contain-other-types-p complement-type1)
1290                   (type-might-contain-other-types-p type2))
1291         ;; Because of the way our types which don't contain other
1292         ;; types are disjoint subsets of the space of possible values,
1293         ;; (SUBTYPEP '(NOT AA) 'B)=NIL when AA and B are simple (and B
1294         ;; is not T, as checked above).
1295         (return (values nil t)))
1296       ;; The old (TYPE= TYPE1 TYPE2) branch would never be taken, as
1297       ;; TYPE1 and TYPE2 will only be equal if they're both NOT types,
1298       ;; and then the :SIMPLE-SUBTYPEP method would be used instead.
1299       ;; But a CSUBTYPEP relationship might still hold:
1300       (multiple-value-bind (equal certain)
1301           (csubtypep complement-type1 type2)
1302         ;; If a is a subtype of b, ~a is not a subtype of b (unless
1303         ;; b=T, which was excluded above).
1304         (unless certain
1305           (return (values nil nil)))
1306         (when equal
1307           (return (values nil t))))
1308       (multiple-value-bind (equal certain)
1309           (csubtypep type2 complement-type1)
1310         ;; If b is a subtype of a, ~a is not a subtype of b.  (FIXME:
1311         ;; That's not true if a=T. Do we know at this point that a is
1312         ;; not T?)
1313         (unless certain
1314           (return (values nil nil)))
1315         (when equal
1316           (return (values nil t))))
1317       ;; old CSR comment ca. 0.7.2, now obsoleted by the SIMPLE-CTYPE?
1318       ;; KLUDGE case above: Other cases here would rely on being able
1319       ;; to catch all possible cases, which the fragility of this type
1320       ;; system doesn't inspire me; for instance, if a is type= to ~b,
1321       ;; then we want T, T; if this is not the case and the types are
1322       ;; disjoint (have an intersection of *empty-type*) then we want
1323       ;; NIL, T; else if the union of a and b is the *universal-type*
1324       ;; then we want T, T. So currently we still claim to be unsure
1325       ;; about e.g. (subtypep '(not fixnum) 'single-float).
1326       ;;
1327       ;; OTOH we might still get here:
1328       (values nil nil))))
1329
1330 (!define-type-method (negation :complex-=) (type1 type2)
1331   ;; (NOT FOO) isn't equivalent to anything that's not a negation
1332   ;; type, except possibly a type that might contain it in disguise.
1333   (declare (ignore type2))
1334   (if (type-might-contain-other-types-p type1)
1335       (values nil nil)
1336       (values nil t)))
1337
1338 (!define-type-method (negation :simple-intersection2) (type1 type2)
1339   (let ((not1 (negation-type-type type1))
1340         (not2 (negation-type-type type2)))
1341     (cond
1342       ((csubtypep not1 not2) type2)
1343       ((csubtypep not2 not1) type1)
1344       ;; Why no analagous clause to the disjoint in the SIMPLE-UNION2
1345       ;; method, below?  The clause would read
1346       ;;
1347       ;; ((EQ (TYPE-UNION NOT1 NOT2) *UNIVERSAL-TYPE*) *EMPTY-TYPE*)
1348       ;;
1349       ;; but with proper canonicalization of negation types, there's
1350       ;; no way of constructing two negation types with union of their
1351       ;; negations being the universal type.
1352       (t
1353        (aver (not (eq (type-union not1 not2) *universal-type*)))
1354        nil))))
1355
1356 (!define-type-method (negation :complex-intersection2) (type1 type2)
1357   (cond
1358     ((csubtypep type1 (negation-type-type type2)) *empty-type*)
1359     ((eq (type-intersection type1 (negation-type-type type2)) *empty-type*)
1360      type1)
1361     (t nil)))
1362
1363 (!define-type-method (negation :simple-union2) (type1 type2)
1364   (let ((not1 (negation-type-type type1))
1365         (not2 (negation-type-type type2)))
1366     (cond
1367       ((csubtypep not1 not2) type1)
1368       ((csubtypep not2 not1) type2)
1369       ((eq (type-intersection not1 not2) *empty-type*)
1370        *universal-type*)
1371       (t nil))))
1372
1373 (!define-type-method (negation :complex-union2) (type1 type2)
1374   (cond
1375     ((csubtypep (negation-type-type type2) type1) *universal-type*)
1376     ((eq (type-intersection type1 (negation-type-type type2)) *empty-type*)
1377      type2)
1378     (t nil)))
1379
1380 (!define-type-method (negation :simple-=) (type1 type2)
1381   (type= (negation-type-type type1) (negation-type-type type2)))
1382
1383 (!def-type-translator not (typespec)
1384   (let* ((not-type (specifier-type typespec))
1385          (spec (type-specifier not-type)))
1386     (cond
1387       ;; canonicalize (NOT (NOT FOO))
1388       ((and (listp spec) (eq (car spec) 'not))
1389        (specifier-type (cadr spec)))
1390       ;; canonicalize (NOT NIL) and (NOT T)
1391       ((eq not-type *empty-type*) *universal-type*)
1392       ((eq not-type *universal-type*) *empty-type*)
1393       ((and (numeric-type-p not-type)
1394             (null (numeric-type-low not-type))
1395             (null (numeric-type-high not-type)))
1396        (make-negation-type :type not-type))
1397       ((numeric-type-p not-type)
1398        (type-union
1399         (make-negation-type
1400          :type (modified-numeric-type not-type :low nil :high nil))
1401         (cond
1402           ((null (numeric-type-low not-type))
1403            (modified-numeric-type
1404             not-type
1405             :low (let ((h (numeric-type-high not-type)))
1406                    (if (consp h) (car h) (list h)))
1407             :high nil))
1408           ((null (numeric-type-high not-type))
1409            (modified-numeric-type
1410             not-type
1411             :low nil
1412             :high (let ((l (numeric-type-low not-type)))
1413                     (if (consp l) (car l) (list l)))))
1414           (t (type-union
1415               (modified-numeric-type
1416                not-type
1417                :low nil
1418                :high (let ((l (numeric-type-low not-type)))
1419                        (if (consp l) (car l) (list l))))
1420               (modified-numeric-type
1421                not-type
1422                :low (let ((h (numeric-type-high not-type)))
1423                       (if (consp h) (car h) (list h)))
1424                :high nil))))))
1425       ((intersection-type-p not-type)
1426        (apply #'type-union
1427               (mapcar #'(lambda (x)
1428                           (specifier-type `(not ,(type-specifier x))))
1429                       (intersection-type-types not-type))))
1430       ((union-type-p not-type)
1431        (apply #'type-intersection
1432               (mapcar #'(lambda (x)
1433                           (specifier-type `(not ,(type-specifier x))))
1434                       (union-type-types not-type))))
1435       ((member-type-p not-type)
1436        (let ((members (member-type-members not-type)))
1437          (if (some #'floatp members)
1438              (let (floats)
1439                (dolist (pair `((0.0f0 . ,(load-time-value (make-unportable-float :single-float-negative-zero)))
1440                                (0.0d0 . ,(load-time-value (make-unportable-float :double-float-negative-zero)))
1441                                #!+long-float
1442                                (0.0l0 . ,(load-time-value (make-unportable-float :long-float-negative-zero)))))
1443                  (when (member (car pair) members)
1444                    (aver (not (member (cdr pair) members)))
1445                    (push (cdr pair) floats)
1446                    (setf members (remove (car pair) members)))
1447                  (when (member (cdr pair) members)
1448                    (aver (not (member (car pair) members)))
1449                    (push (car pair) floats)
1450                    (setf members (remove (cdr pair) members))))
1451                (apply #'type-intersection
1452                       (if (null members)
1453                           *universal-type*
1454                           (make-negation-type
1455                            :type (make-member-type :members members)))
1456                       (mapcar
1457                        (lambda (x)
1458                          (let ((type (ctype-of x)))
1459                            (type-union
1460                             (make-negation-type
1461                              :type (modified-numeric-type type
1462                                                           :low nil :high nil))
1463                             (modified-numeric-type type
1464                                                    :low nil :high (list x))
1465                             (make-member-type :members (list x))
1466                             (modified-numeric-type type
1467                                                    :low (list x) :high nil))))
1468                        floats)))
1469              (make-negation-type :type not-type))))
1470       ((and (cons-type-p not-type)
1471             (eq (cons-type-car-type not-type) *universal-type*)
1472             (eq (cons-type-cdr-type not-type) *universal-type*))
1473        (make-negation-type :type not-type))
1474       ((cons-type-p not-type)
1475        (type-union
1476         (make-negation-type :type (specifier-type 'cons))
1477         (cond
1478           ((and (not (eq (cons-type-car-type not-type) *universal-type*))
1479                 (not (eq (cons-type-cdr-type not-type) *universal-type*)))
1480            (type-union
1481             (make-cons-type
1482              (specifier-type `(not ,(type-specifier
1483                                      (cons-type-car-type not-type))))
1484              *universal-type*)
1485             (make-cons-type
1486              *universal-type*
1487              (specifier-type `(not ,(type-specifier
1488                                      (cons-type-cdr-type not-type)))))))
1489           ((not (eq (cons-type-car-type not-type) *universal-type*))
1490            (make-cons-type
1491             (specifier-type `(not ,(type-specifier
1492                                     (cons-type-car-type not-type))))
1493             *universal-type*))
1494           ((not (eq (cons-type-cdr-type not-type) *universal-type*))
1495            (make-cons-type
1496             *universal-type*
1497             (specifier-type `(not ,(type-specifier
1498                                     (cons-type-cdr-type not-type))))))
1499           (t (bug "Weird CONS type ~S" not-type)))))
1500       (t (make-negation-type :type not-type)))))
1501 \f
1502 ;;;; numeric types
1503
1504 (!define-type-class number)
1505
1506 (declaim (inline numeric-type-equal))
1507 (defun numeric-type-equal (type1 type2)
1508   (and (eq (numeric-type-class type1) (numeric-type-class type2))
1509        (eq (numeric-type-format type1) (numeric-type-format type2))
1510        (eq (numeric-type-complexp type1) (numeric-type-complexp type2))))
1511
1512 (!define-type-method (number :simple-=) (type1 type2)
1513   (values
1514    (and (numeric-type-equal type1 type2)
1515         (equalp (numeric-type-low type1) (numeric-type-low type2))
1516         (equalp (numeric-type-high type1) (numeric-type-high type2)))
1517    t))
1518
1519 (!define-type-method (number :unparse) (type)
1520   (let* ((complexp (numeric-type-complexp type))
1521          (low (numeric-type-low type))
1522          (high (numeric-type-high type))
1523          (base (case (numeric-type-class type)
1524                  (integer 'integer)
1525                  (rational 'rational)
1526                  (float (or (numeric-type-format type) 'float))
1527                  (t 'real))))
1528     (let ((base+bounds
1529            (cond ((and (eq base 'integer) high low)
1530                   (let ((high-count (logcount high))
1531                         (high-length (integer-length high)))
1532                     (cond ((= low 0)
1533                            (cond ((= high 0) '(integer 0 0))
1534                                  ((= high 1) 'bit)
1535                                  ((and (= high-count high-length)
1536                                        (plusp high-length))
1537                                   `(unsigned-byte ,high-length))
1538                                  (t
1539                                   `(mod ,(1+ high)))))
1540                           ((and (= low sb!xc:most-negative-fixnum)
1541                                 (= high sb!xc:most-positive-fixnum))
1542                            'fixnum)
1543                           ((and (= low (lognot high))
1544                                 (= high-count high-length)
1545                                 (> high-count 0))
1546                            `(signed-byte ,(1+ high-length)))
1547                           (t
1548                            `(integer ,low ,high)))))
1549                  (high `(,base ,(or low '*) ,high))
1550                  (low
1551                   (if (and (eq base 'integer) (= low 0))
1552                       'unsigned-byte
1553                       `(,base ,low)))
1554                  (t base))))
1555       (ecase complexp
1556         (:real
1557          base+bounds)
1558         (:complex
1559          (if (eq base+bounds 'real)
1560              'complex
1561              `(complex ,base+bounds)))
1562         ((nil)
1563          (aver (eq base+bounds 'real))
1564          'number)))))
1565
1566 ;;; Return true if X is "less than or equal" to Y, taking open bounds
1567 ;;; into consideration. CLOSED is the predicate used to test the bound
1568 ;;; on a closed interval (e.g. <=), and OPEN is the predicate used on
1569 ;;; open bounds (e.g. <). Y is considered to be the outside bound, in
1570 ;;; the sense that if it is infinite (NIL), then the test succeeds,
1571 ;;; whereas if X is infinite, then the test fails (unless Y is also
1572 ;;; infinite).
1573 ;;;
1574 ;;; This is for comparing bounds of the same kind, e.g. upper and
1575 ;;; upper. Use NUMERIC-BOUND-TEST* for different kinds of bounds.
1576 (defmacro numeric-bound-test (x y closed open)
1577   `(cond ((not ,y) t)
1578          ((not ,x) nil)
1579          ((consp ,x)
1580           (if (consp ,y)
1581               (,closed (car ,x) (car ,y))
1582               (,closed (car ,x) ,y)))
1583          (t
1584           (if (consp ,y)
1585               (,open ,x (car ,y))
1586               (,closed ,x ,y)))))
1587
1588 ;;; This is used to compare upper and lower bounds. This is different
1589 ;;; from the same-bound case:
1590 ;;; -- Since X = NIL is -infinity, whereas y = NIL is +infinity, we
1591 ;;;    return true if *either* arg is NIL.
1592 ;;; -- an open inner bound is "greater" and also squeezes the interval,
1593 ;;;    causing us to use the OPEN test for those cases as well.
1594 (defmacro numeric-bound-test* (x y closed open)
1595   `(cond ((not ,y) t)
1596          ((not ,x) t)
1597          ((consp ,x)
1598           (if (consp ,y)
1599               (,open (car ,x) (car ,y))
1600               (,open (car ,x) ,y)))
1601          (t
1602           (if (consp ,y)
1603               (,open ,x (car ,y))
1604               (,closed ,x ,y)))))
1605
1606 ;;; Return whichever of the numeric bounds X and Y is "maximal"
1607 ;;; according to the predicates CLOSED (e.g. >=) and OPEN (e.g. >).
1608 ;;; This is only meaningful for maximizing like bounds, i.e. upper and
1609 ;;; upper. If MAX-P is true, then we return NIL if X or Y is NIL,
1610 ;;; otherwise we return the other arg.
1611 (defmacro numeric-bound-max (x y closed open max-p)
1612   (once-only ((n-x x)
1613               (n-y y))
1614     `(cond ((not ,n-x) ,(if max-p nil n-y))
1615            ((not ,n-y) ,(if max-p nil n-x))
1616            ((consp ,n-x)
1617             (if (consp ,n-y)
1618                 (if (,closed (car ,n-x) (car ,n-y)) ,n-x ,n-y)
1619                 (if (,open (car ,n-x) ,n-y) ,n-x ,n-y)))
1620            (t
1621             (if (consp ,n-y)
1622                 (if (,open (car ,n-y) ,n-x) ,n-y ,n-x)
1623                 (if (,closed ,n-y ,n-x) ,n-y ,n-x))))))
1624
1625 (!define-type-method (number :simple-subtypep) (type1 type2)
1626   (let ((class1 (numeric-type-class type1))
1627         (class2 (numeric-type-class type2))
1628         (complexp2 (numeric-type-complexp type2))
1629         (format2 (numeric-type-format type2))
1630         (low1 (numeric-type-low type1))
1631         (high1 (numeric-type-high type1))
1632         (low2 (numeric-type-low type2))
1633         (high2 (numeric-type-high type2)))
1634     ;; If one is complex and the other isn't, they are disjoint.
1635     (cond ((not (or (eq (numeric-type-complexp type1) complexp2)
1636                     (null complexp2)))
1637            (values nil t))
1638           ;; If the classes are specified and different, the types are
1639           ;; disjoint unless type2 is RATIONAL and type1 is INTEGER.
1640           ;; [ or type1 is INTEGER and type2 is of the form (RATIONAL
1641           ;; X X) for integral X, but this is dealt with in the
1642           ;; canonicalization inside MAKE-NUMERIC-TYPE ]
1643           ((not (or (eq class1 class2)
1644                     (null class2)
1645                     (and (eq class1 'integer) (eq class2 'rational))))
1646            (values nil t))
1647           ;; If the float formats are specified and different, the types
1648           ;; are disjoint.
1649           ((not (or (eq (numeric-type-format type1) format2)
1650                     (null format2)))
1651            (values nil t))
1652           ;; Check the bounds.
1653           ((and (numeric-bound-test low1 low2 >= >)
1654                 (numeric-bound-test high1 high2 <= <))
1655            (values t t))
1656           (t
1657            (values nil t)))))
1658
1659 (!define-superclasses number ((number)) !cold-init-forms)
1660
1661 ;;; If the high bound of LOW is adjacent to the low bound of HIGH,
1662 ;;; then return true, otherwise NIL.
1663 (defun numeric-types-adjacent (low high)
1664   (let ((low-bound (numeric-type-high low))
1665         (high-bound (numeric-type-low high)))
1666     (cond ((not (and low-bound high-bound)) nil)
1667           ((and (consp low-bound) (consp high-bound)) nil)
1668           ((consp low-bound)
1669            (let ((low-value (car low-bound)))
1670              (or (eql low-value high-bound)
1671                  (and (eql low-value
1672                            (load-time-value (make-unportable-float
1673                                              :single-float-negative-zero)))
1674                       (eql high-bound 0f0))
1675                  (and (eql low-value 0f0)
1676                       (eql high-bound
1677                            (load-time-value (make-unportable-float
1678                                              :single-float-negative-zero))))
1679                  (and (eql low-value
1680                            (load-time-value (make-unportable-float
1681                                              :double-float-negative-zero)))
1682                       (eql high-bound 0d0))
1683                  (and (eql low-value 0d0)
1684                       (eql high-bound
1685                            (load-time-value (make-unportable-float
1686                                              :double-float-negative-zero)))))))
1687           ((consp high-bound)
1688            (let ((high-value (car high-bound)))
1689              (or (eql high-value low-bound)
1690                  (and (eql high-value
1691                            (load-time-value (make-unportable-float
1692                                              :single-float-negative-zero)))
1693                       (eql low-bound 0f0))
1694                  (and (eql high-value 0f0)
1695                       (eql low-bound
1696                            (load-time-value (make-unportable-float
1697                                              :single-float-negative-zero))))
1698                  (and (eql high-value
1699                            (load-time-value (make-unportable-float
1700                                              :double-float-negative-zero)))
1701                       (eql low-bound 0d0))
1702                  (and (eql high-value 0d0)
1703                       (eql low-bound
1704                            (load-time-value (make-unportable-float
1705                                              :double-float-negative-zero)))))))
1706           ((and (eq (numeric-type-class low) 'integer)
1707                 (eq (numeric-type-class high) 'integer))
1708            (eql (1+ low-bound) high-bound))
1709           (t
1710            nil))))
1711
1712 ;;; Return a numeric type that is a supertype for both TYPE1 and TYPE2.
1713 ;;;
1714 ;;; Old comment, probably no longer applicable:
1715 ;;;
1716 ;;;   ### Note: we give up early to keep from dropping lots of
1717 ;;;   information on the floor by returning overly general types.
1718 (!define-type-method (number :simple-union2) (type1 type2)
1719   (declare (type numeric-type type1 type2))
1720   (cond ((csubtypep type1 type2) type2)
1721         ((csubtypep type2 type1) type1)
1722         (t
1723          (let ((class1 (numeric-type-class type1))
1724                (format1 (numeric-type-format type1))
1725                (complexp1 (numeric-type-complexp type1))
1726                (class2 (numeric-type-class type2))
1727                (format2 (numeric-type-format type2))
1728                (complexp2 (numeric-type-complexp type2)))
1729            (cond
1730              ((and (eq class1 class2)
1731                    (eq format1 format2)
1732                    (eq complexp1 complexp2)
1733                    (or (numeric-types-intersect type1 type2)
1734                        (numeric-types-adjacent type1 type2)
1735                        (numeric-types-adjacent type2 type1)))
1736               (make-numeric-type
1737                :class class1
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              ;; FIXME: These two clauses are almost identical, and the
1747              ;; consequents are in fact identical in every respect.
1748              ((and (eq class1 'rational)
1749                    (eq class2 'integer)
1750                    (eq format1 format2)
1751                    (eq complexp1 complexp2)
1752                    (integerp (numeric-type-low type2))
1753                    (integerp (numeric-type-high type2))
1754                    (= (numeric-type-low type2) (numeric-type-high type2))
1755                    (or (numeric-types-adjacent type1 type2)
1756                        (numeric-types-adjacent type2 type1)))
1757               (make-numeric-type
1758                :class 'rational
1759                :format format1
1760                :complexp complexp1
1761                :low (numeric-bound-max (numeric-type-low type1)
1762                                        (numeric-type-low type2)
1763                                        <= < t)
1764                :high (numeric-bound-max (numeric-type-high type1)
1765                                         (numeric-type-high type2)
1766                                         >= > t)))
1767              ((and (eq class1 'integer)
1768                    (eq class2 'rational)
1769                    (eq format1 format2)
1770                    (eq complexp1 complexp2)
1771                    (integerp (numeric-type-low type1))
1772                    (integerp (numeric-type-high type1))
1773                    (= (numeric-type-low type1) (numeric-type-high type1))
1774                    (or (numeric-types-adjacent type1 type2)
1775                        (numeric-types-adjacent type2 type1)))
1776               (make-numeric-type
1777                :class 'rational
1778                :format format1
1779                :complexp complexp1
1780                :low (numeric-bound-max (numeric-type-low type1)
1781                                        (numeric-type-low type2)
1782                                        <= < t)
1783                :high (numeric-bound-max (numeric-type-high type1)
1784                                         (numeric-type-high type2)
1785                                         >= > t)))
1786              (t nil))))))
1787
1788
1789 (!cold-init-forms
1790   (setf (info :type :kind 'number)
1791         #+sb-xc-host :defined #-sb-xc-host :primitive)
1792   (setf (info :type :builtin 'number)
1793         (make-numeric-type :complexp nil)))
1794
1795 (!def-type-translator complex (&optional (typespec '*))
1796   (if (eq typespec '*)
1797       (make-numeric-type :complexp :complex)
1798       (labels ((not-numeric ()
1799                  (error "The component type for COMPLEX is not numeric: ~S"
1800                         typespec))
1801                (not-real ()
1802                  (error "The component type for COMPLEX is not real: ~S"
1803                         typespec))
1804                (complex1 (component-type)
1805                  (unless (numeric-type-p component-type)
1806                    (not-numeric))
1807                  (when (eq (numeric-type-complexp component-type) :complex)
1808                    (not-real))
1809                  (modified-numeric-type component-type :complexp :complex))
1810                (complex-union (component)
1811                  (unless (numberp component)
1812                    (not-numeric))
1813                  ;; KLUDGE: This TYPECASE more or less does
1814                  ;; (UPGRADED-COMPLEX-PART-TYPE (TYPE-OF COMPONENT)),
1815                  ;; (plus a small hack to treat (EQL COMPONENT 0) specially)
1816                  ;; but uses logic cut and pasted from the DEFUN of
1817                  ;; UPGRADED-COMPLEX-PART-TYPE. That's fragile, because
1818                  ;; changing the definition of UPGRADED-COMPLEX-PART-TYPE
1819                  ;; would tend to break the code here. Unfortunately,
1820                  ;; though, reusing UPGRADED-COMPLEX-PART-TYPE here
1821                  ;; would cause another kind of fragility, because
1822                  ;; ANSI's definition of TYPE-OF is so weak that e.g.
1823                  ;; (UPGRADED-COMPLEX-PART-TYPE (TYPE-OF 1/2)) could
1824                  ;; end up being (UPGRADED-COMPLEX-PART-TYPE 'REAL)
1825                  ;; instead of (UPGRADED-COMPLEX-PART-TYPE 'RATIONAL).
1826                  ;; So using TYPE-OF would mean that ANSI-conforming
1827                  ;; maintenance changes in TYPE-OF could break the code here.
1828                  ;; It's not clear how best to fix this. -- WHN 2002-01-21,
1829                  ;; trying to summarize CSR's concerns in his patch
1830                  (typecase component
1831                    (complex (error "The component type for COMPLEX (EQL X) ~
1832                                     is complex: ~S"
1833                                    component))
1834                    ((eql 0) (specifier-type nil)) ; as required by ANSI
1835                    (single-float (specifier-type '(complex single-float)))
1836                    (double-float (specifier-type '(complex double-float)))
1837                    #!+long-float
1838                    (long-float (specifier-type '(complex long-float)))
1839                    (rational (specifier-type '(complex rational)))
1840                    (t (specifier-type '(complex real))))))
1841         (let ((ctype (specifier-type typespec)))
1842           (typecase ctype
1843             (numeric-type (complex1 ctype))
1844             (union-type (apply #'type-union
1845                                ;; FIXME: This code could suffer from
1846                                ;; (admittedly very obscure) cases of
1847                                ;; bug 145 e.g. when TYPE is
1848                                ;;   (OR (AND INTEGER (SATISFIES ODDP))
1849                                ;;       (AND FLOAT (SATISFIES FOO))
1850                                ;; and not even report the problem very well.
1851                                (mapcar #'complex1
1852                                        (union-type-types ctype))))
1853             ;; MEMBER-TYPE is almost the same as UNION-TYPE, but
1854             ;; there's a gotcha: (COMPLEX (EQL 0)) is, according to
1855             ;; ANSI, equal to type NIL, the empty set.
1856             (member-type (apply #'type-union
1857                                 (mapcar #'complex-union
1858                                         (member-type-members ctype))))
1859             (t
1860              (multiple-value-bind (subtypep certainly)
1861                  (csubtypep ctype (specifier-type 'real))
1862                (if (and (not subtypep) certainly)
1863                    (not-real)
1864                    ;; ANSI just says that TYPESPEC is any subtype of
1865                    ;; type REAL, not necessarily a NUMERIC-TYPE. In
1866                    ;; particular, at this point TYPESPEC could legally be
1867                    ;; an intersection type like (AND REAL (SATISFIES ODDP)),
1868                    ;; in which case we fall through the logic above and
1869                    ;; end up here, stumped.
1870                    (bug "~@<(known bug #145): The type ~S is too hairy to be 
1871                          used for a COMPLEX component.~:@>"
1872                         typespec)))))))))
1873
1874 ;;; If X is *, return NIL, otherwise return the bound, which must be a
1875 ;;; member of TYPE or a one-element list of a member of TYPE.
1876 #!-sb-fluid (declaim (inline canonicalized-bound))
1877 (defun canonicalized-bound (bound type)
1878   (cond ((eq bound '*) nil)
1879         ((or (sb!xc:typep bound type)
1880              (and (consp bound)
1881                   (sb!xc:typep (car bound) type)
1882                   (null (cdr bound))))
1883           bound)
1884         (t
1885          (error "Bound is not ~S, a ~S or a list of a ~S: ~S"
1886                 '*
1887                 type
1888                 type
1889                 bound))))
1890
1891 (!def-type-translator integer (&optional (low '*) (high '*))
1892   (let* ((l (canonicalized-bound low 'integer))
1893          (lb (if (consp l) (1+ (car l)) l))
1894          (h (canonicalized-bound high 'integer))
1895          (hb (if (consp h) (1- (car h)) h)))
1896     (if (and hb lb (< hb lb))
1897         *empty-type*
1898       (make-numeric-type :class 'integer
1899                          :complexp :real
1900                          :enumerable (not (null (and l h)))
1901                          :low lb
1902                          :high hb))))
1903
1904 (defmacro !def-bounded-type (type class format)
1905   `(!def-type-translator ,type (&optional (low '*) (high '*))
1906      (let ((lb (canonicalized-bound low ',type))
1907            (hb (canonicalized-bound high ',type)))
1908        (if (not (numeric-bound-test* lb hb <= <))
1909            *empty-type*
1910          (make-numeric-type :class ',class
1911                             :format ',format
1912                             :low lb
1913                             :high hb)))))
1914
1915 (!def-bounded-type rational rational nil)
1916
1917 ;;; Unlike CMU CL, we represent the types FLOAT and REAL as
1918 ;;; UNION-TYPEs of more primitive types, in order to make
1919 ;;; type representation more unique, avoiding problems in the
1920 ;;; simplification of things like
1921 ;;;   (subtypep '(or (single-float -1.0 1.0) (single-float 0.1))
1922 ;;;             '(or (real -1 7) (single-float 0.1) (single-float -1.0 1.0)))
1923 ;;; When we allowed REAL to remain as a separate NUMERIC-TYPE,
1924 ;;; it was too easy for the first argument to be simplified to
1925 ;;; '(SINGLE-FLOAT -1.0), and for the second argument to be simplified
1926 ;;; to '(OR (REAL -1 7) (SINGLE-FLOAT 0.1)) and then for the
1927 ;;; SUBTYPEP to fail (returning NIL,T instead of T,T) because
1928 ;;; the first argument can't be seen to be a subtype of any of the
1929 ;;; terms in the second argument.
1930 ;;;
1931 ;;; The old CMU CL way was:
1932 ;;;   (!def-bounded-type float float nil)
1933 ;;;   (!def-bounded-type real nil nil)
1934 ;;;
1935 ;;; FIXME: If this new way works for a while with no weird new
1936 ;;; problems, we can go back and rip out support for separate FLOAT
1937 ;;; and REAL flavors of NUMERIC-TYPE. The new way was added in
1938 ;;; sbcl-0.6.11.22, 2001-03-21.
1939 ;;;
1940 ;;; FIXME: It's probably necessary to do something to fix the
1941 ;;; analogous problem with INTEGER and RATIONAL types. Perhaps
1942 ;;; bounded RATIONAL types should be represented as (OR RATIO INTEGER).
1943 (defun coerce-bound (bound type inner-coerce-bound-fun)
1944   (declare (type function inner-coerce-bound-fun))
1945   (cond ((eql bound '*)
1946          bound)
1947         ((consp bound)
1948          (destructuring-bind (inner-bound) bound
1949            (list (funcall inner-coerce-bound-fun inner-bound type))))
1950         (t
1951          (funcall inner-coerce-bound-fun bound type))))
1952 (defun inner-coerce-real-bound (bound type)
1953   (ecase type
1954     (rational (rationalize bound))
1955     (float (if (floatp bound)
1956                bound
1957                ;; Coerce to the widest float format available, to
1958                ;; avoid unnecessary loss of precision:
1959                (coerce bound 'long-float)))))
1960 (defun coerced-real-bound (bound type)
1961   (coerce-bound bound type #'inner-coerce-real-bound))
1962 (defun coerced-float-bound (bound type)
1963   (coerce-bound bound type #'coerce))
1964 (!def-type-translator real (&optional (low '*) (high '*))
1965   (specifier-type `(or (float ,(coerced-real-bound  low 'float)
1966                               ,(coerced-real-bound high 'float))
1967                        (rational ,(coerced-real-bound  low 'rational)
1968                                  ,(coerced-real-bound high 'rational)))))
1969 (!def-type-translator float (&optional (low '*) (high '*))
1970   (specifier-type 
1971    `(or (single-float ,(coerced-float-bound  low 'single-float)
1972                       ,(coerced-float-bound high 'single-float))
1973         (double-float ,(coerced-float-bound  low 'double-float)
1974                       ,(coerced-float-bound high 'double-float))
1975         #!+long-float ,(error "stub: no long float support yet"))))
1976
1977 (defmacro !define-float-format (f)
1978   `(!def-bounded-type ,f float ,f))
1979
1980 (!define-float-format short-float)
1981 (!define-float-format single-float)
1982 (!define-float-format double-float)
1983 (!define-float-format long-float)
1984
1985 (defun numeric-types-intersect (type1 type2)
1986   (declare (type numeric-type type1 type2))
1987   (let* ((class1 (numeric-type-class type1))
1988          (class2 (numeric-type-class type2))
1989          (complexp1 (numeric-type-complexp type1))
1990          (complexp2 (numeric-type-complexp type2))
1991          (format1 (numeric-type-format type1))
1992          (format2 (numeric-type-format type2))
1993          (low1 (numeric-type-low type1))
1994          (high1 (numeric-type-high type1))
1995          (low2 (numeric-type-low type2))
1996          (high2 (numeric-type-high type2)))
1997     ;; If one is complex and the other isn't, then they are disjoint.
1998     (cond ((not (or (eq complexp1 complexp2)
1999                     (null complexp1) (null complexp2)))
2000            nil)
2001           ;; If either type is a float, then the other must either be
2002           ;; specified to be a float or unspecified. Otherwise, they
2003           ;; are disjoint.
2004           ((and (eq class1 'float)
2005                 (not (member class2 '(float nil)))) nil)
2006           ((and (eq class2 'float)
2007                 (not (member class1 '(float nil)))) nil)
2008           ;; If the float formats are specified and different, the
2009           ;; types are disjoint.
2010           ((not (or (eq format1 format2) (null format1) (null format2)))
2011            nil)
2012           (t
2013            ;; Check the bounds. This is a bit odd because we must
2014            ;; always have the outer bound of the interval as the
2015            ;; second arg.
2016            (if (numeric-bound-test high1 high2 <= <)
2017                (or (and (numeric-bound-test low1 low2 >= >)
2018                         (numeric-bound-test* low1 high2 <= <))
2019                    (and (numeric-bound-test low2 low1 >= >)
2020                         (numeric-bound-test* low2 high1 <= <)))
2021                (or (and (numeric-bound-test* low2 high1 <= <)
2022                         (numeric-bound-test low2 low1 >= >))
2023                    (and (numeric-bound-test high2 high1 <= <)
2024                         (numeric-bound-test* high2 low1 >= >))))))))
2025
2026 ;;; Take the numeric bound X and convert it into something that can be
2027 ;;; used as a bound in a numeric type with the specified CLASS and
2028 ;;; FORMAT. If UP-P is true, then we round up as needed, otherwise we
2029 ;;; round down. UP-P true implies that X is a lower bound, i.e. (N) > N.
2030 ;;;
2031 ;;; This is used by NUMERIC-TYPE-INTERSECTION to mash the bound into
2032 ;;; the appropriate type number. X may only be a float when CLASS is
2033 ;;; FLOAT.
2034 ;;;
2035 ;;; ### Note: it is possible for the coercion to a float to overflow
2036 ;;; or underflow. This happens when the bound doesn't fit in the
2037 ;;; specified format. In this case, we should really return the
2038 ;;; appropriate {Most | Least}-{Positive | Negative}-XXX-Float float
2039 ;;; of desired format. But these conditions aren't currently signalled
2040 ;;; in any useful way.
2041 ;;;
2042 ;;; Also, when converting an open rational bound into a float we
2043 ;;; should probably convert it to a closed bound of the closest float
2044 ;;; in the specified format. KLUDGE: In general, open float bounds are
2045 ;;; screwed up. -- (comment from original CMU CL)
2046 (defun round-numeric-bound (x class format up-p)
2047   (if x
2048       (let ((cx (if (consp x) (car x) x)))
2049         (ecase class
2050           ((nil rational) x)
2051           (integer
2052            (if (and (consp x) (integerp cx))
2053                (if up-p (1+ cx) (1- cx))
2054                (if up-p (ceiling cx) (floor cx))))
2055           (float
2056            (let ((res (if format (coerce cx format) (float cx))))
2057              (if (consp x) (list res) res)))))
2058       nil))
2059
2060 ;;; Handle the case of type intersection on two numeric types. We use
2061 ;;; TYPES-EQUAL-OR-INTERSECT to throw out the case of types with no
2062 ;;; intersection. If an attribute in TYPE1 is unspecified, then we use
2063 ;;; TYPE2's attribute, which must be at least as restrictive. If the
2064 ;;; types intersect, then the only attributes that can be specified
2065 ;;; and different are the class and the bounds.
2066 ;;;
2067 ;;; When the class differs, we use the more restrictive class. The
2068 ;;; only interesting case is RATIONAL/INTEGER, since RATIONAL includes
2069 ;;; INTEGER.
2070 ;;;
2071 ;;; We make the result lower (upper) bound the maximum (minimum) of
2072 ;;; the argument lower (upper) bounds. We convert the bounds into the
2073 ;;; appropriate numeric type before maximizing. This avoids possible
2074 ;;; confusion due to mixed-type comparisons (but I think the result is
2075 ;;; the same).
2076 (!define-type-method (number :simple-intersection2) (type1 type2)
2077   (declare (type numeric-type type1 type2))
2078   (if (numeric-types-intersect type1 type2)
2079       (let* ((class1 (numeric-type-class type1))
2080              (class2 (numeric-type-class type2))
2081              (class (ecase class1
2082                       ((nil) class2)
2083                       ((integer float) class1)
2084                       (rational (if (eq class2 'integer)
2085                                        'integer
2086                                        'rational))))
2087              (format (or (numeric-type-format type1)
2088                          (numeric-type-format type2))))
2089         (make-numeric-type
2090          :class class
2091          :format format
2092          :complexp (or (numeric-type-complexp type1)
2093                        (numeric-type-complexp type2))
2094          :low (numeric-bound-max
2095                (round-numeric-bound (numeric-type-low type1)
2096                                     class format t)
2097                (round-numeric-bound (numeric-type-low type2)
2098                                     class format t)
2099                > >= nil)
2100          :high (numeric-bound-max
2101                 (round-numeric-bound (numeric-type-high type1)
2102                                      class format nil)
2103                 (round-numeric-bound (numeric-type-high type2)
2104                                      class format nil)
2105                 < <= nil)))
2106       *empty-type*))
2107
2108 ;;; Given two float formats, return the one with more precision. If
2109 ;;; either one is null, return NIL.
2110 (defun float-format-max (f1 f2)
2111   (when (and f1 f2)
2112     (dolist (f *float-formats* (error "bad float format: ~S" f1))
2113       (when (or (eq f f1) (eq f f2))
2114         (return f)))))
2115
2116 ;;; Return the result of an operation on TYPE1 and TYPE2 according to
2117 ;;; the rules of numeric contagion. This is always NUMBER, some float
2118 ;;; format (possibly complex) or RATIONAL. Due to rational
2119 ;;; canonicalization, there isn't much we can do here with integers or
2120 ;;; rational complex numbers.
2121 ;;;
2122 ;;; If either argument is not a NUMERIC-TYPE, then return NUMBER. This
2123 ;;; is useful mainly for allowing types that are technically numbers,
2124 ;;; but not a NUMERIC-TYPE.
2125 (defun numeric-contagion (type1 type2)
2126   (if (and (numeric-type-p type1) (numeric-type-p type2))
2127       (let ((class1 (numeric-type-class type1))
2128             (class2 (numeric-type-class type2))
2129             (format1 (numeric-type-format type1))
2130             (format2 (numeric-type-format type2))
2131             (complexp1 (numeric-type-complexp type1))
2132             (complexp2 (numeric-type-complexp type2)))
2133         (cond ((or (null complexp1)
2134                    (null complexp2))
2135                (specifier-type 'number))
2136               ((eq class1 'float)
2137                (make-numeric-type
2138                 :class 'float
2139                 :format (ecase class2
2140                           (float (float-format-max format1 format2))
2141                           ((integer rational) format1)
2142                           ((nil)
2143                            ;; A double-float with any real number is a
2144                            ;; double-float.
2145                            #!-long-float
2146                            (if (eq format1 'double-float)
2147                              'double-float
2148                              nil)
2149                            ;; A long-float with any real number is a
2150                            ;; long-float.
2151                            #!+long-float
2152                            (if (eq format1 'long-float)
2153                              'long-float
2154                              nil)))
2155                 :complexp (if (or (eq complexp1 :complex)
2156                                   (eq complexp2 :complex))
2157                               :complex
2158                               :real)))
2159               ((eq class2 'float) (numeric-contagion type2 type1))
2160               ((and (eq complexp1 :real) (eq complexp2 :real))
2161                (make-numeric-type
2162                 :class (and class1 class2 'rational)
2163                 :complexp :real))
2164               (t
2165                (specifier-type 'number))))
2166       (specifier-type 'number)))
2167 \f
2168 ;;;; array types
2169
2170 (!define-type-class array)
2171
2172 ;;; What this does depends on the setting of the
2173 ;;; *USE-IMPLEMENTATION-TYPES* switch. If true, return the specialized
2174 ;;; element type, otherwise return the original element type.
2175 (defun specialized-element-type-maybe (type)
2176   (declare (type array-type type))
2177   (if *use-implementation-types*
2178       (array-type-specialized-element-type type)
2179       (array-type-element-type type)))
2180
2181 (!define-type-method (array :simple-=) (type1 type2)
2182   (if (or (unknown-type-p (array-type-element-type type1))
2183           (unknown-type-p (array-type-element-type type2)))
2184       (multiple-value-bind (equalp certainp)
2185           (type= (array-type-element-type type1)
2186                  (array-type-element-type type2))
2187         ;; by its nature, the call to TYPE= should never return NIL,
2188         ;; T, as we don't know what the UNKNOWN-TYPE will grow up to
2189         ;; be.  -- CSR, 2002-08-19
2190         (aver (not (and (not equalp) certainp)))
2191         (values equalp certainp))
2192       (values (and (equal (array-type-dimensions type1)
2193                           (array-type-dimensions type2))
2194                    (eq (array-type-complexp type1)
2195                        (array-type-complexp type2))
2196                    (type= (specialized-element-type-maybe type1)
2197                           (specialized-element-type-maybe type2)))
2198               t)))
2199
2200 (!define-type-method (array :unparse) (type)
2201   (let ((dims (array-type-dimensions type))
2202         (eltype (type-specifier (array-type-element-type type)))
2203         (complexp (array-type-complexp type)))
2204     (cond ((eq dims '*)
2205            (if (eq eltype '*)
2206                (if complexp 'array 'simple-array)
2207                (if complexp `(array ,eltype) `(simple-array ,eltype))))
2208           ((= (length dims) 1)
2209            (if complexp
2210                (if (eq (car dims) '*)
2211                    (case eltype
2212                      (bit 'bit-vector)
2213                      (base-char 'base-string)
2214                      (* 'vector)
2215                      (t `(vector ,eltype)))
2216                    (case eltype
2217                      (bit `(bit-vector ,(car dims)))
2218                      (base-char `(base-string ,(car dims)))
2219                      (t `(vector ,eltype ,(car dims)))))
2220                (if (eq (car dims) '*)
2221                    (case eltype
2222                      (bit 'simple-bit-vector)
2223                      (base-char 'simple-base-string)
2224                      ((t) 'simple-vector)
2225                      (t `(simple-array ,eltype (*))))
2226                    (case eltype
2227                      (bit `(simple-bit-vector ,(car dims)))
2228                      (base-char `(simple-base-string ,(car dims)))
2229                      ((t) `(simple-vector ,(car dims)))
2230                      (t `(simple-array ,eltype ,dims))))))
2231           (t
2232            (if complexp
2233                `(array ,eltype ,dims)
2234                `(simple-array ,eltype ,dims))))))
2235
2236 (!define-type-method (array :simple-subtypep) (type1 type2)
2237   (let ((dims1 (array-type-dimensions type1))
2238         (dims2 (array-type-dimensions type2))
2239         (complexp2 (array-type-complexp type2)))
2240     (cond (;; not subtypep unless dimensions are compatible
2241            (not (or (eq dims2 '*)
2242                     (and (not (eq dims1 '*))
2243                          ;; (sbcl-0.6.4 has trouble figuring out that
2244                          ;; DIMS1 and DIMS2 must be lists at this
2245                          ;; point, and knowing that is important to
2246                          ;; compiling EVERY efficiently.)
2247                          (= (length (the list dims1))
2248                             (length (the list dims2)))
2249                          (every (lambda (x y)
2250                                   (or (eq y '*) (eql x y)))
2251                                 (the list dims1)
2252                                 (the list dims2)))))
2253            (values nil t))
2254           ;; not subtypep unless complexness is compatible
2255           ((not (or (eq complexp2 :maybe)
2256                     (eq (array-type-complexp type1) complexp2)))
2257            (values nil t))
2258           ;; Since we didn't fail any of the tests above, we win
2259           ;; if the TYPE2 element type is wild.
2260           ((eq (array-type-element-type type2) *wild-type*)
2261            (values t t))
2262           (;; Since we didn't match any of the special cases above, we
2263            ;; can't give a good answer unless both the element types
2264            ;; have been defined.
2265            (or (unknown-type-p (array-type-element-type type1))
2266                (unknown-type-p (array-type-element-type type2)))
2267            (values nil nil))
2268           (;; Otherwise, the subtype relationship holds iff the
2269            ;; types are equal, and they're equal iff the specialized
2270            ;; element types are identical.
2271            t
2272            (values (type= (specialized-element-type-maybe type1)
2273                           (specialized-element-type-maybe type2))
2274                    t)))))
2275
2276 ;;; FIXME: is this dead?
2277 (!define-superclasses array
2278   ((base-string base-string)
2279    (vector vector)
2280    (array))
2281   !cold-init-forms)
2282
2283 (defun array-types-intersect (type1 type2)
2284   (declare (type array-type type1 type2))
2285   (let ((dims1 (array-type-dimensions type1))
2286         (dims2 (array-type-dimensions type2))
2287         (complexp1 (array-type-complexp type1))
2288         (complexp2 (array-type-complexp type2)))
2289     ;; See whether dimensions are compatible.
2290     (cond ((not (or (eq dims1 '*) (eq dims2 '*)
2291                     (and (= (length dims1) (length dims2))
2292                          (every (lambda (x y)
2293                                   (or (eq x '*) (eq y '*) (= x y)))
2294                                 dims1 dims2))))
2295            (values nil t))
2296           ;; See whether complexpness is compatible.
2297           ((not (or (eq complexp1 :maybe)
2298                     (eq complexp2 :maybe)
2299                     (eq complexp1 complexp2)))
2300            (values nil t))
2301           ;; Old comment:
2302           ;;
2303           ;;   If either element type is wild, then they intersect.
2304           ;;   Otherwise, the types must be identical.
2305           ;;
2306           ;; FIXME: There seems to have been a fair amount of
2307           ;; confusion about the distinction between requested element
2308           ;; type and specialized element type; here is one of
2309           ;; them. If we request an array to hold objects of an
2310           ;; unknown type, we can do no better than represent that
2311           ;; type as an array specialized on wild-type.  We keep the
2312           ;; requested element-type in the -ELEMENT-TYPE slot, and
2313           ;; *WILD-TYPE* in the -SPECIALIZED-ELEMENT-TYPE.  So, here,
2314           ;; we must test for the SPECIALIZED slot being *WILD-TYPE*,
2315           ;; not just the ELEMENT-TYPE slot.  Maybe the return value
2316           ;; in that specific case should be T, NIL?  Or maybe this
2317           ;; function should really be called
2318           ;; ARRAY-TYPES-COULD-POSSIBLY-INTERSECT?  In any case, this
2319           ;; was responsible for bug #123, and this whole issue could
2320           ;; do with a rethink and/or a rewrite.  -- CSR, 2002-08-21
2321           ((or (eq (array-type-specialized-element-type type1) *wild-type*)
2322                (eq (array-type-specialized-element-type type2) *wild-type*)
2323                (type= (specialized-element-type-maybe type1)
2324                       (specialized-element-type-maybe type2)))
2325
2326            (values t t))
2327           (t
2328            (values nil t)))))
2329
2330 (!define-type-method (array :simple-intersection2) (type1 type2)
2331   (declare (type array-type type1 type2))
2332   (if (array-types-intersect type1 type2)
2333       (let ((dims1 (array-type-dimensions type1))
2334             (dims2 (array-type-dimensions type2))
2335             (complexp1 (array-type-complexp type1))
2336             (complexp2 (array-type-complexp type2))
2337             (eltype1 (array-type-element-type type1))
2338             (eltype2 (array-type-element-type type2)))
2339         (specialize-array-type
2340          (make-array-type
2341           :dimensions (cond ((eq dims1 '*) dims2)
2342                             ((eq dims2 '*) dims1)
2343                             (t
2344                              (mapcar (lambda (x y) (if (eq x '*) y x))
2345                                      dims1 dims2)))
2346           :complexp (if (eq complexp1 :maybe) complexp2 complexp1)
2347           :element-type (cond
2348                           ((eq eltype1 *wild-type*) eltype2)
2349                           ((eq eltype2 *wild-type*) eltype1)
2350                           (t (type-intersection eltype1 eltype2))))))
2351       *empty-type*))
2352
2353 ;;; Check a supplied dimension list to determine whether it is legal,
2354 ;;; and return it in canonical form (as either '* or a list).
2355 (defun canonical-array-dimensions (dims)
2356   (typecase dims
2357     ((member *) dims)
2358     (integer
2359      (when (minusp dims)
2360        (error "Arrays can't have a negative number of dimensions: ~S" dims))
2361      (when (>= dims sb!xc:array-rank-limit)
2362        (error "array type with too many dimensions: ~S" dims))
2363      (make-list dims :initial-element '*))
2364     (list
2365      (when (>= (length dims) sb!xc:array-rank-limit)
2366        (error "array type with too many dimensions: ~S" dims))
2367      (dolist (dim dims)
2368        (unless (eq dim '*)
2369          (unless (and (integerp dim)
2370                       (>= dim 0)
2371                       (< dim sb!xc:array-dimension-limit))
2372            (error "bad dimension in array type: ~S" dim))))
2373      dims)
2374     (t
2375      (error "Array dimensions is not a list, integer or *:~%  ~S" dims))))
2376 \f
2377 ;;;; MEMBER types
2378
2379 (!define-type-class member)
2380
2381 (!define-type-method (member :unparse) (type)
2382   (let ((members (member-type-members type)))
2383     (cond
2384       ((equal members '(nil)) 'null)
2385       ((type= type (specifier-type 'standard-char)) 'standard-char)
2386       (t `(member ,@members)))))
2387
2388 (!define-type-method (member :simple-subtypep) (type1 type2)
2389   (values (subsetp (member-type-members type1) (member-type-members type2))
2390           t))
2391
2392 (!define-type-method (member :complex-subtypep-arg1) (type1 type2)
2393   (every/type (swapped-args-fun #'ctypep)
2394               type2
2395               (member-type-members type1)))
2396
2397 ;;; We punt if the odd type is enumerable and intersects with the
2398 ;;; MEMBER type. If not enumerable, then it is definitely not a
2399 ;;; subtype of the MEMBER type.
2400 (!define-type-method (member :complex-subtypep-arg2) (type1 type2)
2401   (cond ((not (type-enumerable type1)) (values nil t))
2402         ((types-equal-or-intersect type1 type2)
2403          (invoke-complex-subtypep-arg1-method type1 type2))
2404         (t (values nil t))))
2405
2406 (!define-type-method (member :simple-intersection2) (type1 type2)
2407   (let ((mem1 (member-type-members type1))
2408         (mem2 (member-type-members type2)))
2409     (cond ((subsetp mem1 mem2) type1)
2410           ((subsetp mem2 mem1) type2)
2411           (t
2412            (let ((res (intersection mem1 mem2)))
2413              (if res
2414                  (make-member-type :members res)
2415                  *empty-type*))))))
2416
2417 (!define-type-method (member :complex-intersection2) (type1 type2)
2418   (block punt
2419     (collect ((members))
2420       (let ((mem2 (member-type-members type2)))
2421         (dolist (member mem2)
2422           (multiple-value-bind (val win) (ctypep member type1)
2423             (unless win
2424               (return-from punt nil))
2425             (when val (members member))))
2426         (cond ((subsetp mem2 (members)) type2)
2427               ((null (members)) *empty-type*)
2428               (t
2429                (make-member-type :members (members))))))))
2430
2431 ;;; We don't need a :COMPLEX-UNION2, since the only interesting case is
2432 ;;; a union type, and the member/union interaction is handled by the
2433 ;;; union type method.
2434 (!define-type-method (member :simple-union2) (type1 type2)
2435   (let ((mem1 (member-type-members type1))
2436         (mem2 (member-type-members type2)))
2437     (cond ((subsetp mem1 mem2) type2)
2438           ((subsetp mem2 mem1) type1)
2439           (t
2440            (make-member-type :members (union mem1 mem2))))))
2441
2442 (!define-type-method (member :simple-=) (type1 type2)
2443   (let ((mem1 (member-type-members type1))
2444         (mem2 (member-type-members type2)))
2445     (values (and (subsetp mem1 mem2)
2446                  (subsetp mem2 mem1))
2447             t)))
2448
2449 (!define-type-method (member :complex-=) (type1 type2)
2450   (if (type-enumerable type1)
2451       (multiple-value-bind (val win) (csubtypep type2 type1)
2452         (if (or val (not win))
2453             (values nil nil)
2454             (values nil t)))
2455       (values nil t)))
2456
2457 (!def-type-translator member (&rest members)
2458   (if members
2459       (let (ms numbers)
2460         (dolist (m (remove-duplicates members))
2461           (typecase m
2462             (float (if (zerop m)
2463                        (push m ms)
2464                        (push (ctype-of m) numbers)))
2465             (number (push (ctype-of m) numbers))
2466             (t (push m ms))))
2467         (apply #'type-union
2468                (if ms
2469                    (make-member-type :members ms)
2470                    *empty-type*)
2471                (nreverse numbers)))
2472       *empty-type*))
2473 \f
2474 ;;;; intersection types
2475 ;;;;
2476 ;;;; Until version 0.6.10.6, SBCL followed the original CMU CL approach
2477 ;;;; of punting on all AND types, not just the unreasonably complicated
2478 ;;;; ones. The change was motivated by trying to get the KEYWORD type
2479 ;;;; to behave sensibly:
2480 ;;;;    ;; reasonable definition
2481 ;;;;    (DEFTYPE KEYWORD () '(AND SYMBOL (SATISFIES KEYWORDP)))
2482 ;;;;    ;; reasonable behavior
2483 ;;;;    (AVER (SUBTYPEP 'KEYWORD 'SYMBOL))
2484 ;;;; Without understanding a little about the semantics of AND, we'd
2485 ;;;; get (SUBTYPEP 'KEYWORD 'SYMBOL)=>NIL,NIL and, for entirely
2486 ;;;; parallel reasons, (SUBTYPEP 'RATIO 'NUMBER)=>NIL,NIL. That's
2487 ;;;; not so good..)
2488 ;;;;
2489 ;;;; We still follow the example of CMU CL to some extent, by punting
2490 ;;;; (to the opaque HAIRY-TYPE) on sufficiently complicated types
2491 ;;;; involving AND.
2492
2493 (!define-type-class intersection)
2494
2495 ;;; A few intersection types have special names. The others just get
2496 ;;; mechanically unparsed.
2497 (!define-type-method (intersection :unparse) (type)
2498   (declare (type ctype type))
2499   (or (find type '(ratio keyword) :key #'specifier-type :test #'type=)
2500       `(and ,@(mapcar #'type-specifier (intersection-type-types type)))))
2501
2502 ;;; shared machinery for type equality: true if every type in the set
2503 ;;; TYPES1 matches a type in the set TYPES2 and vice versa
2504 (defun type=-set (types1 types2)
2505   (flet ((type<=-set (x y)
2506            (declare (type list x y))
2507            (every/type (lambda (x y-element)
2508                          (any/type #'type= y-element x))
2509                        x y)))
2510     (and/type (type<=-set types1 types2)
2511               (type<=-set types2 types1))))
2512
2513 ;;; Two intersection types are equal if their subtypes are equal sets.
2514 ;;;
2515 ;;; FIXME: Might it be better to use
2516 ;;;   (AND (SUBTYPEP X Y) (SUBTYPEP Y X))
2517 ;;; instead, since SUBTYPEP is the usual relationship that we care
2518 ;;; most about, so it would be good to leverage any ingenuity there
2519 ;;; in this more obscure method?
2520 (!define-type-method (intersection :simple-=) (type1 type2)
2521   (type=-set (intersection-type-types type1)
2522              (intersection-type-types type2)))
2523
2524 (defun %intersection-complex-subtypep-arg1 (type1 type2)
2525   (type= type1 (type-intersection type1 type2)))
2526
2527 (defun %intersection-simple-subtypep (type1 type2)
2528   (every/type #'%intersection-complex-subtypep-arg1
2529               type1
2530               (intersection-type-types type2)))
2531
2532 (!define-type-method (intersection :simple-subtypep) (type1 type2)
2533   (%intersection-simple-subtypep type1 type2))
2534   
2535 (!define-type-method (intersection :complex-subtypep-arg1) (type1 type2)
2536   (%intersection-complex-subtypep-arg1 type1 type2))
2537
2538 (defun %intersection-complex-subtypep-arg2 (type1 type2)
2539   (every/type #'csubtypep type1 (intersection-type-types type2)))
2540
2541 (!define-type-method (intersection :complex-subtypep-arg2) (type1 type2)
2542   (%intersection-complex-subtypep-arg2 type1 type2))
2543
2544 ;;; FIXME: This will look eeriely familiar to readers of the UNION
2545 ;;; :SIMPLE-INTERSECTION2 :COMPLEX-INTERSECTION2 method.  That's
2546 ;;; because it was generated by cut'n'paste methods.  Given that
2547 ;;; intersections and unions have all sorts of symmetries known to
2548 ;;; mathematics, it shouldn't be beyond the ken of some programmers to
2549 ;;; reflect those symmetries in code in a way that ties them together
2550 ;;; more strongly than having two independent near-copies :-/
2551 (!define-type-method (intersection :simple-union2 :complex-union2)
2552                      (type1 type2)
2553   ;; Within this method, type2 is guaranteed to be an intersection
2554   ;; type:
2555   (aver (intersection-type-p type2))
2556   ;; Make sure to call only the applicable methods...
2557   (cond ((and (intersection-type-p type1)
2558               (%intersection-simple-subtypep type1 type2)) type2)
2559         ((and (intersection-type-p type1)
2560               (%intersection-simple-subtypep type2 type1)) type1)
2561         ((and (not (intersection-type-p type1))
2562               (%intersection-complex-subtypep-arg2 type1 type2))
2563          type2)
2564         ((and (not (intersection-type-p type1))
2565               (%intersection-complex-subtypep-arg1 type2 type1))
2566          type1)
2567         ;; KLUDGE: This special (and somewhat hairy) magic is required
2568         ;; to deal with the RATIONAL/INTEGER special case.  The UNION
2569         ;; of (INTEGER * -1) and (AND (RATIONAL * -1/2) (NOT INTEGER))
2570         ;; should be (RATIONAL * -1/2) -- CSR, 2003-02-28
2571         ((and (csubtypep type2 (specifier-type 'ratio))
2572               (numeric-type-p type1)
2573               (csubtypep type1 (specifier-type 'integer))
2574               (csubtypep type2
2575                          (make-numeric-type
2576                           :class 'rational
2577                           :complexp nil
2578                           :low (if (null (numeric-type-low type1))
2579                                    nil
2580                                    (list (1- (numeric-type-low type1))))
2581                           :high (if (null (numeric-type-high type1))
2582                                     nil
2583                                     (list (1+ (numeric-type-high type1)))))))
2584          (type-union type1
2585                      (apply #'type-intersection
2586                             (remove (specifier-type '(not integer))
2587                                     (intersection-type-types type2)
2588                                     :test #'type=))))
2589         (t
2590          (let ((accumulator *universal-type*))
2591            (do ((t2s (intersection-type-types type2) (cdr t2s)))
2592                ((null t2s) accumulator)
2593              (let ((union (type-union type1 (car t2s))))
2594                (when (union-type-p union)
2595                  ;; we have to give up here -- there are all sorts of
2596                  ;; ordering worries, but it's better than before.
2597                  ;; Doing exactly the same as in the UNION
2598                  ;; :SIMPLE/:COMPLEX-INTERSECTION2 method causes stack
2599                  ;; overflow with the mutual recursion never bottoming
2600                  ;; out.
2601                  (if (and (eq accumulator *universal-type*)
2602                           (null (cdr t2s)))
2603                      ;; KLUDGE: if we get here, we have a partially
2604                      ;; simplified result.  While this isn't by any
2605                      ;; means a universal simplification, including
2606                      ;; this logic here means that we can get (OR
2607                      ;; KEYWORD (NOT KEYWORD)) canonicalized to T.
2608                      (return union)
2609                      (return nil)))
2610                (setf accumulator
2611                      (type-intersection accumulator union))))))))
2612
2613 (!def-type-translator and (&whole whole &rest type-specifiers)
2614   (apply #'type-intersection
2615          (mapcar #'specifier-type
2616                  type-specifiers)))
2617 \f
2618 ;;;; union types
2619
2620 (!define-type-class union)
2621
2622 ;;; The LIST, FLOAT and REAL types have special names.  Other union
2623 ;;; types just get mechanically unparsed.
2624 (!define-type-method (union :unparse) (type)
2625   (declare (type ctype type))
2626   (cond
2627     ((type= type (specifier-type 'list)) 'list)
2628     ((type= type (specifier-type 'float)) 'float)
2629     ((type= type (specifier-type 'real)) 'real)
2630     ((type= type (specifier-type 'sequence)) 'sequence)
2631     ((type= type (specifier-type 'bignum)) 'bignum)
2632     ((type= type (specifier-type 'simple-string)) 'simple-string)
2633     ((type= type (specifier-type 'string)) 'string)
2634     (t `(or ,@(mapcar #'type-specifier (union-type-types type))))))
2635
2636 ;;; Two union types are equal if they are each subtypes of each
2637 ;;; other. We need to be this clever because our complex subtypep
2638 ;;; methods are now more accurate; we don't get infinite recursion
2639 ;;; because the simple-subtypep method delegates to complex-subtypep
2640 ;;; of the individual types of type1. - CSR, 2002-04-09
2641 ;;;
2642 ;;; Previous comment, now obsolete, but worth keeping around because
2643 ;;; it is true, though too strong a condition:
2644 ;;;
2645 ;;; Two union types are equal if their subtypes are equal sets.
2646 (!define-type-method (union :simple-=) (type1 type2)
2647   (multiple-value-bind (subtype certain?)
2648       (csubtypep type1 type2)
2649     (if subtype
2650         (csubtypep type2 type1)
2651         ;; we might as well become as certain as possible.
2652         (if certain?
2653             (values nil t)
2654             (multiple-value-bind (subtype certain?)
2655                 (csubtypep type2 type1)
2656               (declare (ignore subtype))
2657               (values nil certain?))))))
2658
2659 (!define-type-method (union :complex-=) (type1 type2)
2660   (declare (ignore type1))
2661   (if (some #'type-might-contain-other-types-p 
2662             (union-type-types type2))
2663       (values nil nil)
2664       (values nil t)))
2665
2666 ;;; Similarly, a union type is a subtype of another if and only if
2667 ;;; every element of TYPE1 is a subtype of TYPE2.
2668 (defun union-simple-subtypep (type1 type2)
2669   (every/type (swapped-args-fun #'union-complex-subtypep-arg2)
2670               type2
2671               (union-type-types type1)))
2672
2673 (!define-type-method (union :simple-subtypep) (type1 type2)
2674   (union-simple-subtypep type1 type2))
2675   
2676 (defun union-complex-subtypep-arg1 (type1 type2)
2677   (every/type (swapped-args-fun #'csubtypep)
2678               type2
2679               (union-type-types type1)))
2680
2681 (!define-type-method (union :complex-subtypep-arg1) (type1 type2)
2682   (union-complex-subtypep-arg1 type1 type2))
2683
2684 (defun union-complex-subtypep-arg2 (type1 type2)
2685   (multiple-value-bind (sub-value sub-certain?)
2686       ;; was: (any/type #'csubtypep type1 (union-type-types type2)),
2687       ;; which turns out to be too restrictive, causing bug 91.
2688       ;;
2689       ;; the following reimplementation might look dodgy.  It is
2690       ;; dodgy. It depends on the union :complex-= method not doing
2691       ;; very much work -- certainly, not using subtypep. Reasoning:
2692       (progn
2693         ;; At this stage, we know that type2 is a union type and type1
2694         ;; isn't. We might as well check this, though:
2695         (aver (union-type-p type2))
2696         (aver (not (union-type-p type1)))
2697         ;;     A is a subset of (B1 u B2)
2698         ;; <=> A n (B1 u B2) = A
2699         ;; <=> (A n B1) u (A n B2) = A
2700         ;;
2701         ;; But, we have to be careful not to delegate this type= to
2702         ;; something that could invoke subtypep, which might get us
2703         ;; back here -> stack explosion. We therefore ensure that the
2704         ;; second type (which is the one that's dispatched on) is
2705         ;; either a union type (where we've ensured that the complex-=
2706         ;; method will not call subtypep) or something with no union
2707         ;; types involved, in which case we'll never come back here.
2708         ;;
2709         ;; If we don't do this, then e.g.
2710         ;; (SUBTYPEP '(MEMBER 3) '(OR (SATISFIES FOO) (SATISFIES BAR)))
2711         ;; would loop infinitely, as the member :complex-= method is
2712         ;; implemented in terms of subtypep.
2713         ;;
2714         ;; Ouch. - CSR, 2002-04-10
2715         (type= type1
2716                (apply #'type-union
2717                       (mapcar (lambda (x) (type-intersection type1 x))
2718                               (union-type-types type2)))))
2719     (if sub-certain?
2720         (values sub-value sub-certain?)
2721         ;; The ANY/TYPE expression above is a sufficient condition for
2722         ;; subsetness, but not a necessary one, so we might get a more
2723         ;; certain answer by this CALL-NEXT-METHOD-ish step when the
2724         ;; ANY/TYPE expression is uncertain.
2725         (invoke-complex-subtypep-arg1-method type1 type2))))
2726
2727 (!define-type-method (union :complex-subtypep-arg2) (type1 type2)
2728   (union-complex-subtypep-arg2 type1 type2))
2729
2730 (!define-type-method (union :simple-intersection2 :complex-intersection2)
2731                      (type1 type2)
2732   ;; The CSUBTYPEP clauses here let us simplify e.g.
2733   ;;   (TYPE-INTERSECTION2 (SPECIFIER-TYPE 'LIST)
2734   ;;                       (SPECIFIER-TYPE '(OR LIST VECTOR)))
2735   ;; (where LIST is (OR CONS NULL)).
2736   ;;
2737   ;; The tests are more or less (CSUBTYPEP TYPE1 TYPE2) and vice
2738   ;; versa, but it's important that we pre-expand them into
2739   ;; specialized operations on individual elements of
2740   ;; UNION-TYPE-TYPES, instead of using the ordinary call to
2741   ;; CSUBTYPEP, in order to avoid possibly invoking any methods which
2742   ;; might in turn invoke (TYPE-INTERSECTION2 TYPE1 TYPE2) and thus
2743   ;; cause infinite recursion.
2744   ;;
2745   ;; Within this method, type2 is guaranteed to be a union type:
2746   (aver (union-type-p type2))
2747   ;; Make sure to call only the applicable methods...
2748   (cond ((and (union-type-p type1)
2749               (union-simple-subtypep type1 type2)) type1)
2750         ((and (union-type-p type1)
2751               (union-simple-subtypep type2 type1)) type2)
2752         ((and (not (union-type-p type1))
2753               (union-complex-subtypep-arg2 type1 type2))
2754          type1)
2755         ((and (not (union-type-p type1))
2756               (union-complex-subtypep-arg1 type2 type1))
2757          type2)
2758         (t 
2759          ;; KLUDGE: This code accumulates a sequence of TYPE-UNION2
2760          ;; operations in a particular order, and gives up if any of
2761          ;; the sub-unions turn out not to be simple. In other cases
2762          ;; ca. sbcl-0.6.11.15, that approach to taking a union was a
2763          ;; bad idea, since it can overlook simplifications which
2764          ;; might occur if the terms were accumulated in a different
2765          ;; order. It's possible that that will be a problem here too.
2766          ;; However, I can't think of a good example to demonstrate
2767          ;; it, and without an example to demonstrate it I can't write
2768          ;; test cases, and without test cases I don't want to
2769          ;; complicate the code to address what's still a hypothetical
2770          ;; problem. So I punted. -- WHN 2001-03-20
2771          (let ((accumulator *empty-type*))
2772            (dolist (t2 (union-type-types type2) accumulator)
2773              (setf accumulator
2774                    (type-union accumulator
2775                                (type-intersection type1 t2))))))))
2776
2777 (!def-type-translator or (&rest type-specifiers)
2778   (apply #'type-union
2779          (mapcar #'specifier-type
2780                  type-specifiers)))
2781 \f
2782 ;;;; CONS types
2783
2784 (!define-type-class cons)
2785
2786 (!def-type-translator cons (&optional (car-type-spec '*) (cdr-type-spec '*))
2787   (let ((car-type (single-value-specifier-type car-type-spec))
2788         (cdr-type (single-value-specifier-type cdr-type-spec)))
2789     (make-cons-type car-type cdr-type)))
2790  
2791 (!define-type-method (cons :unparse) (type)
2792   (let ((car-eltype (type-specifier (cons-type-car-type type)))
2793         (cdr-eltype (type-specifier (cons-type-cdr-type type))))
2794     (if (and (member car-eltype '(t *))
2795              (member cdr-eltype '(t *)))
2796         'cons
2797         `(cons ,car-eltype ,cdr-eltype))))
2798  
2799 (!define-type-method (cons :simple-=) (type1 type2)
2800   (declare (type cons-type type1 type2))
2801   (and (type= (cons-type-car-type type1) (cons-type-car-type type2))
2802        (type= (cons-type-cdr-type type1) (cons-type-cdr-type type2))))
2803  
2804 (!define-type-method (cons :simple-subtypep) (type1 type2)
2805   (declare (type cons-type type1 type2))
2806   (multiple-value-bind (val-car win-car)
2807       (csubtypep (cons-type-car-type type1) (cons-type-car-type type2))
2808     (multiple-value-bind (val-cdr win-cdr)
2809         (csubtypep (cons-type-cdr-type type1) (cons-type-cdr-type type2))
2810       (if (and val-car val-cdr)
2811           (values t (and win-car win-cdr))
2812           (values nil (or win-car win-cdr))))))
2813  
2814 ;;; Give up if a precise type is not possible, to avoid returning
2815 ;;; overly general types.
2816 (!define-type-method (cons :simple-union2) (type1 type2)
2817   (declare (type cons-type type1 type2))
2818   (let ((car-type1 (cons-type-car-type type1))
2819         (car-type2 (cons-type-car-type type2))
2820         (cdr-type1 (cons-type-cdr-type type1))
2821         (cdr-type2 (cons-type-cdr-type type2)))
2822     ;; UGH.  -- CSR, 2003-02-24
2823     (macrolet ((frob-car (car1 car2 cdr1 cdr2)
2824                  `(type-union
2825                    (make-cons-type ,car1 (type-union ,cdr1 ,cdr2))
2826                    (make-cons-type
2827                     (type-intersection ,car2
2828                      (specifier-type
2829                       `(not ,(type-specifier ,car1))))
2830                     ,cdr2))))
2831       (cond ((type= car-type1 car-type2)
2832              (make-cons-type car-type1
2833                              (type-union cdr-type1 cdr-type2)))
2834             ((type= cdr-type1 cdr-type2)
2835              (make-cons-type (type-union car-type1 car-type2)
2836                              cdr-type1))
2837             ((csubtypep car-type1 car-type2)
2838              (frob-car car-type1 car-type2 cdr-type1 cdr-type2))
2839             ((csubtypep car-type2 car-type1)
2840              (frob-car car-type2 car-type1 cdr-type2 cdr-type1))
2841             ;; Don't put these in -- consider the effect of taking the
2842             ;; union of (CONS (INTEGER 0 2) (INTEGER 5 7)) and
2843             ;; (CONS (INTEGER 0 3) (INTEGER 5 6)).
2844             #+nil
2845             ((csubtypep cdr-type1 cdr-type2)
2846              (frob-cdr car-type1 car-type2 cdr-type1 cdr-type2))
2847             #+nil
2848             ((csubtypep cdr-type2 cdr-type1)
2849              (frob-cdr car-type2 car-type1 cdr-type2 cdr-type1))))))
2850             
2851 (!define-type-method (cons :simple-intersection2) (type1 type2)
2852   (declare (type cons-type type1 type2))
2853   (let (car-int2
2854         cdr-int2)
2855     (and (setf car-int2 (type-intersection2 (cons-type-car-type type1)
2856                                             (cons-type-car-type type2)))
2857          (setf cdr-int2 (type-intersection2 (cons-type-cdr-type type1)
2858                                             (cons-type-cdr-type type2)))
2859          (make-cons-type car-int2 cdr-int2))))
2860 \f
2861 ;;; Return the type that describes all objects that are in X but not
2862 ;;; in Y. If we can't determine this type, then return NIL.
2863 ;;;
2864 ;;; For now, we only are clever dealing with union and member types.
2865 ;;; If either type is not a union type, then we pretend that it is a
2866 ;;; union of just one type. What we do is remove from X all the types
2867 ;;; that are a subtype any type in Y. If any type in X intersects with
2868 ;;; a type in Y but is not a subtype, then we give up.
2869 ;;;
2870 ;;; We must also special-case any member type that appears in the
2871 ;;; union. We remove from X's members all objects that are TYPEP to Y.
2872 ;;; If Y has any members, we must be careful that none of those
2873 ;;; members are CTYPEP to any of Y's non-member types. We give up in
2874 ;;; this case, since to compute that difference we would have to break
2875 ;;; the type from X into some collection of types that represents the
2876 ;;; type without that particular element. This seems too hairy to be
2877 ;;; worthwhile, given its low utility.
2878 (defun type-difference (x y)
2879   (let ((x-types (if (union-type-p x) (union-type-types x) (list x)))
2880         (y-types (if (union-type-p y) (union-type-types y) (list y))))
2881     (collect ((res))
2882       (dolist (x-type x-types)
2883         (if (member-type-p x-type)
2884             (collect ((members))
2885               (dolist (mem (member-type-members x-type))
2886                 (multiple-value-bind (val win) (ctypep mem y)
2887                   (unless win (return-from type-difference nil))
2888                   (unless val
2889                     (members mem))))
2890               (when (members)
2891                 (res (make-member-type :members (members)))))
2892             (dolist (y-type y-types (res x-type))
2893               (multiple-value-bind (val win) (csubtypep x-type y-type)
2894                 (unless win (return-from type-difference nil))
2895                 (when val (return))
2896                 (when (types-equal-or-intersect x-type y-type)
2897                   (return-from type-difference nil))))))
2898       (let ((y-mem (find-if #'member-type-p y-types)))
2899         (when y-mem
2900           (let ((members (member-type-members y-mem)))
2901             (dolist (x-type x-types)
2902               (unless (member-type-p x-type)
2903                 (dolist (member members)
2904                   (multiple-value-bind (val win) (ctypep member x-type)
2905                     (when (or (not win) val)
2906                       (return-from type-difference nil)))))))))
2907       (apply #'type-union (res)))))
2908 \f
2909 (!def-type-translator array (&optional (element-type '*)
2910                                        (dimensions '*))
2911   (specialize-array-type
2912    (make-array-type :dimensions (canonical-array-dimensions dimensions)
2913                     :complexp :maybe
2914                     :element-type (if (eq element-type '*)
2915                                       *wild-type*
2916                                       (specifier-type element-type)))))
2917
2918 (!def-type-translator simple-array (&optional (element-type '*)
2919                                               (dimensions '*))
2920   (specialize-array-type
2921    (make-array-type :dimensions (canonical-array-dimensions dimensions)
2922                     :complexp nil
2923                     :element-type (if (eq element-type '*)
2924                                       *wild-type*
2925                                       (specifier-type element-type)))))
2926 \f
2927 ;;;; utilities shared between cross-compiler and target system
2928
2929 ;;; Does the type derived from compilation of an actual function
2930 ;;; definition satisfy declarations of a function's type?
2931 (defun defined-ftype-matches-declared-ftype-p (defined-ftype declared-ftype)
2932   (declare (type ctype defined-ftype declared-ftype))
2933   (flet ((is-built-in-class-function-p (ctype)
2934            (and (built-in-classoid-p ctype)
2935                 (eq (built-in-classoid-name ctype) 'function))))
2936     (cond (;; DECLARED-FTYPE could certainly be #<BUILT-IN-CLASS FUNCTION>;
2937            ;; that's what happens when we (DECLAIM (FTYPE FUNCTION FOO)).
2938            (is-built-in-class-function-p declared-ftype)
2939            ;; In that case, any definition satisfies the declaration.
2940            t)
2941           (;; It's not clear whether or how DEFINED-FTYPE might be
2942            ;; #<BUILT-IN-CLASS FUNCTION>, but it's not obviously
2943            ;; invalid, so let's handle that case too, just in case.
2944            (is-built-in-class-function-p defined-ftype)
2945            ;; No matter what DECLARED-FTYPE might be, we can't prove
2946            ;; that an object of type FUNCTION doesn't satisfy it, so
2947            ;; we return success no matter what.
2948            t)
2949           (;; Otherwise both of them must be FUN-TYPE objects.
2950            t
2951            ;; FIXME: For now we only check compatibility of the return
2952            ;; type, not argument types, and we don't even check the
2953            ;; return type very precisely (as per bug 94a). It would be
2954            ;; good to do a better job. Perhaps to check the
2955            ;; compatibility of the arguments, we should (1) redo
2956            ;; VALUES-TYPES-EQUAL-OR-INTERSECT as
2957            ;; ARGS-TYPES-EQUAL-OR-INTERSECT, and then (2) apply it to
2958            ;; the ARGS-TYPE slices of the FUN-TYPEs. (ARGS-TYPE
2959            ;; is a base class both of VALUES-TYPE and of FUN-TYPE.)
2960            (values-types-equal-or-intersect
2961             (fun-type-returns defined-ftype)
2962             (fun-type-returns declared-ftype))))))
2963            
2964 ;;; This messy case of CTYPE for NUMBER is shared between the
2965 ;;; cross-compiler and the target system.
2966 (defun ctype-of-number (x)
2967   (let ((num (if (complexp x) (realpart x) x)))
2968     (multiple-value-bind (complexp low high)
2969         (if (complexp x)
2970             (let ((imag (imagpart x)))
2971               (values :complex (min num imag) (max num imag)))
2972             (values :real num num))
2973       (make-numeric-type :class (etypecase num
2974                                   (integer 'integer)
2975                                   (rational 'rational)
2976                                   (float 'float))
2977                          :format (and (floatp num) (float-format-name num))
2978                          :complexp complexp
2979                          :low low
2980                          :high high))))
2981 \f
2982 (locally
2983   ;; Why SAFETY 0? To suppress the is-it-the-right-structure-type
2984   ;; checking for declarations in structure accessors. Otherwise we
2985   ;; can get caught in a chicken-and-egg bootstrapping problem, whose
2986   ;; symptom on x86 OpenBSD sbcl-0.pre7.37.flaky5.22 is an illegal
2987   ;; instruction trap. I haven't tracked it down, but I'm guessing it
2988   ;; has to do with setting LAYOUTs when the LAYOUT hasn't been set
2989   ;; yet. -- WHN
2990   (declare (optimize (safety 0)))
2991   (!defun-from-collected-cold-init-forms !late-type-cold-init))
2992
2993 (/show0 "late-type.lisp end of file")