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