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