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