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