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