0.9.15.35: fix CONS :SIMPLE-= method
[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   (make-negation-type :type 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                        nil))))))))
853
854 (defun-cached (type-intersection2 :hash-function type-cache-hash
855                                   :hash-bits 8
856                                   :values 1
857                                   :default nil
858                                   :init-wrapper !cold-init-forms)
859               ((type1 eq) (type2 eq))
860   (declare (type ctype type1 type2))
861   (cond ((eq type1 type2)
862          ;; FIXME: For some reason, this doesn't catch e.g. type1 =
863          ;; type2 = (SPECIFIER-TYPE
864          ;; 'SOME-UNKNOWN-TYPE). Investigate. - CSR, 2002-04-10
865          type1)
866         ((or (intersection-type-p type1)
867              (intersection-type-p type2))
868          ;; Intersections of INTERSECTION-TYPE should have the
869          ;; INTERSECTION-TYPE-TYPES values broken out and intersected
870          ;; separately. The full TYPE-INTERSECTION function knows how
871          ;; to do that, so let it handle it.
872          (type-intersection type1 type2))
873         (t
874          ;; the ordinary case: we dispatch to type methods
875          (%type-intersection2 type1 type2))))
876
877 ;;; Return as restrictive and simple a type as we can discover that is
878 ;;; no more restrictive than the intersection of TYPE1 and TYPE2. At
879 ;;; worst, we arbitrarily return one of the arguments as the first
880 ;;; value (trying not to return a hairy type).
881 (defun type-approx-intersection2 (type1 type2)
882   (cond ((type-intersection2 type1 type2))
883         ((hairy-type-p type1) type2)
884         (t type1)))
885
886 ;;; a test useful for checking whether a derived type matches a
887 ;;; declared type
888 ;;;
889 ;;; The first value is true unless the types don't intersect and
890 ;;; aren't equal. The second value is true if the first value is
891 ;;; definitely correct. NIL is considered to intersect with any type.
892 ;;; If T is a subtype of either type, then we also return T, T. This
893 ;;; way we recognize that hairy types might intersect with T.
894 (defun types-equal-or-intersect (type1 type2)
895   (declare (type ctype type1 type2))
896   (if (or (eq type1 *empty-type*) (eq type2 *empty-type*))
897       (values t t)
898       (let ((intersection2 (type-intersection2 type1 type2)))
899         (cond ((not intersection2)
900                (if (or (csubtypep *universal-type* type1)
901                        (csubtypep *universal-type* type2))
902                    (values t t)
903                    (values t nil)))
904               ((eq intersection2 *empty-type*) (values nil t))
905               (t (values t t))))))
906
907 ;;; Return a Common Lisp type specifier corresponding to the TYPE
908 ;;; object.
909 (defun type-specifier (type)
910   (declare (type ctype type))
911   (funcall (type-class-unparse (type-class-info type)) type))
912
913 (defun-cached (type-negation :hash-function (lambda (type)
914                                               (logand (type-hash-value type)
915                                                       #xff))
916                              :hash-bits 8
917                              :values 1
918                              :default nil
919                              :init-wrapper !cold-init-forms)
920               ((type eq))
921   (declare (type ctype type))
922   (funcall (type-class-negate (type-class-info type)) type))
923
924 ;;; (VALUES-SPECIFIER-TYPE and SPECIFIER-TYPE moved from here to
925 ;;; early-type.lisp by WHN ca. 19990201.)
926
927 ;;; Take a list of type specifiers, computing the translation of each
928 ;;; specifier and defining it as a builtin type.
929 (declaim (ftype (function (list) (values)) precompute-types))
930 (defun precompute-types (specs)
931   (dolist (spec specs)
932     (let ((res (specifier-type spec)))
933       (unless (unknown-type-p res)
934         (setf (info :type :builtin spec) res)
935         ;; KLUDGE: the three copies of this idiom in this file (and
936         ;; the one in class.lisp as at sbcl-0.7.4.1x) should be
937         ;; coalesced, or perhaps the error-detecting code that
938         ;; disallows redefinition of :PRIMITIVE types should be
939         ;; rewritten to use *TYPE-SYSTEM-FINALIZED* (rather than
940         ;; *TYPE-SYSTEM-INITIALIZED*). The effect of this is not to
941         ;; cause redefinition errors when precompute-types is called
942         ;; for a second time while building the target compiler using
943         ;; the cross-compiler. -- CSR, trying to explain why this
944         ;; isn't completely wrong, 2002-06-07
945         (setf (info :type :kind spec) #+sb-xc-host :defined #-sb-xc-host :primitive))))
946   (values))
947 \f
948 ;;;; general TYPE-UNION and TYPE-INTERSECTION operations
949 ;;;;
950 ;;;; These are fully general operations on CTYPEs: they'll always
951 ;;;; return a CTYPE representing the result.
952
953 ;;; shared logic for unions and intersections: Return a list of
954 ;;; types representing the same types as INPUT-TYPES, but with
955 ;;; COMPOUND-TYPEs satisfying %COMPOUND-TYPE-P broken up into their
956 ;;; component types, and with any SIMPLY2 simplifications applied.
957 (macrolet
958     ((def (name compound-type-p simplify2)
959          `(defun ,name (types)
960             (when types
961               (multiple-value-bind (first rest)
962                   (if (,compound-type-p (car types))
963                       (values (car (compound-type-types (car types)))
964                               (append (cdr (compound-type-types (car types)))
965                                       (cdr types)))
966                       (values (car types) (cdr types)))
967                 (let ((rest (,name rest)) u)
968                   (dolist (r rest (cons first rest))
969                     (when (setq u (,simplify2 first r))
970                       (return (,name (nsubstitute u r rest)))))))))))
971   (def simplify-intersections intersection-type-p type-intersection2)
972   (def simplify-unions union-type-p type-union2))
973
974 (defun maybe-distribute-one-union (union-type types)
975   (let* ((intersection (apply #'type-intersection types))
976          (union (mapcar (lambda (x) (type-intersection x intersection))
977                         (union-type-types union-type))))
978     (if (notany (lambda (x) (or (hairy-type-p x)
979                                 (intersection-type-p x)))
980                 union)
981         union
982         nil)))
983
984 (defun type-intersection (&rest input-types)
985   (%type-intersection input-types))
986 (defun-cached (%type-intersection :hash-bits 8
987                                   :hash-function (lambda (x)
988                                                    (logand (sxhash x) #xff)))
989     ((input-types equal))
990   (let ((simplified-types (simplify-intersections input-types)))
991     (declare (type list simplified-types))
992     ;; We want to have a canonical representation of types (or failing
993     ;; that, punt to HAIRY-TYPE). Canonical representation would have
994     ;; intersections inside unions but not vice versa, since you can
995     ;; always achieve that by the distributive rule. But we don't want
996     ;; to just apply the distributive rule, since it would be too easy
997     ;; to end up with unreasonably huge type expressions. So instead
998     ;; we try to generate a simple type by distributing the union; if
999     ;; the type can't be made simple, we punt to HAIRY-TYPE.
1000     (if (and (cdr simplified-types) (some #'union-type-p simplified-types))
1001         (let* ((first-union (find-if #'union-type-p simplified-types))
1002                (other-types (coerce (remove first-union simplified-types)
1003                                     'list))
1004                (distributed (maybe-distribute-one-union first-union
1005                                                         other-types)))
1006           (if distributed
1007               (apply #'type-union distributed)
1008               (make-hairy-type
1009                :specifier `(and ,@(map 'list
1010                                        #'type-specifier
1011                                        simplified-types)))))
1012         (cond
1013           ((null simplified-types) *universal-type*)
1014           ((null (cdr simplified-types)) (car simplified-types))
1015           (t (%make-intersection-type
1016               (some #'type-enumerable simplified-types)
1017               simplified-types))))))
1018
1019 (defun type-union (&rest input-types)
1020   (%type-union input-types))
1021 (defun-cached (%type-union :hash-bits 8
1022                            :hash-function (lambda (x)
1023                                             (logand (sxhash x) #xff)))
1024     ((input-types equal))
1025   (let ((simplified-types (simplify-unions input-types)))
1026     (cond
1027       ((null simplified-types) *empty-type*)
1028       ((null (cdr simplified-types)) (car simplified-types))
1029       (t (make-union-type
1030           (every #'type-enumerable simplified-types)
1031           simplified-types)))))
1032 \f
1033 ;;;; built-in types
1034
1035 (!define-type-class named)
1036
1037 (!cold-init-forms
1038  (macrolet ((frob (name var)
1039               `(progn
1040                  (setq ,var (make-named-type :name ',name))
1041                  (setf (info :type :kind ',name)
1042                        #+sb-xc-host :defined #-sb-xc-host :primitive)
1043                  (setf (info :type :builtin ',name) ,var))))
1044    ;; KLUDGE: In ANSI, * isn't really the name of a type, it's just a
1045    ;; special symbol which can be stuck in some places where an
1046    ;; ordinary type can go, e.g. (ARRAY * 1) instead of (ARRAY T 1).
1047    ;; In SBCL it also used to denote universal VALUES type.
1048    (frob * *wild-type*)
1049    (frob nil *empty-type*)
1050    (frob t *universal-type*)
1051    ;; new in sbcl-0.9.5: these used to be CLASSOID types, but that
1052    ;; view of them was incompatible with requirements on the MOP
1053    ;; metaobject class hierarchy: the INSTANCE and
1054    ;; FUNCALLABLE-INSTANCE types are disjoint (instances have
1055    ;; instance-pointer-lowtag; funcallable-instances have
1056    ;; fun-pointer-lowtag), while FUNCALLABLE-STANDARD-OBJECT is
1057    ;; required to be a subclass of STANDARD-OBJECT.  -- CSR,
1058    ;; 2005-09-09
1059    (frob instance *instance-type*)
1060    (frob funcallable-instance *funcallable-instance-type*))
1061  (setf *universal-fun-type*
1062        (make-fun-type :wild-args t
1063                       :returns *wild-type*)))
1064
1065 (!define-type-method (named :simple-=) (type1 type2)
1066   ;;(aver (not (eq type1 *wild-type*))) ; * isn't really a type.
1067   (values (eq type1 type2) t))
1068
1069 (defun cons-type-might-be-empty-type (type)
1070   (declare (type cons-type type))
1071   (let ((car-type (cons-type-car-type type))
1072         (cdr-type (cons-type-cdr-type type)))
1073     (or
1074      (if (cons-type-p car-type)
1075          (cons-type-might-be-empty-type car-type)
1076          (multiple-value-bind (yes surep)
1077              (type= car-type *empty-type*)
1078            (aver (not yes))
1079            (not surep)))
1080      (if (cons-type-p cdr-type)
1081          (cons-type-might-be-empty-type cdr-type)
1082          (multiple-value-bind (yes surep)
1083              (type= cdr-type *empty-type*)
1084            (aver (not yes))
1085            (not surep))))))
1086
1087 (!define-type-method (named :complex-=) (type1 type2)
1088   (cond
1089     ((and (eq type2 *empty-type*)
1090           (or (and (intersection-type-p type1)
1091                    ;; not allowed to be unsure on these... FIXME: keep
1092                    ;; the list of CL types that are intersection types
1093                    ;; once and only once.
1094                    (not (or (type= type1 (specifier-type 'ratio))
1095                             (type= type1 (specifier-type 'keyword)))))
1096               (and (cons-type-p type1)
1097                    (cons-type-might-be-empty-type type1))))
1098      ;; things like (AND (EQL 0) (SATISFIES ODDP)) or (AND FUNCTION
1099      ;; STREAM) can get here.  In general, we can't really tell
1100      ;; whether these are equal to NIL or not, so
1101      (values nil nil))
1102     ((type-might-contain-other-types-p type1)
1103      (invoke-complex-=-other-method type1 type2))
1104     (t (values nil t))))
1105
1106 (!define-type-method (named :simple-subtypep) (type1 type2)
1107   (aver (not (eq type1 *wild-type*))) ; * isn't really a type.
1108   (aver (not (eq type1 type2)))
1109   (values (or (eq type1 *empty-type*)
1110               (eq type2 *wild-type*)
1111               (eq type2 *universal-type*)) t))
1112
1113 (!define-type-method (named :complex-subtypep-arg1) (type1 type2)
1114   ;; This AVER causes problems if we write accurate methods for the
1115   ;; union (and possibly intersection) types which then delegate to
1116   ;; us; while a user shouldn't get here, because of the odd status of
1117   ;; *wild-type* a type-intersection executed by the compiler can. -
1118   ;; CSR, 2002-04-10
1119   ;;
1120   ;; (aver (not (eq type1 *wild-type*))) ; * isn't really a type.
1121   (cond ((eq type1 *empty-type*)
1122          t)
1123         (;; When TYPE2 might be the universal type in disguise
1124          (type-might-contain-other-types-p type2)
1125          ;; Now that the UNION and HAIRY COMPLEX-SUBTYPEP-ARG2 methods
1126          ;; can delegate to us (more or less as CALL-NEXT-METHOD) when
1127          ;; they're uncertain, we can't just barf on COMPOUND-TYPE and
1128          ;; HAIRY-TYPEs as we used to. Instead we deal with the
1129          ;; problem (where at least part of the problem is cases like
1130          ;;   (SUBTYPEP T '(SATISFIES FOO))
1131          ;; or
1132          ;;   (SUBTYPEP T '(AND (SATISFIES FOO) (SATISFIES BAR)))
1133          ;; where the second type is a hairy type like SATISFIES, or
1134          ;; is a compound type which might contain a hairy type) by
1135          ;; returning uncertainty.
1136          (values nil nil))
1137         ((eq type1 *funcallable-instance-type*)
1138          (values (eq type2 (specifier-type 'function)) t))
1139         (t
1140          ;; This case would have been picked off by the SIMPLE-SUBTYPEP
1141          ;; method, and so shouldn't appear here.
1142          (aver (not (named-type-p type2)))
1143          ;; Since TYPE2 is not EQ *UNIVERSAL-TYPE* and is not another
1144          ;; named type in disguise, TYPE2 is not a superset of TYPE1.
1145          (values nil t))))
1146
1147 (!define-type-method (named :complex-subtypep-arg2) (type1 type2)
1148   (aver (not (eq type2 *wild-type*))) ; * isn't really a type.
1149   (cond ((eq type2 *universal-type*)
1150          (values t t))
1151         ((or (type-might-contain-other-types-p type1)
1152              ;; some CONS types can conceal danger
1153              (and (cons-type-p type1)
1154                   (cons-type-might-be-empty-type type1)))
1155          ;; those types can be other types in disguise.  So we'd
1156          ;; better delegate.
1157          (invoke-complex-subtypep-arg1-method type1 type2))
1158         ((and (or (eq type2 *instance-type*)
1159                   (eq type2 *funcallable-instance-type*))
1160               (member-type-p type1))
1161          ;; member types can be subtypep INSTANCE and
1162          ;; FUNCALLABLE-INSTANCE in surprising ways.
1163          (invoke-complex-subtypep-arg1-method type1 type2))
1164         ((and (eq type2 *instance-type*) (classoid-p type1))
1165          (if (member type1 *non-instance-classoid-types* :key #'find-classoid)
1166              (values nil t)
1167              (let* ((layout (classoid-layout type1))
1168                     (inherits (layout-inherits layout))
1169                     (functionp (find (classoid-layout (find-classoid 'function))
1170                                      inherits)))
1171                (cond
1172                  (functionp
1173                   (values nil t))
1174                  ((eq type1 (find-classoid 'function))
1175                   (values nil t))
1176                  ((or (structure-classoid-p type1)
1177                       #+nil
1178                       (condition-classoid-p type1))
1179                   (values t t))
1180                  (t (values nil nil))))))
1181         ((and (eq type2 *funcallable-instance-type*) (classoid-p type1))
1182          (if (member type1 *non-instance-classoid-types* :key #'find-classoid)
1183              (values nil t)
1184              (let* ((layout (classoid-layout type1))
1185                     (inherits (layout-inherits layout))
1186                     (functionp (find (classoid-layout (find-classoid 'function))
1187                                      inherits)))
1188                (values (if functionp t nil) t))))
1189         (t
1190          ;; FIXME: This seems to rely on there only being 4 or 5
1191          ;; NAMED-TYPE values, and the exclusion of various
1192          ;; possibilities above. It would be good to explain it and/or
1193          ;; rewrite it so that it's clearer.
1194          (values nil t))))
1195
1196 (!define-type-method (named :complex-intersection2) (type1 type2)
1197   ;; FIXME: This assertion failed when I added it in sbcl-0.6.11.13.
1198   ;; Perhaps when bug 85 is fixed it can be reenabled.
1199   ;;(aver (not (eq type2 *wild-type*))) ; * isn't really a type.
1200   (cond
1201     ((eq type2 *instance-type*)
1202      (if (classoid-p type1)
1203          (if (and (not (member type1 *non-instance-classoid-types*
1204                                :key #'find-classoid))
1205                   (not (eq type1 (find-classoid 'function)))
1206                   (not (find (classoid-layout (find-classoid 'function))
1207                              (layout-inherits (classoid-layout type1)))))
1208              (if (or (structure-classoid-p type1)
1209                      (and (not (eq type1 (find-classoid 'stream)))
1210                           (not (find (classoid-layout (find-classoid 'stream))
1211                                      (layout-inherits (classoid-layout type1))))))
1212                  type1
1213                  nil)
1214              *empty-type*)
1215          (if (or (type-might-contain-other-types-p type1)
1216                  (member-type-p type1))
1217              nil
1218              *empty-type*)))
1219     ((eq type2 *funcallable-instance-type*)
1220      (if (classoid-p type1)
1221          (if (and (not (member type1 *non-instance-classoid-types*
1222                                :key #'find-classoid))
1223                   (find (classoid-layout (find-classoid 'function))
1224                         (layout-inherits (classoid-layout type1))))
1225              type1
1226              (if (type= type1 (find-classoid 'function))
1227                  type2
1228                  nil))
1229          (if (fun-type-p type1)
1230              nil
1231              (if (or (type-might-contain-other-types-p type1)
1232                      (member-type-p type1))
1233                  nil
1234                  *empty-type*))))
1235     (t (hierarchical-intersection2 type1 type2))))
1236
1237 (!define-type-method (named :complex-union2) (type1 type2)
1238   ;; Perhaps when bug 85 is fixed this can be reenabled.
1239   ;;(aver (not (eq type2 *wild-type*))) ; * isn't really a type.
1240   (cond
1241     ((eq type2 *instance-type*)
1242      (if (classoid-p type1)
1243          (if (or (member type1 *non-instance-classoid-types*
1244                          :key #'find-classoid)
1245                  (find (classoid-layout (find-classoid 'function))
1246                        (layout-inherits (classoid-layout type1))))
1247              nil
1248              type2)
1249          nil))
1250     ((eq type2 *funcallable-instance-type*)
1251      (if (classoid-p type1)
1252          (if (or (member type1 *non-instance-classoid-types*
1253                          :key #'find-classoid)
1254                  (not (find (classoid-layout (find-classoid 'function))
1255                             (layout-inherits (classoid-layout type1)))))
1256              nil
1257              (if (eq type1 (specifier-type 'function))
1258                  type1
1259                  type2))
1260          nil))
1261     (t (hierarchical-union2 type1 type2))))
1262
1263 (!define-type-method (named :negate) (x)
1264   (aver (not (eq x *wild-type*)))
1265   (cond
1266     ((eq x *universal-type*) *empty-type*)
1267     ((eq x *empty-type*) *universal-type*)
1268     ((or (eq x *instance-type*)
1269          (eq x *funcallable-instance-type*))
1270      (make-negation-type :type x))
1271     (t (bug "NAMED type unexpected: ~S" x))))
1272
1273 (!define-type-method (named :unparse) (x)
1274   (named-type-name x))
1275 \f
1276 ;;;; hairy and unknown types
1277
1278 (!define-type-method (hairy :negate) (x)
1279   (make-negation-type :type x))
1280
1281 (!define-type-method (hairy :unparse) (x)
1282   (hairy-type-specifier x))
1283
1284 (!define-type-method (hairy :simple-subtypep) (type1 type2)
1285   (let ((hairy-spec1 (hairy-type-specifier type1))
1286         (hairy-spec2 (hairy-type-specifier type2)))
1287     (cond ((equal-but-no-car-recursion hairy-spec1 hairy-spec2)
1288            (values t t))
1289           (t
1290            (values nil nil)))))
1291
1292 (!define-type-method (hairy :complex-subtypep-arg2) (type1 type2)
1293   (invoke-complex-subtypep-arg1-method type1 type2))
1294
1295 (!define-type-method (hairy :complex-subtypep-arg1) (type1 type2)
1296   (declare (ignore type1 type2))
1297   (values nil nil))
1298
1299 (!define-type-method (hairy :complex-=) (type1 type2)
1300   (if (and (unknown-type-p type2)
1301            (let* ((specifier2 (unknown-type-specifier type2))
1302                   (name2 (if (consp specifier2)
1303                              (car specifier2)
1304                              specifier2)))
1305              (info :type :kind name2)))
1306       (let ((type2 (specifier-type (unknown-type-specifier type2))))
1307         (if (unknown-type-p type2)
1308             (values nil nil)
1309             (type= type1 type2)))
1310   (values nil nil)))
1311
1312 (!define-type-method (hairy :simple-intersection2 :complex-intersection2)
1313                      (type1 type2)
1314   (if (type= type1 type2)
1315       type1
1316       nil))
1317
1318 (!define-type-method (hairy :simple-union2)
1319                      (type1 type2)
1320   (if (type= type1 type2)
1321       type1
1322       nil))
1323
1324 (!define-type-method (hairy :simple-=) (type1 type2)
1325   (if (equal-but-no-car-recursion (hairy-type-specifier type1)
1326                                   (hairy-type-specifier type2))
1327       (values t t)
1328       (values nil nil)))
1329
1330 (!def-type-translator satisfies (&whole whole fun)
1331   (declare (ignore fun))
1332   ;; Check legality of arguments.
1333   (destructuring-bind (satisfies predicate-name) whole
1334     (declare (ignore satisfies))
1335     (unless (symbolp predicate-name)
1336       (error 'simple-type-error
1337              :datum predicate-name
1338              :expected-type 'symbol
1339              :format-control "The SATISFIES predicate name is not a symbol: ~S"
1340              :format-arguments (list predicate-name))))
1341   ;; Create object.
1342   (make-hairy-type :specifier whole))
1343 \f
1344 ;;;; negation types
1345
1346 (!define-type-method (negation :negate) (x)
1347   (negation-type-type x))
1348
1349 (!define-type-method (negation :unparse) (x)
1350   (if (type= (negation-type-type x) (specifier-type 'cons))
1351       'atom
1352       `(not ,(type-specifier (negation-type-type x)))))
1353
1354 (!define-type-method (negation :simple-subtypep) (type1 type2)
1355   (csubtypep (negation-type-type type2) (negation-type-type type1)))
1356
1357 (!define-type-method (negation :complex-subtypep-arg2) (type1 type2)
1358   (let* ((complement-type2 (negation-type-type type2))
1359          (intersection2 (type-intersection2 type1
1360                                             complement-type2)))
1361     (if intersection2
1362         ;; FIXME: if uncertain, maybe try arg1?
1363         (type= intersection2 *empty-type*)
1364         (invoke-complex-subtypep-arg1-method type1 type2))))
1365
1366 (!define-type-method (negation :complex-subtypep-arg1) (type1 type2)
1367   ;; "Incrementally extended heuristic algorithms tend inexorably toward the
1368   ;; incomprehensible." -- http://www.unlambda.com/~james/lambda/lambda.txt
1369   ;;
1370   ;; You may not believe this. I couldn't either. But then I sat down
1371   ;; and drew lots of Venn diagrams. Comments involving a and b refer
1372   ;; to the call (subtypep '(not a) 'b) -- CSR, 2002-02-27.
1373   (block nil
1374     ;; (Several logical truths in this block are true as long as
1375     ;; b/=T. As of sbcl-0.7.1.28, it seems impossible to construct a
1376     ;; case with b=T where we actually reach this type method, but
1377     ;; we'll test for and exclude this case anyway, since future
1378     ;; maintenance might make it possible for it to end up in this
1379     ;; code.)
1380     (multiple-value-bind (equal certain)
1381         (type= type2 *universal-type*)
1382       (unless certain
1383         (return (values nil nil)))
1384       (when equal
1385         (return (values t t))))
1386     (let ((complement-type1 (negation-type-type type1)))
1387       ;; Do the special cases first, in order to give us a chance if
1388       ;; subtype/supertype relationships are hairy.
1389       (multiple-value-bind (equal certain)
1390           (type= complement-type1 type2)
1391         ;; If a = b, ~a is not a subtype of b (unless b=T, which was
1392         ;; excluded above).
1393         (unless certain
1394           (return (values nil nil)))
1395         (when equal
1396           (return (values nil t))))
1397       ;; KLUDGE: ANSI requires that the SUBTYPEP result between any
1398       ;; two built-in atomic type specifiers never be uncertain. This
1399       ;; is hard to do cleanly for the built-in types whose
1400       ;; definitions include (NOT FOO), i.e. CONS and RATIO. However,
1401       ;; we can do it with this hack, which uses our global knowledge
1402       ;; that our implementation of the type system uses disjoint
1403       ;; implementation types to represent disjoint sets (except when
1404       ;; types are contained in other types).  (This is a KLUDGE
1405       ;; because it's fragile. Various changes in internal
1406       ;; representation in the type system could make it start
1407       ;; confidently returning incorrect results.) -- WHN 2002-03-08
1408       (unless (or (type-might-contain-other-types-p complement-type1)
1409                   (type-might-contain-other-types-p type2))
1410         ;; Because of the way our types which don't contain other
1411         ;; types are disjoint subsets of the space of possible values,
1412         ;; (SUBTYPEP '(NOT AA) 'B)=NIL when AA and B are simple (and B
1413         ;; is not T, as checked above).
1414         (return (values nil t)))
1415       ;; The old (TYPE= TYPE1 TYPE2) branch would never be taken, as
1416       ;; TYPE1 and TYPE2 will only be equal if they're both NOT types,
1417       ;; and then the :SIMPLE-SUBTYPEP method would be used instead.
1418       ;; But a CSUBTYPEP relationship might still hold:
1419       (multiple-value-bind (equal certain)
1420           (csubtypep complement-type1 type2)
1421         ;; If a is a subtype of b, ~a is not a subtype of b (unless
1422         ;; b=T, which was excluded above).
1423         (unless certain
1424           (return (values nil nil)))
1425         (when equal
1426           (return (values nil t))))
1427       (multiple-value-bind (equal certain)
1428           (csubtypep type2 complement-type1)
1429         ;; If b is a subtype of a, ~a is not a subtype of b.  (FIXME:
1430         ;; That's not true if a=T. Do we know at this point that a is
1431         ;; not T?)
1432         (unless certain
1433           (return (values nil nil)))
1434         (when equal
1435           (return (values nil t))))
1436       ;; old CSR comment ca. 0.7.2, now obsoleted by the SIMPLE-CTYPE?
1437       ;; KLUDGE case above: Other cases here would rely on being able
1438       ;; to catch all possible cases, which the fragility of this type
1439       ;; system doesn't inspire me; for instance, if a is type= to ~b,
1440       ;; then we want T, T; if this is not the case and the types are
1441       ;; disjoint (have an intersection of *empty-type*) then we want
1442       ;; NIL, T; else if the union of a and b is the *universal-type*
1443       ;; then we want T, T. So currently we still claim to be unsure
1444       ;; about e.g. (subtypep '(not fixnum) 'single-float).
1445       ;;
1446       ;; OTOH we might still get here:
1447       (values nil nil))))
1448
1449 (!define-type-method (negation :complex-=) (type1 type2)
1450   ;; (NOT FOO) isn't equivalent to anything that's not a negation
1451   ;; type, except possibly a type that might contain it in disguise.
1452   (declare (ignore type2))
1453   (if (type-might-contain-other-types-p type1)
1454       (values nil nil)
1455       (values nil t)))
1456
1457 (!define-type-method (negation :simple-intersection2) (type1 type2)
1458   (let ((not1 (negation-type-type type1))
1459         (not2 (negation-type-type type2)))
1460     (cond
1461       ((csubtypep not1 not2) type2)
1462       ((csubtypep not2 not1) type1)
1463       ;; Why no analagous clause to the disjoint in the SIMPLE-UNION2
1464       ;; method, below?  The clause would read
1465       ;;
1466       ;; ((EQ (TYPE-UNION NOT1 NOT2) *UNIVERSAL-TYPE*) *EMPTY-TYPE*)
1467       ;;
1468       ;; but with proper canonicalization of negation types, there's
1469       ;; no way of constructing two negation types with union of their
1470       ;; negations being the universal type.
1471       (t
1472        (aver (not (eq (type-union not1 not2) *universal-type*)))
1473        nil))))
1474
1475 (!define-type-method (negation :complex-intersection2) (type1 type2)
1476   (cond
1477     ((csubtypep type1 (negation-type-type type2)) *empty-type*)
1478     ((eq (type-intersection type1 (negation-type-type type2)) *empty-type*)
1479      type1)
1480     (t nil)))
1481
1482 (!define-type-method (negation :simple-union2) (type1 type2)
1483   (let ((not1 (negation-type-type type1))
1484         (not2 (negation-type-type type2)))
1485     (cond
1486       ((csubtypep not1 not2) type1)
1487       ((csubtypep not2 not1) type2)
1488       ((eq (type-intersection not1 not2) *empty-type*)
1489        *universal-type*)
1490       (t nil))))
1491
1492 (!define-type-method (negation :complex-union2) (type1 type2)
1493   (cond
1494     ((csubtypep (negation-type-type type2) type1) *universal-type*)
1495     ((eq (type-intersection type1 (negation-type-type type2)) *empty-type*)
1496      type2)
1497     (t nil)))
1498
1499 (!define-type-method (negation :simple-=) (type1 type2)
1500   (type= (negation-type-type type1) (negation-type-type type2)))
1501
1502 (!def-type-translator not (typespec)
1503   (type-negation (specifier-type typespec)))
1504 \f
1505 ;;;; numeric types
1506
1507 (!define-type-class number)
1508
1509 (declaim (inline numeric-type-equal))
1510 (defun numeric-type-equal (type1 type2)
1511   (and (eq (numeric-type-class type1) (numeric-type-class type2))
1512        (eq (numeric-type-format type1) (numeric-type-format type2))
1513        (eq (numeric-type-complexp type1) (numeric-type-complexp type2))))
1514
1515 (!define-type-method (number :simple-=) (type1 type2)
1516   (values
1517    (and (numeric-type-equal type1 type2)
1518         (equalp (numeric-type-low type1) (numeric-type-low type2))
1519         (equalp (numeric-type-high type1) (numeric-type-high type2)))
1520    t))
1521
1522 (!define-type-method (number :negate) (type)
1523   (if (and (null (numeric-type-low type)) (null (numeric-type-high type)))
1524       (make-negation-type :type type)
1525       (type-union
1526        (make-negation-type
1527         :type (modified-numeric-type type :low nil :high nil))
1528        (cond
1529          ((null (numeric-type-low type))
1530           (modified-numeric-type
1531            type
1532            :low (let ((h (numeric-type-high type)))
1533                   (if (consp h) (car h) (list h)))
1534            :high nil))
1535          ((null (numeric-type-high type))
1536           (modified-numeric-type
1537            type
1538            :low nil
1539            :high (let ((l (numeric-type-low type)))
1540                    (if (consp l) (car l) (list l)))))
1541          (t (type-union
1542              (modified-numeric-type
1543               type
1544               :low nil
1545               :high (let ((l (numeric-type-low type)))
1546                       (if (consp l) (car l) (list l))))
1547              (modified-numeric-type
1548               type
1549               :low (let ((h (numeric-type-high type)))
1550                      (if (consp h) (car h) (list h)))
1551               :high nil)))))))
1552
1553 (!define-type-method (number :unparse) (type)
1554   (let* ((complexp (numeric-type-complexp type))
1555          (low (numeric-type-low type))
1556          (high (numeric-type-high type))
1557          (base (case (numeric-type-class type)
1558                  (integer 'integer)
1559                  (rational 'rational)
1560                  (float (or (numeric-type-format type) 'float))
1561                  (t 'real))))
1562     (let ((base+bounds
1563            (cond ((and (eq base 'integer) high low)
1564                   (let ((high-count (logcount high))
1565                         (high-length (integer-length high)))
1566                     (cond ((= low 0)
1567                            (cond ((= high 0) '(integer 0 0))
1568                                  ((= high 1) 'bit)
1569                                  ((and (= high-count high-length)
1570                                        (plusp high-length))
1571                                   `(unsigned-byte ,high-length))
1572                                  (t
1573                                   `(mod ,(1+ high)))))
1574                           ((and (= low sb!xc:most-negative-fixnum)
1575                                 (= high sb!xc:most-positive-fixnum))
1576                            'fixnum)
1577                           ((and (= low (lognot high))
1578                                 (= high-count high-length)
1579                                 (> high-count 0))
1580                            `(signed-byte ,(1+ high-length)))
1581                           (t
1582                            `(integer ,low ,high)))))
1583                  (high `(,base ,(or low '*) ,high))
1584                  (low
1585                   (if (and (eq base 'integer) (= low 0))
1586                       'unsigned-byte
1587                       `(,base ,low)))
1588                  (t base))))
1589       (ecase complexp
1590         (:real
1591          base+bounds)
1592         (:complex
1593          (aver (neq base+bounds 'real))
1594          `(complex ,base+bounds))
1595         ((nil)
1596          (aver (eq base+bounds 'real))
1597          'number)))))
1598
1599 ;;; Return true if X is "less than or equal" to Y, taking open bounds
1600 ;;; into consideration. CLOSED is the predicate used to test the bound
1601 ;;; on a closed interval (e.g. <=), and OPEN is the predicate used on
1602 ;;; open bounds (e.g. <). Y is considered to be the outside bound, in
1603 ;;; the sense that if it is infinite (NIL), then the test succeeds,
1604 ;;; whereas if X is infinite, then the test fails (unless Y is also
1605 ;;; infinite).
1606 ;;;
1607 ;;; This is for comparing bounds of the same kind, e.g. upper and
1608 ;;; upper. Use NUMERIC-BOUND-TEST* for different kinds of bounds.
1609 (defmacro numeric-bound-test (x y closed open)
1610   `(cond ((not ,y) t)
1611          ((not ,x) nil)
1612          ((consp ,x)
1613           (if (consp ,y)
1614               (,closed (car ,x) (car ,y))
1615               (,closed (car ,x) ,y)))
1616          (t
1617           (if (consp ,y)
1618               (,open ,x (car ,y))
1619               (,closed ,x ,y)))))
1620
1621 ;;; This is used to compare upper and lower bounds. This is different
1622 ;;; from the same-bound case:
1623 ;;; -- Since X = NIL is -infinity, whereas y = NIL is +infinity, we
1624 ;;;    return true if *either* arg is NIL.
1625 ;;; -- an open inner bound is "greater" and also squeezes the interval,
1626 ;;;    causing us to use the OPEN test for those cases as well.
1627 (defmacro numeric-bound-test* (x y closed open)
1628   `(cond ((not ,y) t)
1629          ((not ,x) t)
1630          ((consp ,x)
1631           (if (consp ,y)
1632               (,open (car ,x) (car ,y))
1633               (,open (car ,x) ,y)))
1634          (t
1635           (if (consp ,y)
1636               (,open ,x (car ,y))
1637               (,closed ,x ,y)))))
1638
1639 ;;; Return whichever of the numeric bounds X and Y is "maximal"
1640 ;;; according to the predicates CLOSED (e.g. >=) and OPEN (e.g. >).
1641 ;;; This is only meaningful for maximizing like bounds, i.e. upper and
1642 ;;; upper. If MAX-P is true, then we return NIL if X or Y is NIL,
1643 ;;; otherwise we return the other arg.
1644 (defmacro numeric-bound-max (x y closed open max-p)
1645   (once-only ((n-x x)
1646               (n-y y))
1647     `(cond ((not ,n-x) ,(if max-p nil n-y))
1648            ((not ,n-y) ,(if max-p nil n-x))
1649            ((consp ,n-x)
1650             (if (consp ,n-y)
1651                 (if (,closed (car ,n-x) (car ,n-y)) ,n-x ,n-y)
1652                 (if (,open (car ,n-x) ,n-y) ,n-x ,n-y)))
1653            (t
1654             (if (consp ,n-y)
1655                 (if (,open (car ,n-y) ,n-x) ,n-y ,n-x)
1656                 (if (,closed ,n-y ,n-x) ,n-y ,n-x))))))
1657
1658 (!define-type-method (number :simple-subtypep) (type1 type2)
1659   (let ((class1 (numeric-type-class type1))
1660         (class2 (numeric-type-class type2))
1661         (complexp2 (numeric-type-complexp type2))
1662         (format2 (numeric-type-format type2))
1663         (low1 (numeric-type-low type1))
1664         (high1 (numeric-type-high type1))
1665         (low2 (numeric-type-low type2))
1666         (high2 (numeric-type-high type2)))
1667     ;; If one is complex and the other isn't, they are disjoint.
1668     (cond ((not (or (eq (numeric-type-complexp type1) complexp2)
1669                     (null complexp2)))
1670            (values nil t))
1671           ;; If the classes are specified and different, the types are
1672           ;; disjoint unless type2 is RATIONAL and type1 is INTEGER.
1673           ;; [ or type1 is INTEGER and type2 is of the form (RATIONAL
1674           ;; X X) for integral X, but this is dealt with in the
1675           ;; canonicalization inside MAKE-NUMERIC-TYPE ]
1676           ((not (or (eq class1 class2)
1677                     (null class2)
1678                     (and (eq class1 'integer) (eq class2 'rational))))
1679            (values nil t))
1680           ;; If the float formats are specified and different, the types
1681           ;; are disjoint.
1682           ((not (or (eq (numeric-type-format type1) format2)
1683                     (null format2)))
1684            (values nil t))
1685           ;; Check the bounds.
1686           ((and (numeric-bound-test low1 low2 >= >)
1687                 (numeric-bound-test high1 high2 <= <))
1688            (values t t))
1689           (t
1690            (values nil t)))))
1691
1692 (!define-superclasses number ((number)) !cold-init-forms)
1693
1694 ;;; If the high bound of LOW is adjacent to the low bound of HIGH,
1695 ;;; then return true, otherwise NIL.
1696 (defun numeric-types-adjacent (low high)
1697   (let ((low-bound (numeric-type-high low))
1698         (high-bound (numeric-type-low high)))
1699     (cond ((not (and low-bound high-bound)) nil)
1700           ((and (consp low-bound) (consp high-bound)) nil)
1701           ((consp low-bound)
1702            (let ((low-value (car low-bound)))
1703              (or (eql low-value high-bound)
1704                  (and (eql low-value
1705                            (load-time-value (make-unportable-float
1706                                              :single-float-negative-zero)))
1707                       (eql high-bound 0f0))
1708                  (and (eql low-value 0f0)
1709                       (eql high-bound
1710                            (load-time-value (make-unportable-float
1711                                              :single-float-negative-zero))))
1712                  (and (eql low-value
1713                            (load-time-value (make-unportable-float
1714                                              :double-float-negative-zero)))
1715                       (eql high-bound 0d0))
1716                  (and (eql low-value 0d0)
1717                       (eql high-bound
1718                            (load-time-value (make-unportable-float
1719                                              :double-float-negative-zero)))))))
1720           ((consp high-bound)
1721            (let ((high-value (car high-bound)))
1722              (or (eql high-value low-bound)
1723                  (and (eql high-value
1724                            (load-time-value (make-unportable-float
1725                                              :single-float-negative-zero)))
1726                       (eql low-bound 0f0))
1727                  (and (eql high-value 0f0)
1728                       (eql low-bound
1729                            (load-time-value (make-unportable-float
1730                                              :single-float-negative-zero))))
1731                  (and (eql high-value
1732                            (load-time-value (make-unportable-float
1733                                              :double-float-negative-zero)))
1734                       (eql low-bound 0d0))
1735                  (and (eql high-value 0d0)
1736                       (eql low-bound
1737                            (load-time-value (make-unportable-float
1738                                              :double-float-negative-zero)))))))
1739           ((and (eq (numeric-type-class low) 'integer)
1740                 (eq (numeric-type-class high) 'integer))
1741            (eql (1+ low-bound) high-bound))
1742           (t
1743            nil))))
1744
1745 ;;; Return a numeric type that is a supertype for both TYPE1 and TYPE2.
1746 ;;;
1747 ;;; Old comment, probably no longer applicable:
1748 ;;;
1749 ;;;   ### Note: we give up early to keep from dropping lots of
1750 ;;;   information on the floor by returning overly general types.
1751 (!define-type-method (number :simple-union2) (type1 type2)
1752   (declare (type numeric-type type1 type2))
1753   (cond ((csubtypep type1 type2) type2)
1754         ((csubtypep type2 type1) type1)
1755         (t
1756          (let ((class1 (numeric-type-class type1))
1757                (format1 (numeric-type-format type1))
1758                (complexp1 (numeric-type-complexp type1))
1759                (class2 (numeric-type-class type2))
1760                (format2 (numeric-type-format type2))
1761                (complexp2 (numeric-type-complexp type2)))
1762            (cond
1763              ((and (eq class1 class2)
1764                    (eq format1 format2)
1765                    (eq complexp1 complexp2)
1766                    (or (numeric-types-intersect type1 type2)
1767                        (numeric-types-adjacent type1 type2)
1768                        (numeric-types-adjacent type2 type1)))
1769               (make-numeric-type
1770                :class class1
1771                :format format1
1772                :complexp complexp1
1773                :low (numeric-bound-max (numeric-type-low type1)
1774                                        (numeric-type-low type2)
1775                                        <= < t)
1776                :high (numeric-bound-max (numeric-type-high type1)
1777                                         (numeric-type-high type2)
1778                                         >= > t)))
1779              ;; FIXME: These two clauses are almost identical, and the
1780              ;; consequents are in fact identical in every respect.
1781              ((and (eq class1 'rational)
1782                    (eq class2 'integer)
1783                    (eq format1 format2)
1784                    (eq complexp1 complexp2)
1785                    (integerp (numeric-type-low type2))
1786                    (integerp (numeric-type-high type2))
1787                    (= (numeric-type-low type2) (numeric-type-high type2))
1788                    (or (numeric-types-adjacent type1 type2)
1789                        (numeric-types-adjacent type2 type1)))
1790               (make-numeric-type
1791                :class 'rational
1792                :format format1
1793                :complexp complexp1
1794                :low (numeric-bound-max (numeric-type-low type1)
1795                                        (numeric-type-low type2)
1796                                        <= < t)
1797                :high (numeric-bound-max (numeric-type-high type1)
1798                                         (numeric-type-high type2)
1799                                         >= > t)))
1800              ((and (eq class1 'integer)
1801                    (eq class2 'rational)
1802                    (eq format1 format2)
1803                    (eq complexp1 complexp2)
1804                    (integerp (numeric-type-low type1))
1805                    (integerp (numeric-type-high type1))
1806                    (= (numeric-type-low type1) (numeric-type-high type1))
1807                    (or (numeric-types-adjacent type1 type2)
1808                        (numeric-types-adjacent type2 type1)))
1809               (make-numeric-type
1810                :class 'rational
1811                :format format1
1812                :complexp complexp1
1813                :low (numeric-bound-max (numeric-type-low type1)
1814                                        (numeric-type-low type2)
1815                                        <= < t)
1816                :high (numeric-bound-max (numeric-type-high type1)
1817                                         (numeric-type-high type2)
1818                                         >= > t)))
1819              (t nil))))))
1820
1821
1822 (!cold-init-forms
1823   (setf (info :type :kind 'number)
1824         #+sb-xc-host :defined #-sb-xc-host :primitive)
1825   (setf (info :type :builtin 'number)
1826         (make-numeric-type :complexp nil)))
1827
1828 (!def-type-translator complex (&optional (typespec '*))
1829   (if (eq typespec '*)
1830       (specifier-type '(complex real))
1831       (labels ((not-numeric ()
1832                  (error "The component type for COMPLEX is not numeric: ~S"
1833                         typespec))
1834                (not-real ()
1835                  (error "The component type for COMPLEX is not a subtype of REAL: ~S"
1836                         typespec))
1837                (complex1 (component-type)
1838                  (unless (numeric-type-p component-type)
1839                    (not-numeric))
1840                  (when (eq (numeric-type-complexp component-type) :complex)
1841                    (not-real))
1842                  (if (csubtypep component-type (specifier-type '(eql 0)))
1843                      *empty-type*
1844                      (modified-numeric-type component-type
1845                                             :complexp :complex)))
1846                (do-complex (ctype)
1847                  (cond
1848                    ((eq ctype *empty-type*) *empty-type*)
1849                    ((eq ctype *universal-type*) (not-real))
1850                    ((typep ctype 'numeric-type) (complex1 ctype))
1851                    ((typep ctype 'union-type)
1852                     (apply #'type-union
1853                            (mapcar #'do-complex (union-type-types ctype))))
1854                    ((typep ctype 'member-type)
1855                     (apply #'type-union
1856                            (mapcar (lambda (x) (do-complex (ctype-of x)))
1857                                    (member-type-members ctype))))
1858                    ((and (typep ctype 'intersection-type)
1859                          ;; FIXME: This is very much a
1860                          ;; not-quite-worst-effort, but we are required to do
1861                          ;; something here because of our representation of
1862                          ;; RATIO as (AND RATIONAL (NOT INTEGER)): we must
1863                          ;; allow users to ask about (COMPLEX RATIO).  This
1864                          ;; will of course fail to work right on such types
1865                          ;; as (AND INTEGER (SATISFIES ZEROP))...
1866                          (let ((numbers (remove-if-not
1867                                          #'numeric-type-p
1868                                          (intersection-type-types ctype))))
1869                            (and (car numbers)
1870                                 (null (cdr numbers))
1871                                 (eq (numeric-type-complexp (car numbers)) :real)
1872                                 (complex1 (car numbers))))))
1873                    (t
1874                     (multiple-value-bind (subtypep certainly)
1875                         (csubtypep ctype (specifier-type 'real))
1876                       (if (and (not subtypep) certainly)
1877                           (not-real)
1878                           ;; ANSI just says that TYPESPEC is any subtype of
1879                           ;; type REAL, not necessarily a NUMERIC-TYPE. In
1880                           ;; particular, at this point TYPESPEC could legally
1881                           ;; be a hairy type like (AND NUMBER (SATISFIES
1882                           ;; REALP) (SATISFIES ZEROP)), in which case we fall
1883                           ;; through the logic above and end up here,
1884                           ;; stumped.
1885                           (bug "~@<(known bug #145): The type ~S is too hairy to be ~
1886 used for a COMPLEX component.~:@>"
1887                                typespec)))))))
1888         (let ((ctype (specifier-type typespec)))
1889           (do-complex ctype)))))
1890
1891 ;;; If X is *, return NIL, otherwise return the bound, which must be a
1892 ;;; member of TYPE or a one-element list of a member of TYPE.
1893 #!-sb-fluid (declaim (inline canonicalized-bound))
1894 (defun canonicalized-bound (bound type)
1895   (cond ((eq bound '*) nil)
1896         ((or (sb!xc:typep bound type)
1897              (and (consp bound)
1898                   (sb!xc:typep (car bound) type)
1899                   (null (cdr bound))))
1900           bound)
1901         (t
1902          (error "Bound is not ~S, a ~S or a list of a ~S: ~S"
1903                 '*
1904                 type
1905                 type
1906                 bound))))
1907
1908 (!def-type-translator integer (&optional (low '*) (high '*))
1909   (let* ((l (canonicalized-bound low 'integer))
1910          (lb (if (consp l) (1+ (car l)) l))
1911          (h (canonicalized-bound high 'integer))
1912          (hb (if (consp h) (1- (car h)) h)))
1913     (if (and hb lb (< hb lb))
1914         *empty-type*
1915       (make-numeric-type :class 'integer
1916                          :complexp :real
1917                          :enumerable (not (null (and l h)))
1918                          :low lb
1919                          :high hb))))
1920
1921 (defmacro !def-bounded-type (type class format)
1922   `(!def-type-translator ,type (&optional (low '*) (high '*))
1923      (let ((lb (canonicalized-bound low ',type))
1924            (hb (canonicalized-bound high ',type)))
1925        (if (not (numeric-bound-test* lb hb <= <))
1926            *empty-type*
1927          (make-numeric-type :class ',class
1928                             :format ',format
1929                             :low lb
1930                             :high hb)))))
1931
1932 (!def-bounded-type rational rational nil)
1933
1934 ;;; Unlike CMU CL, we represent the types FLOAT and REAL as
1935 ;;; UNION-TYPEs of more primitive types, in order to make
1936 ;;; type representation more unique, avoiding problems in the
1937 ;;; simplification of things like
1938 ;;;   (subtypep '(or (single-float -1.0 1.0) (single-float 0.1))
1939 ;;;             '(or (real -1 7) (single-float 0.1) (single-float -1.0 1.0)))
1940 ;;; When we allowed REAL to remain as a separate NUMERIC-TYPE,
1941 ;;; it was too easy for the first argument to be simplified to
1942 ;;; '(SINGLE-FLOAT -1.0), and for the second argument to be simplified
1943 ;;; to '(OR (REAL -1 7) (SINGLE-FLOAT 0.1)) and then for the
1944 ;;; SUBTYPEP to fail (returning NIL,T instead of T,T) because
1945 ;;; the first argument can't be seen to be a subtype of any of the
1946 ;;; terms in the second argument.
1947 ;;;
1948 ;;; The old CMU CL way was:
1949 ;;;   (!def-bounded-type float float nil)
1950 ;;;   (!def-bounded-type real nil nil)
1951 ;;;
1952 ;;; FIXME: If this new way works for a while with no weird new
1953 ;;; problems, we can go back and rip out support for separate FLOAT
1954 ;;; and REAL flavors of NUMERIC-TYPE. The new way was added in
1955 ;;; sbcl-0.6.11.22, 2001-03-21.
1956 ;;;
1957 ;;; FIXME: It's probably necessary to do something to fix the
1958 ;;; analogous problem with INTEGER and RATIONAL types. Perhaps
1959 ;;; bounded RATIONAL types should be represented as (OR RATIO INTEGER).
1960 (defun coerce-bound (bound type upperp inner-coerce-bound-fun)
1961   (declare (type function inner-coerce-bound-fun))
1962   (if (eql bound '*)
1963       bound
1964       (funcall inner-coerce-bound-fun bound type upperp)))
1965 (defun inner-coerce-real-bound (bound type upperp)
1966   #+sb-xc-host (declare (ignore upperp))
1967   (let #+sb-xc-host ()
1968        #-sb-xc-host
1969        ((nl (load-time-value (symbol-value 'sb!xc:most-negative-long-float)))
1970         (pl (load-time-value (symbol-value 'sb!xc:most-positive-long-float))))
1971     (let ((nbound (if (consp bound) (car bound) bound))
1972           (consp (consp bound)))
1973       (ecase type
1974         (rational
1975          (if consp
1976              (list (rational nbound))
1977              (rational nbound)))
1978         (float
1979          (cond
1980            ((floatp nbound) bound)
1981            (t
1982             ;; Coerce to the widest float format available, to avoid
1983             ;; unnecessary loss of precision, but don't coerce
1984             ;; unrepresentable numbers, except on the host where we
1985             ;; shouldn't be making these types (but KLUDGE: can't even
1986             ;; assert portably that we're not).
1987             #-sb-xc-host
1988             (ecase upperp
1989               ((nil)
1990                (when (< nbound nl) (return-from inner-coerce-real-bound nl)))
1991               ((t)
1992                (when (> nbound pl) (return-from inner-coerce-real-bound pl))))
1993             (let ((result (coerce nbound 'long-float)))
1994               (if consp (list result) result)))))))))
1995 (defun inner-coerce-float-bound (bound type upperp)
1996   #+sb-xc-host (declare (ignore upperp))
1997   (let #+sb-xc-host ()
1998        #-sb-xc-host
1999        ((nd (load-time-value (symbol-value 'sb!xc:most-negative-double-float)))
2000         (pd (load-time-value (symbol-value 'sb!xc:most-positive-double-float)))
2001         (ns (load-time-value (symbol-value 'sb!xc:most-negative-single-float)))
2002         (ps (load-time-value
2003              (symbol-value 'sb!xc:most-positive-single-float))))
2004     (let ((nbound (if (consp bound) (car bound) bound))
2005           (consp (consp bound)))
2006       (ecase type
2007         (single-float
2008          (cond
2009            ((typep nbound 'single-float) bound)
2010            (t
2011             #-sb-xc-host
2012             (ecase upperp
2013               ((nil)
2014                (when (< nbound ns) (return-from inner-coerce-float-bound ns)))
2015               ((t)
2016                (when (> nbound ps) (return-from inner-coerce-float-bound ps))))
2017             (let ((result (coerce nbound 'single-float)))
2018               (if consp (list result) result)))))
2019         (double-float
2020          (cond
2021            ((typep nbound 'double-float) bound)
2022            (t
2023             #-sb-xc-host
2024             (ecase upperp
2025               ((nil)
2026                (when (< nbound nd) (return-from inner-coerce-float-bound nd)))
2027               ((t)
2028                (when (> nbound pd) (return-from inner-coerce-float-bound pd))))
2029             (let ((result (coerce nbound 'double-float)))
2030               (if consp (list result) result)))))))))
2031 (defun coerced-real-bound (bound type upperp)
2032   (coerce-bound bound type upperp #'inner-coerce-real-bound))
2033 (defun coerced-float-bound (bound type upperp)
2034   (coerce-bound bound type upperp #'inner-coerce-float-bound))
2035 (!def-type-translator real (&optional (low '*) (high '*))
2036   (specifier-type `(or (float ,(coerced-real-bound  low 'float nil)
2037                               ,(coerced-real-bound high 'float t))
2038                        (rational ,(coerced-real-bound  low 'rational nil)
2039                                  ,(coerced-real-bound high 'rational t)))))
2040 (!def-type-translator float (&optional (low '*) (high '*))
2041   (specifier-type
2042    `(or (single-float ,(coerced-float-bound  low 'single-float nil)
2043                       ,(coerced-float-bound high 'single-float t))
2044         (double-float ,(coerced-float-bound  low 'double-float nil)
2045                       ,(coerced-float-bound high 'double-float t))
2046         #!+long-float ,(error "stub: no long float support yet"))))
2047
2048 (defmacro !define-float-format (f)
2049   `(!def-bounded-type ,f float ,f))
2050
2051 (!define-float-format short-float)
2052 (!define-float-format single-float)
2053 (!define-float-format double-float)
2054 (!define-float-format long-float)
2055
2056 (defun numeric-types-intersect (type1 type2)
2057   (declare (type numeric-type type1 type2))
2058   (let* ((class1 (numeric-type-class type1))
2059          (class2 (numeric-type-class type2))
2060          (complexp1 (numeric-type-complexp type1))
2061          (complexp2 (numeric-type-complexp type2))
2062          (format1 (numeric-type-format type1))
2063          (format2 (numeric-type-format type2))
2064          (low1 (numeric-type-low type1))
2065          (high1 (numeric-type-high type1))
2066          (low2 (numeric-type-low type2))
2067          (high2 (numeric-type-high type2)))
2068     ;; If one is complex and the other isn't, then they are disjoint.
2069     (cond ((not (or (eq complexp1 complexp2)
2070                     (null complexp1) (null complexp2)))
2071            nil)
2072           ;; If either type is a float, then the other must either be
2073           ;; specified to be a float or unspecified. Otherwise, they
2074           ;; are disjoint.
2075           ((and (eq class1 'float)
2076                 (not (member class2 '(float nil)))) nil)
2077           ((and (eq class2 'float)
2078                 (not (member class1 '(float nil)))) nil)
2079           ;; If the float formats are specified and different, the
2080           ;; types are disjoint.
2081           ((not (or (eq format1 format2) (null format1) (null format2)))
2082            nil)
2083           (t
2084            ;; Check the bounds. This is a bit odd because we must
2085            ;; always have the outer bound of the interval as the
2086            ;; second arg.
2087            (if (numeric-bound-test high1 high2 <= <)
2088                (or (and (numeric-bound-test low1 low2 >= >)
2089                         (numeric-bound-test* low1 high2 <= <))
2090                    (and (numeric-bound-test low2 low1 >= >)
2091                         (numeric-bound-test* low2 high1 <= <)))
2092                (or (and (numeric-bound-test* low2 high1 <= <)
2093                         (numeric-bound-test low2 low1 >= >))
2094                    (and (numeric-bound-test high2 high1 <= <)
2095                         (numeric-bound-test* high2 low1 >= >))))))))
2096
2097 ;;; Take the numeric bound X and convert it into something that can be
2098 ;;; used as a bound in a numeric type with the specified CLASS and
2099 ;;; FORMAT. If UP-P is true, then we round up as needed, otherwise we
2100 ;;; round down. UP-P true implies that X is a lower bound, i.e. (N) > N.
2101 ;;;
2102 ;;; This is used by NUMERIC-TYPE-INTERSECTION to mash the bound into
2103 ;;; the appropriate type number. X may only be a float when CLASS is
2104 ;;; FLOAT.
2105 ;;;
2106 ;;; ### Note: it is possible for the coercion to a float to overflow
2107 ;;; or underflow. This happens when the bound doesn't fit in the
2108 ;;; specified format. In this case, we should really return the
2109 ;;; appropriate {Most | Least}-{Positive | Negative}-XXX-Float float
2110 ;;; of desired format. But these conditions aren't currently signalled
2111 ;;; in any useful way.
2112 ;;;
2113 ;;; Also, when converting an open rational bound into a float we
2114 ;;; should probably convert it to a closed bound of the closest float
2115 ;;; in the specified format. KLUDGE: In general, open float bounds are
2116 ;;; screwed up. -- (comment from original CMU CL)
2117 (defun round-numeric-bound (x class format up-p)
2118   (if x
2119       (let ((cx (if (consp x) (car x) x)))
2120         (ecase class
2121           ((nil rational) x)
2122           (integer
2123            (if (and (consp x) (integerp cx))
2124                (if up-p (1+ cx) (1- cx))
2125                (if up-p (ceiling cx) (floor cx))))
2126           (float
2127            (let ((res
2128                   (cond
2129                     ((and format (subtypep format 'double-float))
2130                      (if (<= most-negative-double-float cx most-positive-double-float)
2131                          (coerce cx format)
2132                          nil))
2133                     (t
2134                      (if (<= most-negative-single-float cx most-positive-single-float)
2135                          ;; FIXME: bug #389
2136                          (coerce cx (or format 'single-float))
2137                          nil)))))
2138              (if (consp x) (list res) res)))))
2139       nil))
2140
2141 ;;; Handle the case of type intersection on two numeric types. We use
2142 ;;; TYPES-EQUAL-OR-INTERSECT to throw out the case of types with no
2143 ;;; intersection. If an attribute in TYPE1 is unspecified, then we use
2144 ;;; TYPE2's attribute, which must be at least as restrictive. If the
2145 ;;; types intersect, then the only attributes that can be specified
2146 ;;; and different are the class and the bounds.
2147 ;;;
2148 ;;; When the class differs, we use the more restrictive class. The
2149 ;;; only interesting case is RATIONAL/INTEGER, since RATIONAL includes
2150 ;;; INTEGER.
2151 ;;;
2152 ;;; We make the result lower (upper) bound the maximum (minimum) of
2153 ;;; the argument lower (upper) bounds. We convert the bounds into the
2154 ;;; appropriate numeric type before maximizing. This avoids possible
2155 ;;; confusion due to mixed-type comparisons (but I think the result is
2156 ;;; the same).
2157 (!define-type-method (number :simple-intersection2) (type1 type2)
2158   (declare (type numeric-type type1 type2))
2159   (if (numeric-types-intersect type1 type2)
2160       (let* ((class1 (numeric-type-class type1))
2161              (class2 (numeric-type-class type2))
2162              (class (ecase class1
2163                       ((nil) class2)
2164                       ((integer float) class1)
2165                       (rational (if (eq class2 'integer)
2166                                        'integer
2167                                        'rational))))
2168              (format (or (numeric-type-format type1)
2169                          (numeric-type-format type2))))
2170         (make-numeric-type
2171          :class class
2172          :format format
2173          :complexp (or (numeric-type-complexp type1)
2174                        (numeric-type-complexp type2))
2175          :low (numeric-bound-max
2176                (round-numeric-bound (numeric-type-low type1)
2177                                     class format t)
2178                (round-numeric-bound (numeric-type-low type2)
2179                                     class format t)
2180                > >= nil)
2181          :high (numeric-bound-max
2182                 (round-numeric-bound (numeric-type-high type1)
2183                                      class format nil)
2184                 (round-numeric-bound (numeric-type-high type2)
2185                                      class format nil)
2186                 < <= nil)))
2187       *empty-type*))
2188
2189 ;;; Given two float formats, return the one with more precision. If
2190 ;;; either one is null, return NIL.
2191 (defun float-format-max (f1 f2)
2192   (when (and f1 f2)
2193     (dolist (f *float-formats* (error "bad float format: ~S" f1))
2194       (when (or (eq f f1) (eq f f2))
2195         (return f)))))
2196
2197 ;;; Return the result of an operation on TYPE1 and TYPE2 according to
2198 ;;; the rules of numeric contagion. This is always NUMBER, some float
2199 ;;; format (possibly complex) or RATIONAL. Due to rational
2200 ;;; canonicalization, there isn't much we can do here with integers or
2201 ;;; rational complex numbers.
2202 ;;;
2203 ;;; If either argument is not a NUMERIC-TYPE, then return NUMBER. This
2204 ;;; is useful mainly for allowing types that are technically numbers,
2205 ;;; but not a NUMERIC-TYPE.
2206 (defun numeric-contagion (type1 type2)
2207   (if (and (numeric-type-p type1) (numeric-type-p type2))
2208       (let ((class1 (numeric-type-class type1))
2209             (class2 (numeric-type-class type2))
2210             (format1 (numeric-type-format type1))
2211             (format2 (numeric-type-format type2))
2212             (complexp1 (numeric-type-complexp type1))
2213             (complexp2 (numeric-type-complexp type2)))
2214         (cond ((or (null complexp1)
2215                    (null complexp2))
2216                (specifier-type 'number))
2217               ((eq class1 'float)
2218                (make-numeric-type
2219                 :class 'float
2220                 :format (ecase class2
2221                           (float (float-format-max format1 format2))
2222                           ((integer rational) format1)
2223                           ((nil)
2224                            ;; A double-float with any real number is a
2225                            ;; double-float.
2226                            #!-long-float
2227                            (if (eq format1 'double-float)
2228                              'double-float
2229                              nil)
2230                            ;; A long-float with any real number is a
2231                            ;; long-float.
2232                            #!+long-float
2233                            (if (eq format1 'long-float)
2234                              'long-float
2235                              nil)))
2236                 :complexp (if (or (eq complexp1 :complex)
2237                                   (eq complexp2 :complex))
2238                               :complex
2239                               :real)))
2240               ((eq class2 'float) (numeric-contagion type2 type1))
2241               ((and (eq complexp1 :real) (eq complexp2 :real))
2242                (make-numeric-type
2243                 :class (and class1 class2 'rational)
2244                 :complexp :real))
2245               (t
2246                (specifier-type 'number))))
2247       (specifier-type 'number)))
2248 \f
2249 ;;;; array types
2250
2251 (!define-type-class array)
2252
2253 ;;; What this does depends on the setting of the
2254 ;;; *USE-IMPLEMENTATION-TYPES* switch. If true, return the specialized
2255 ;;; element type, otherwise return the original element type.
2256 (defun specialized-element-type-maybe (type)
2257   (declare (type array-type type))
2258   (if *use-implementation-types*
2259       (array-type-specialized-element-type type)
2260       (array-type-element-type type)))
2261
2262 (!define-type-method (array :simple-=) (type1 type2)
2263   (cond ((not (and (equal (array-type-dimensions type1)
2264                           (array-type-dimensions type2))
2265                    (eq (array-type-complexp type1)
2266                        (array-type-complexp type2))))
2267          (values nil t))
2268         ((or (unknown-type-p (array-type-element-type type1))
2269              (unknown-type-p (array-type-element-type type2)))
2270          (multiple-value-bind (equalp certainp)
2271              (type= (array-type-element-type type1)
2272                     (array-type-element-type type2))
2273            ;; By its nature, the call to TYPE= should never return
2274            ;; NIL, T, as we don't know what the UNKNOWN-TYPE will grow
2275            ;; up to be.  -- CSR, 2002-08-19
2276            (aver (not (and (not equalp) certainp)))
2277            (values equalp certainp)))
2278         (t
2279          (values (type= (specialized-element-type-maybe type1)
2280                         (specialized-element-type-maybe type2))
2281                  t))))
2282
2283 (!define-type-method (array :negate) (type)
2284   ;; FIXME (and hint to PFD): we're vulnerable here to attacks of the
2285   ;; form "are (AND ARRAY (NOT (ARRAY T))) and (OR (ARRAY BIT) (ARRAY
2286   ;; NIL) (ARRAY CHAR) ...) equivalent?" -- CSR, 2003-12-10
2287   (make-negation-type :type type))
2288
2289 (!define-type-method (array :unparse) (type)
2290   (let ((dims (array-type-dimensions type))
2291         (eltype (type-specifier (array-type-element-type type)))
2292         (complexp (array-type-complexp type)))
2293     (cond ((eq dims '*)
2294            (if (eq eltype '*)
2295                (if complexp 'array 'simple-array)
2296                (if complexp `(array ,eltype) `(simple-array ,eltype))))
2297           ((= (length dims) 1)
2298            (if complexp
2299                (if (eq (car dims) '*)
2300                    (case eltype
2301                      (bit 'bit-vector)
2302                      ((base-char #!-sb-unicode character) 'base-string)
2303                      (* 'vector)
2304                      (t `(vector ,eltype)))
2305                    (case eltype
2306                      (bit `(bit-vector ,(car dims)))
2307                      ((base-char #!-sb-unicode character)
2308                       `(base-string ,(car dims)))
2309                      (t `(vector ,eltype ,(car dims)))))
2310                (if (eq (car dims) '*)
2311                    (case eltype
2312                      (bit 'simple-bit-vector)
2313                      ((base-char #!-sb-unicode character) 'simple-base-string)
2314                      ((t) 'simple-vector)
2315                      (t `(simple-array ,eltype (*))))
2316                    (case eltype
2317                      (bit `(simple-bit-vector ,(car dims)))
2318                      ((base-char #!-sb-unicode character)
2319                       `(simple-base-string ,(car dims)))
2320                      ((t) `(simple-vector ,(car dims)))
2321                      (t `(simple-array ,eltype ,dims))))))
2322           (t
2323            (if complexp
2324                `(array ,eltype ,dims)
2325                `(simple-array ,eltype ,dims))))))
2326
2327 (!define-type-method (array :simple-subtypep) (type1 type2)
2328   (let ((dims1 (array-type-dimensions type1))
2329         (dims2 (array-type-dimensions type2))
2330         (complexp2 (array-type-complexp type2)))
2331     (cond (;; not subtypep unless dimensions are compatible
2332            (not (or (eq dims2 '*)
2333                     (and (not (eq dims1 '*))
2334                          ;; (sbcl-0.6.4 has trouble figuring out that
2335                          ;; DIMS1 and DIMS2 must be lists at this
2336                          ;; point, and knowing that is important to
2337                          ;; compiling EVERY efficiently.)
2338                          (= (length (the list dims1))
2339                             (length (the list dims2)))
2340                          (every (lambda (x y)
2341                                   (or (eq y '*) (eql x y)))
2342                                 (the list dims1)
2343                                 (the list dims2)))))
2344            (values nil t))
2345           ;; not subtypep unless complexness is compatible
2346           ((not (or (eq complexp2 :maybe)
2347                     (eq (array-type-complexp type1) complexp2)))
2348            (values nil t))
2349           ;; Since we didn't fail any of the tests above, we win
2350           ;; if the TYPE2 element type is wild.
2351           ((eq (array-type-element-type type2) *wild-type*)
2352            (values t t))
2353           (;; Since we didn't match any of the special cases above, if
2354            ;; either element type is unknown we can only give a good
2355            ;; answer if they are the same.
2356            (or (unknown-type-p (array-type-element-type type1))
2357                (unknown-type-p (array-type-element-type type2)))
2358            (if (type= (array-type-element-type type1)
2359                       (array-type-element-type type2))
2360                (values t t)
2361                (values nil nil)))
2362           (;; Otherwise, the subtype relationship holds iff the
2363            ;; types are equal, and they're equal iff the specialized
2364            ;; element types are identical.
2365            t
2366            (values (type= (specialized-element-type-maybe type1)
2367                           (specialized-element-type-maybe type2))
2368                    t)))))
2369
2370 ;;; FIXME: is this dead?
2371 (!define-superclasses array
2372   ((base-string base-string)
2373    (vector vector)
2374    (array))
2375   !cold-init-forms)
2376
2377 (defun array-types-intersect (type1 type2)
2378   (declare (type array-type type1 type2))
2379   (let ((dims1 (array-type-dimensions type1))
2380         (dims2 (array-type-dimensions type2))
2381         (complexp1 (array-type-complexp type1))
2382         (complexp2 (array-type-complexp type2)))
2383     ;; See whether dimensions are compatible.
2384     (cond ((not (or (eq dims1 '*) (eq dims2 '*)
2385                     (and (= (length dims1) (length dims2))
2386                          (every (lambda (x y)
2387                                   (or (eq x '*) (eq y '*) (= x y)))
2388                                 dims1 dims2))))
2389            (values nil t))
2390           ;; See whether complexpness is compatible.
2391           ((not (or (eq complexp1 :maybe)
2392                     (eq complexp2 :maybe)
2393                     (eq complexp1 complexp2)))
2394            (values nil t))
2395           ;; Old comment:
2396           ;;
2397           ;;   If either element type is wild, then they intersect.
2398           ;;   Otherwise, the types must be identical.
2399           ;;
2400           ;; FIXME: There seems to have been a fair amount of
2401           ;; confusion about the distinction between requested element
2402           ;; type and specialized element type; here is one of
2403           ;; them. If we request an array to hold objects of an
2404           ;; unknown type, we can do no better than represent that
2405           ;; type as an array specialized on wild-type.  We keep the
2406           ;; requested element-type in the -ELEMENT-TYPE slot, and
2407           ;; *WILD-TYPE* in the -SPECIALIZED-ELEMENT-TYPE.  So, here,
2408           ;; we must test for the SPECIALIZED slot being *WILD-TYPE*,
2409           ;; not just the ELEMENT-TYPE slot.  Maybe the return value
2410           ;; in that specific case should be T, NIL?  Or maybe this
2411           ;; function should really be called
2412           ;; ARRAY-TYPES-COULD-POSSIBLY-INTERSECT?  In any case, this
2413           ;; was responsible for bug #123, and this whole issue could
2414           ;; do with a rethink and/or a rewrite.  -- CSR, 2002-08-21
2415           ((or (eq (array-type-specialized-element-type type1) *wild-type*)
2416                (eq (array-type-specialized-element-type type2) *wild-type*)
2417                (type= (specialized-element-type-maybe type1)
2418                       (specialized-element-type-maybe type2)))
2419
2420            (values t t))
2421           (t
2422            (values nil t)))))
2423
2424 (!define-type-method (array :simple-intersection2) (type1 type2)
2425   (declare (type array-type type1 type2))
2426   (if (array-types-intersect type1 type2)
2427       (let ((dims1 (array-type-dimensions type1))
2428             (dims2 (array-type-dimensions type2))
2429             (complexp1 (array-type-complexp type1))
2430             (complexp2 (array-type-complexp type2))
2431             (eltype1 (array-type-element-type type1))
2432             (eltype2 (array-type-element-type type2)))
2433         (specialize-array-type
2434          (make-array-type
2435           :dimensions (cond ((eq dims1 '*) dims2)
2436                             ((eq dims2 '*) dims1)
2437                             (t
2438                              (mapcar (lambda (x y) (if (eq x '*) y x))
2439                                      dims1 dims2)))
2440           :complexp (if (eq complexp1 :maybe) complexp2 complexp1)
2441           :element-type (cond
2442                           ((eq eltype1 *wild-type*) eltype2)
2443                           ((eq eltype2 *wild-type*) eltype1)
2444                           (t (type-intersection eltype1 eltype2))))))
2445       *empty-type*))
2446
2447 ;;; Check a supplied dimension list to determine whether it is legal,
2448 ;;; and return it in canonical form (as either '* or a list).
2449 (defun canonical-array-dimensions (dims)
2450   (typecase dims
2451     ((member *) dims)
2452     (integer
2453      (when (minusp dims)
2454        (error "Arrays can't have a negative number of dimensions: ~S" dims))
2455      (when (>= dims sb!xc:array-rank-limit)
2456        (error "array type with too many dimensions: ~S" dims))
2457      (make-list dims :initial-element '*))
2458     (list
2459      (when (>= (length dims) sb!xc:array-rank-limit)
2460        (error "array type with too many dimensions: ~S" dims))
2461      (dolist (dim dims)
2462        (unless (eq dim '*)
2463          (unless (and (integerp dim)
2464                       (>= dim 0)
2465                       (< dim sb!xc:array-dimension-limit))
2466            (error "bad dimension in array type: ~S" dim))))
2467      dims)
2468     (t
2469      (error "Array dimensions is not a list, integer or *:~%  ~S" dims))))
2470 \f
2471 ;;;; MEMBER types
2472
2473 (!define-type-class member)
2474
2475 (!define-type-method (member :negate) (type)
2476   (let ((members (member-type-members type)))
2477     (if (some #'floatp members)
2478         (let (floats)
2479           (dolist (pair `((0.0f0 . ,(load-time-value (make-unportable-float :single-float-negative-zero)))
2480                           (0.0d0 . ,(load-time-value (make-unportable-float :double-float-negative-zero)))
2481                           #!+long-float
2482                           (0.0l0 . ,(load-time-value (make-unportable-float :long-float-negative-zero)))))
2483             (when (member (car pair) members)
2484               (aver (not (member (cdr pair) members)))
2485               (push (cdr pair) floats)
2486               (setf members (remove (car pair) members)))
2487             (when (member (cdr pair) members)
2488               (aver (not (member (car pair) members)))
2489               (push (car pair) floats)
2490               (setf members (remove (cdr pair) members))))
2491           (apply #'type-intersection
2492                  (if (null members)
2493                      *universal-type*
2494                      (make-negation-type
2495                       :type (make-member-type :members members)))
2496                  (mapcar
2497                   (lambda (x)
2498                     (let ((type (ctype-of x)))
2499                       (type-union
2500                        (make-negation-type
2501                         :type (modified-numeric-type type
2502                                                      :low nil :high nil))
2503                        (modified-numeric-type type
2504                                               :low nil :high (list x))
2505                        (make-member-type :members (list x))
2506                        (modified-numeric-type type
2507                                               :low (list x) :high nil))))
2508                   floats)))
2509         (make-negation-type :type type))))
2510
2511 (!define-type-method (member :unparse) (type)
2512   (let ((members (member-type-members type)))
2513     (cond
2514       ((equal members '(nil)) 'null)
2515       ((type= type (specifier-type 'standard-char)) 'standard-char)
2516       (t `(member ,@members)))))
2517
2518 (!define-type-method (member :simple-subtypep) (type1 type2)
2519   (values (subsetp (member-type-members type1) (member-type-members type2))
2520           t))
2521
2522 (!define-type-method (member :complex-subtypep-arg1) (type1 type2)
2523   (every/type (swapped-args-fun #'ctypep)
2524               type2
2525               (member-type-members type1)))
2526
2527 ;;; We punt if the odd type is enumerable and intersects with the
2528 ;;; MEMBER type. If not enumerable, then it is definitely not a
2529 ;;; subtype of the MEMBER type.
2530 (!define-type-method (member :complex-subtypep-arg2) (type1 type2)
2531   (cond ((not (type-enumerable type1)) (values nil t))
2532         ((types-equal-or-intersect type1 type2)
2533          (invoke-complex-subtypep-arg1-method type1 type2))
2534         (t (values nil t))))
2535
2536 (!define-type-method (member :simple-intersection2) (type1 type2)
2537   (let ((mem1 (member-type-members type1))
2538         (mem2 (member-type-members type2)))
2539     (cond ((subsetp mem1 mem2) type1)
2540           ((subsetp mem2 mem1) type2)
2541           (t
2542            (let ((res (intersection mem1 mem2)))
2543              (if res
2544                  (make-member-type :members res)
2545                  *empty-type*))))))
2546
2547 (!define-type-method (member :complex-intersection2) (type1 type2)
2548   (block punt
2549     (collect ((members))
2550       (let ((mem2 (member-type-members type2)))
2551         (dolist (member mem2)
2552           (multiple-value-bind (val win) (ctypep member type1)
2553             (unless win
2554               (return-from punt nil))
2555             (when val (members member))))
2556         (cond ((subsetp mem2 (members)) type2)
2557               ((null (members)) *empty-type*)
2558               (t
2559                (make-member-type :members (members))))))))
2560
2561 ;;; We don't need a :COMPLEX-UNION2, since the only interesting case is
2562 ;;; a union type, and the member/union interaction is handled by the
2563 ;;; union type method.
2564 (!define-type-method (member :simple-union2) (type1 type2)
2565   (let ((mem1 (member-type-members type1))
2566         (mem2 (member-type-members type2)))
2567     (cond ((subsetp mem1 mem2) type2)
2568           ((subsetp mem2 mem1) type1)
2569           (t
2570            (make-member-type :members (union mem1 mem2))))))
2571
2572 (!define-type-method (member :simple-=) (type1 type2)
2573   (let ((mem1 (member-type-members type1))
2574         (mem2 (member-type-members type2)))
2575     (values (and (subsetp mem1 mem2)
2576                  (subsetp mem2 mem1))
2577             t)))
2578
2579 (!define-type-method (member :complex-=) (type1 type2)
2580   (if (type-enumerable type1)
2581       (multiple-value-bind (val win) (csubtypep type2 type1)
2582         (if (or val (not win))
2583             (values nil nil)
2584             (values nil t)))
2585       (values nil t)))
2586
2587 (!def-type-translator member (&rest members)
2588   (if members
2589       (let (ms numbers char-codes)
2590         (dolist (m (remove-duplicates members))
2591           (typecase m
2592             (float (if (zerop m)
2593                        (push m ms)
2594                        (push (ctype-of m) numbers)))
2595             (real (push (ctype-of m) numbers))
2596            (character (push (sb!xc:char-code m) char-codes))
2597             (t (push m ms))))
2598         (apply #'type-union
2599                (if ms
2600                    (make-member-type :members ms)
2601                    *empty-type*)
2602               (if char-codes
2603                   (make-character-set-type
2604                    :pairs (mapcar (lambda (x) (cons x x))
2605                                   (sort char-codes #'<)))
2606                   *empty-type*)
2607                (nreverse numbers)))
2608       *empty-type*))
2609 \f
2610 ;;;; intersection types
2611 ;;;;
2612 ;;;; Until version 0.6.10.6, SBCL followed the original CMU CL approach
2613 ;;;; of punting on all AND types, not just the unreasonably complicated
2614 ;;;; ones. The change was motivated by trying to get the KEYWORD type
2615 ;;;; to behave sensibly:
2616 ;;;;    ;; reasonable definition
2617 ;;;;    (DEFTYPE KEYWORD () '(AND SYMBOL (SATISFIES KEYWORDP)))
2618 ;;;;    ;; reasonable behavior
2619 ;;;;    (AVER (SUBTYPEP 'KEYWORD 'SYMBOL))
2620 ;;;; Without understanding a little about the semantics of AND, we'd
2621 ;;;; get (SUBTYPEP 'KEYWORD 'SYMBOL)=>NIL,NIL and, for entirely
2622 ;;;; parallel reasons, (SUBTYPEP 'RATIO 'NUMBER)=>NIL,NIL. That's
2623 ;;;; not so good..)
2624 ;;;;
2625 ;;;; We still follow the example of CMU CL to some extent, by punting
2626 ;;;; (to the opaque HAIRY-TYPE) on sufficiently complicated types
2627 ;;;; involving AND.
2628
2629 (!define-type-class intersection)
2630
2631 (!define-type-method (intersection :negate) (type)
2632   (apply #'type-union
2633          (mapcar #'type-negation (intersection-type-types type))))
2634
2635 ;;; A few intersection types have special names. The others just get
2636 ;;; mechanically unparsed.
2637 (!define-type-method (intersection :unparse) (type)
2638   (declare (type ctype type))
2639   (or (find type '(ratio keyword) :key #'specifier-type :test #'type=)
2640       `(and ,@(mapcar #'type-specifier (intersection-type-types type)))))
2641
2642 ;;; shared machinery for type equality: true if every type in the set
2643 ;;; TYPES1 matches a type in the set TYPES2 and vice versa
2644 (defun type=-set (types1 types2)
2645   (flet ((type<=-set (x y)
2646            (declare (type list x y))
2647            (every/type (lambda (x y-element)
2648                          (any/type #'type= y-element x))
2649                        x y)))
2650     (and/type (type<=-set types1 types2)
2651               (type<=-set types2 types1))))
2652
2653 ;;; Two intersection types are equal if their subtypes are equal sets.
2654 ;;;
2655 ;;; FIXME: Might it be better to use
2656 ;;;   (AND (SUBTYPEP X Y) (SUBTYPEP Y X))
2657 ;;; instead, since SUBTYPEP is the usual relationship that we care
2658 ;;; most about, so it would be good to leverage any ingenuity there
2659 ;;; in this more obscure method?
2660 (!define-type-method (intersection :simple-=) (type1 type2)
2661   (type=-set (intersection-type-types type1)
2662              (intersection-type-types type2)))
2663
2664 (defun %intersection-complex-subtypep-arg1 (type1 type2)
2665   (type= type1 (type-intersection type1 type2)))
2666
2667 (defun %intersection-simple-subtypep (type1 type2)
2668   (every/type #'%intersection-complex-subtypep-arg1
2669               type1
2670               (intersection-type-types type2)))
2671
2672 (!define-type-method (intersection :simple-subtypep) (type1 type2)
2673   (%intersection-simple-subtypep type1 type2))
2674
2675 (!define-type-method (intersection :complex-subtypep-arg1) (type1 type2)
2676   (%intersection-complex-subtypep-arg1 type1 type2))
2677
2678 (defun %intersection-complex-subtypep-arg2 (type1 type2)
2679   (every/type #'csubtypep type1 (intersection-type-types type2)))
2680
2681 (!define-type-method (intersection :complex-subtypep-arg2) (type1 type2)
2682   (%intersection-complex-subtypep-arg2 type1 type2))
2683
2684 ;;; FIXME: This will look eeriely familiar to readers of the UNION
2685 ;;; :SIMPLE-INTERSECTION2 :COMPLEX-INTERSECTION2 method.  That's
2686 ;;; because it was generated by cut'n'paste methods.  Given that
2687 ;;; intersections and unions have all sorts of symmetries known to
2688 ;;; mathematics, it shouldn't be beyond the ken of some programmers to
2689 ;;; reflect those symmetries in code in a way that ties them together
2690 ;;; more strongly than having two independent near-copies :-/
2691 (!define-type-method (intersection :simple-union2 :complex-union2)
2692                      (type1 type2)
2693   ;; Within this method, type2 is guaranteed to be an intersection
2694   ;; type:
2695   (aver (intersection-type-p type2))
2696   ;; Make sure to call only the applicable methods...
2697   (cond ((and (intersection-type-p type1)
2698               (%intersection-simple-subtypep type1 type2)) type2)
2699         ((and (intersection-type-p type1)
2700               (%intersection-simple-subtypep type2 type1)) type1)
2701         ((and (not (intersection-type-p type1))
2702               (%intersection-complex-subtypep-arg2 type1 type2))
2703          type2)
2704         ((and (not (intersection-type-p type1))
2705               (%intersection-complex-subtypep-arg1 type2 type1))
2706          type1)
2707         ;; KLUDGE: This special (and somewhat hairy) magic is required
2708         ;; to deal with the RATIONAL/INTEGER special case.  The UNION
2709         ;; of (INTEGER * -1) and (AND (RATIONAL * -1/2) (NOT INTEGER))
2710         ;; should be (RATIONAL * -1/2) -- CSR, 2003-02-28
2711         ((and (csubtypep type2 (specifier-type 'ratio))
2712               (numeric-type-p type1)
2713               (csubtypep type1 (specifier-type 'integer))
2714               (csubtypep type2
2715                          (make-numeric-type
2716                           :class 'rational
2717                           :complexp nil
2718                           :low (if (null (numeric-type-low type1))
2719                                    nil
2720                                    (list (1- (numeric-type-low type1))))
2721                           :high (if (null (numeric-type-high type1))
2722                                     nil
2723                                     (list (1+ (numeric-type-high type1)))))))
2724          (type-union type1
2725                      (apply #'type-intersection
2726                             (remove (specifier-type '(not integer))
2727                                     (intersection-type-types type2)
2728                                     :test #'type=))))
2729         (t
2730          (let ((accumulator *universal-type*))
2731            (do ((t2s (intersection-type-types type2) (cdr t2s)))
2732                ((null t2s) accumulator)
2733              (let ((union (type-union type1 (car t2s))))
2734                (when (union-type-p union)
2735                  ;; we have to give up here -- there are all sorts of
2736                  ;; ordering worries, but it's better than before.
2737                  ;; Doing exactly the same as in the UNION
2738                  ;; :SIMPLE/:COMPLEX-INTERSECTION2 method causes stack
2739                  ;; overflow with the mutual recursion never bottoming
2740                  ;; out.
2741                  (if (and (eq accumulator *universal-type*)
2742                           (null (cdr t2s)))
2743                      ;; KLUDGE: if we get here, we have a partially
2744                      ;; simplified result.  While this isn't by any
2745                      ;; means a universal simplification, including
2746                      ;; this logic here means that we can get (OR
2747                      ;; KEYWORD (NOT KEYWORD)) canonicalized to T.
2748                      (return union)
2749                      (return nil)))
2750                (setf accumulator
2751                      (type-intersection accumulator union))))))))
2752
2753 (!def-type-translator and (&whole whole &rest type-specifiers)
2754   (apply #'type-intersection
2755          (mapcar #'specifier-type type-specifiers)))
2756 \f
2757 ;;;; union types
2758
2759 (!define-type-class union)
2760
2761 (!define-type-method (union :negate) (type)
2762   (declare (type ctype type))
2763   (apply #'type-intersection
2764          (mapcar #'type-negation (union-type-types type))))
2765
2766 ;;; The LIST, FLOAT and REAL types have special names.  Other union
2767 ;;; types just get mechanically unparsed.
2768 (!define-type-method (union :unparse) (type)
2769   (declare (type ctype type))
2770   (cond
2771     ((type= type (specifier-type 'list)) 'list)
2772     ((type= type (specifier-type 'float)) 'float)
2773     ((type= type (specifier-type 'real)) 'real)
2774     ((type= type (specifier-type 'sequence)) 'sequence)
2775     ((type= type (specifier-type 'bignum)) 'bignum)
2776     ((type= type (specifier-type 'simple-string)) 'simple-string)
2777     ((type= type (specifier-type 'string)) 'string)
2778     ((type= type (specifier-type 'complex)) 'complex)
2779     ((type= type (specifier-type 'standard-char)) 'standard-char)
2780     (t `(or ,@(mapcar #'type-specifier (union-type-types type))))))
2781
2782 ;;; Two union types are equal if they are each subtypes of each
2783 ;;; other. We need to be this clever because our complex subtypep
2784 ;;; methods are now more accurate; we don't get infinite recursion
2785 ;;; because the simple-subtypep method delegates to complex-subtypep
2786 ;;; of the individual types of type1. - CSR, 2002-04-09
2787 ;;;
2788 ;;; Previous comment, now obsolete, but worth keeping around because
2789 ;;; it is true, though too strong a condition:
2790 ;;;
2791 ;;; Two union types are equal if their subtypes are equal sets.
2792 (!define-type-method (union :simple-=) (type1 type2)
2793   (multiple-value-bind (subtype certain?)
2794       (csubtypep type1 type2)
2795     (if subtype
2796         (csubtypep type2 type1)
2797         ;; we might as well become as certain as possible.
2798         (if certain?
2799             (values nil t)
2800             (multiple-value-bind (subtype certain?)
2801                 (csubtypep type2 type1)
2802               (declare (ignore subtype))
2803               (values nil certain?))))))
2804
2805 (!define-type-method (union :complex-=) (type1 type2)
2806   (declare (ignore type1))
2807   (if (some #'type-might-contain-other-types-p
2808             (union-type-types type2))
2809       (values nil nil)
2810       (values nil t)))
2811
2812 ;;; Similarly, a union type is a subtype of another if and only if
2813 ;;; every element of TYPE1 is a subtype of TYPE2.
2814 (defun union-simple-subtypep (type1 type2)
2815   (every/type (swapped-args-fun #'union-complex-subtypep-arg2)
2816               type2
2817               (union-type-types type1)))
2818
2819 (!define-type-method (union :simple-subtypep) (type1 type2)
2820   (union-simple-subtypep type1 type2))
2821
2822 (defun union-complex-subtypep-arg1 (type1 type2)
2823   (every/type (swapped-args-fun #'csubtypep)
2824               type2
2825               (union-type-types type1)))
2826
2827 (!define-type-method (union :complex-subtypep-arg1) (type1 type2)
2828   (union-complex-subtypep-arg1 type1 type2))
2829
2830 (defun union-complex-subtypep-arg2 (type1 type2)
2831   (multiple-value-bind (sub-value sub-certain?)
2832       ;; was: (any/type #'csubtypep type1 (union-type-types type2)),
2833       ;; which turns out to be too restrictive, causing bug 91.
2834       ;;
2835       ;; the following reimplementation might look dodgy.  It is
2836       ;; dodgy. It depends on the union :complex-= method not doing
2837       ;; very much work -- certainly, not using subtypep. Reasoning:
2838       (progn
2839         ;; At this stage, we know that type2 is a union type and type1
2840         ;; isn't. We might as well check this, though:
2841         (aver (union-type-p type2))
2842         (aver (not (union-type-p type1)))
2843         ;;     A is a subset of (B1 u B2)
2844         ;; <=> A n (B1 u B2) = A
2845         ;; <=> (A n B1) u (A n B2) = A
2846         ;;
2847         ;; But, we have to be careful not to delegate this type= to
2848         ;; something that could invoke subtypep, which might get us
2849         ;; back here -> stack explosion. We therefore ensure that the
2850         ;; second type (which is the one that's dispatched on) is
2851         ;; either a union type (where we've ensured that the complex-=
2852         ;; method will not call subtypep) or something with no union
2853         ;; types involved, in which case we'll never come back here.
2854         ;;
2855         ;; If we don't do this, then e.g.
2856         ;; (SUBTYPEP '(MEMBER 3) '(OR (SATISFIES FOO) (SATISFIES BAR)))
2857         ;; would loop infinitely, as the member :complex-= method is
2858         ;; implemented in terms of subtypep.
2859         ;;
2860         ;; Ouch. - CSR, 2002-04-10
2861         (type= type1
2862                (apply #'type-union
2863                       (mapcar (lambda (x) (type-intersection type1 x))
2864                               (union-type-types type2)))))
2865     (if sub-certain?
2866         (values sub-value sub-certain?)
2867         ;; The ANY/TYPE expression above is a sufficient condition for
2868         ;; subsetness, but not a necessary one, so we might get a more
2869         ;; certain answer by this CALL-NEXT-METHOD-ish step when the
2870         ;; ANY/TYPE expression is uncertain.
2871         (invoke-complex-subtypep-arg1-method type1 type2))))
2872
2873 (!define-type-method (union :complex-subtypep-arg2) (type1 type2)
2874   (union-complex-subtypep-arg2 type1 type2))
2875
2876 (!define-type-method (union :simple-intersection2 :complex-intersection2)
2877                      (type1 type2)
2878   ;; The CSUBTYPEP clauses here let us simplify e.g.
2879   ;;   (TYPE-INTERSECTION2 (SPECIFIER-TYPE 'LIST)
2880   ;;                       (SPECIFIER-TYPE '(OR LIST VECTOR)))
2881   ;; (where LIST is (OR CONS NULL)).
2882   ;;
2883   ;; The tests are more or less (CSUBTYPEP TYPE1 TYPE2) and vice
2884   ;; versa, but it's important that we pre-expand them into
2885   ;; specialized operations on individual elements of
2886   ;; UNION-TYPE-TYPES, instead of using the ordinary call to
2887   ;; CSUBTYPEP, in order to avoid possibly invoking any methods which
2888   ;; might in turn invoke (TYPE-INTERSECTION2 TYPE1 TYPE2) and thus
2889   ;; cause infinite recursion.
2890   ;;
2891   ;; Within this method, type2 is guaranteed to be a union type:
2892   (aver (union-type-p type2))
2893   ;; Make sure to call only the applicable methods...
2894   (cond ((and (union-type-p type1)
2895               (union-simple-subtypep type1 type2)) type1)
2896         ((and (union-type-p type1)
2897               (union-simple-subtypep type2 type1)) type2)
2898         ((and (not (union-type-p type1))
2899               (union-complex-subtypep-arg2 type1 type2))
2900          type1)
2901         ((and (not (union-type-p type1))
2902               (union-complex-subtypep-arg1 type2 type1))
2903          type2)
2904         (t
2905          ;; KLUDGE: This code accumulates a sequence of TYPE-UNION2
2906          ;; operations in a particular order, and gives up if any of
2907          ;; the sub-unions turn out not to be simple. In other cases
2908          ;; ca. sbcl-0.6.11.15, that approach to taking a union was a
2909          ;; bad idea, since it can overlook simplifications which
2910          ;; might occur if the terms were accumulated in a different
2911          ;; order. It's possible that that will be a problem here too.
2912          ;; However, I can't think of a good example to demonstrate
2913          ;; it, and without an example to demonstrate it I can't write
2914          ;; test cases, and without test cases I don't want to
2915          ;; complicate the code to address what's still a hypothetical
2916          ;; problem. So I punted. -- WHN 2001-03-20
2917          (let ((accumulator *empty-type*))
2918            (dolist (t2 (union-type-types type2) accumulator)
2919              (setf accumulator
2920                    (type-union accumulator
2921                                (type-intersection type1 t2))))))))
2922
2923 (!def-type-translator or (&rest type-specifiers)
2924   (apply #'type-union
2925          (mapcar #'specifier-type
2926                  type-specifiers)))
2927 \f
2928 ;;;; CONS types
2929
2930 (!define-type-class cons)
2931
2932 (!def-type-translator cons (&optional (car-type-spec '*) (cdr-type-spec '*))
2933   (let ((car-type (single-value-specifier-type car-type-spec))
2934         (cdr-type (single-value-specifier-type cdr-type-spec)))
2935     (make-cons-type car-type cdr-type)))
2936
2937 (!define-type-method (cons :negate) (type)
2938   (if (and (eq (cons-type-car-type type) *universal-type*)
2939            (eq (cons-type-cdr-type type) *universal-type*))
2940       (make-negation-type :type type)
2941       (type-union
2942        (make-negation-type :type (specifier-type 'cons))
2943        (cond
2944          ((and (not (eq (cons-type-car-type type) *universal-type*))
2945                (not (eq (cons-type-cdr-type type) *universal-type*)))
2946           (type-union
2947            (make-cons-type
2948             (type-negation (cons-type-car-type type))
2949             *universal-type*)
2950            (make-cons-type
2951             *universal-type*
2952             (type-negation (cons-type-cdr-type type)))))
2953          ((not (eq (cons-type-car-type type) *universal-type*))
2954           (make-cons-type
2955            (type-negation (cons-type-car-type type))
2956            *universal-type*))
2957          ((not (eq (cons-type-cdr-type type) *universal-type*))
2958           (make-cons-type
2959            *universal-type*
2960            (type-negation (cons-type-cdr-type type))))
2961          (t (bug "Weird CONS type ~S" type))))))
2962
2963 (!define-type-method (cons :unparse) (type)
2964   (let ((car-eltype (type-specifier (cons-type-car-type type)))
2965         (cdr-eltype (type-specifier (cons-type-cdr-type type))))
2966     (if (and (member car-eltype '(t *))
2967              (member cdr-eltype '(t *)))
2968         'cons
2969         `(cons ,car-eltype ,cdr-eltype))))
2970
2971 (!define-type-method (cons :simple-=) (type1 type2)
2972   (declare (type cons-type type1 type2))
2973   (multiple-value-bind (car-match car-win)
2974       (type= (cons-type-car-type type1) (cons-type-car-type type2))
2975     (multiple-value-bind (cdr-match cdr-win)
2976         (type= (cons-type-cdr-type type1) (cons-type-cdr-type type2))
2977       (cond ((and car-match cdr-match)
2978              (aver (and car-win cdr-win))
2979              (values t t))
2980             (t
2981              (values nil
2982                      ;; FIXME: Ideally we would like to detect and handle
2983                      ;;  (CONS UNKNOWN INTEGER) (CONS UNKNOWN SYMBOL) => NIL, T
2984                      ;; but just returning a secondary true on (and car-win cdr-win)
2985                      ;; unfortunately breaks other things. --NS 2006-08-16
2986                      (and (or (and (not car-match) car-win)
2987                               (and (not cdr-match) cdr-win))
2988                           (not (and (cons-type-might-be-empty-type type1)
2989                                     (cons-type-might-be-empty-type type2))))))))))
2990
2991 (!define-type-method (cons :simple-subtypep) (type1 type2)
2992   (declare (type cons-type type1 type2))
2993   (multiple-value-bind (val-car win-car)
2994       (csubtypep (cons-type-car-type type1) (cons-type-car-type type2))
2995     (multiple-value-bind (val-cdr win-cdr)
2996         (csubtypep (cons-type-cdr-type type1) (cons-type-cdr-type type2))
2997       (if (and val-car val-cdr)
2998           (values t (and win-car win-cdr))
2999           (values nil (or (and (not val-car) win-car)
3000                           (and (not val-cdr) win-cdr)))))))
3001
3002 ;;; Give up if a precise type is not possible, to avoid returning
3003 ;;; overly general types.
3004 (!define-type-method (cons :simple-union2) (type1 type2)
3005   (declare (type cons-type type1 type2))
3006   (let ((car-type1 (cons-type-car-type type1))
3007         (car-type2 (cons-type-car-type type2))
3008         (cdr-type1 (cons-type-cdr-type type1))
3009         (cdr-type2 (cons-type-cdr-type type2))
3010         car-not1
3011         car-not2)
3012     ;; UGH.  -- CSR, 2003-02-24
3013     (macrolet ((frob-car (car1 car2 cdr1 cdr2
3014                           &optional (not1 nil not1p))
3015                  `(type-union
3016                    (make-cons-type ,car1 (type-union ,cdr1 ,cdr2))
3017                    (make-cons-type
3018                     (type-intersection ,car2
3019                      ,(if not1p
3020                           not1
3021                           `(type-negation ,car1)))
3022                     ,cdr2))))
3023       (cond ((type= car-type1 car-type2)
3024              (make-cons-type car-type1
3025                              (type-union cdr-type1 cdr-type2)))
3026             ((type= cdr-type1 cdr-type2)
3027              (make-cons-type (type-union car-type1 car-type2)
3028                              cdr-type1))
3029             ((csubtypep car-type1 car-type2)
3030              (frob-car car-type1 car-type2 cdr-type1 cdr-type2))
3031             ((csubtypep car-type2 car-type1)
3032              (frob-car car-type2 car-type1 cdr-type2 cdr-type1))
3033             ;; more general case of the above, but harder to compute
3034             ((progn
3035                (setf car-not1 (type-negation car-type1))
3036                (multiple-value-bind (yes win)
3037                    (csubtypep car-type2 car-not1)
3038                  (and (not yes) win)))
3039              (frob-car car-type1 car-type2 cdr-type1 cdr-type2 car-not1))
3040             ((progn
3041                (setf car-not2 (type-negation car-type2))
3042                (multiple-value-bind (yes win)
3043                    (csubtypep car-type1 car-not2)
3044                  (and (not yes) win)))
3045              (frob-car car-type2 car-type1 cdr-type2 cdr-type1 car-not2))
3046             ;; Don't put these in -- consider the effect of taking the
3047             ;; union of (CONS (INTEGER 0 2) (INTEGER 5 7)) and
3048             ;; (CONS (INTEGER 0 3) (INTEGER 5 6)).
3049             #+nil
3050             ((csubtypep cdr-type1 cdr-type2)
3051              (frob-cdr car-type1 car-type2 cdr-type1 cdr-type2))
3052             #+nil
3053             ((csubtypep cdr-type2 cdr-type1)
3054              (frob-cdr car-type2 car-type1 cdr-type2 cdr-type1))))))
3055
3056 (!define-type-method (cons :simple-intersection2) (type1 type2)
3057   (declare (type cons-type type1 type2))
3058   (let ((car-int2 (type-intersection2 (cons-type-car-type type1)
3059                                       (cons-type-car-type type2)))
3060         (cdr-int2 (type-intersection2 (cons-type-cdr-type type1)
3061                                       (cons-type-cdr-type type2))))
3062     (cond
3063       ((and car-int2 cdr-int2) (make-cons-type car-int2 cdr-int2))
3064       (car-int2 (make-cons-type car-int2
3065                                 (type-intersection
3066                                  (cons-type-cdr-type type1)
3067                                  (cons-type-cdr-type type2))))
3068       (cdr-int2 (make-cons-type
3069                  (type-intersection (cons-type-car-type type1)
3070                                     (cons-type-car-type type2))
3071                  cdr-int2)))))
3072 \f
3073 ;;;; CHARACTER-SET types
3074
3075 (!define-type-class character-set)
3076
3077 (!def-type-translator character-set
3078     (&optional (pairs '((0 . #.(1- sb!xc:char-code-limit)))))
3079   (make-character-set-type :pairs pairs))
3080
3081 (!define-type-method (character-set :negate) (type)
3082   (let ((pairs (character-set-type-pairs type)))
3083     (if (and (= (length pairs) 1)
3084             (= (caar pairs) 0)
3085             (= (cdar pairs) (1- sb!xc:char-code-limit)))
3086        (make-negation-type :type type)
3087        (let ((not-character
3088               (make-negation-type
3089                :type (make-character-set-type
3090                       :pairs '((0 . #.(1- sb!xc:char-code-limit)))))))
3091          (type-union
3092           not-character
3093           (make-character-set-type
3094            :pairs (let (not-pairs)
3095                     (when (> (caar pairs) 0)
3096                       (push (cons 0 (1- (caar pairs))) not-pairs))
3097                     (do* ((tail pairs (cdr tail))
3098                           (high1 (cdar tail))
3099                           (low2 (caadr tail)))
3100                          ((null (cdr tail))
3101                           (when (< (cdar tail) (1- sb!xc:char-code-limit))
3102                             (push (cons (1+ (cdar tail))
3103                                         (1- sb!xc:char-code-limit))
3104                                   not-pairs))
3105                           (nreverse not-pairs))
3106                       (push (cons (1+ high1) (1- low2)) not-pairs)))))))))
3107
3108 (!define-type-method (character-set :unparse) (type)
3109   (cond
3110     ((type= type (specifier-type 'character)) 'character)
3111     ((type= type (specifier-type 'base-char)) 'base-char)
3112     ((type= type (specifier-type 'extended-char)) 'extended-char)
3113     ((type= type (specifier-type 'standard-char)) 'standard-char)
3114     (t (let ((pairs (character-set-type-pairs type)))
3115         `(member ,@(loop for (low . high) in pairs
3116                          nconc (loop for code from low upto high
3117                                      collect (sb!xc:code-char code))))))))
3118
3119 (!define-type-method (character-set :simple-=) (type1 type2)
3120   (let ((pairs1 (character-set-type-pairs type1))
3121        (pairs2 (character-set-type-pairs type2)))
3122     (values (equal pairs1 pairs2) t)))
3123
3124 (!define-type-method (character-set :simple-subtypep) (type1 type2)
3125   (values
3126    (dolist (pair (character-set-type-pairs type1) t)
3127      (unless (position pair (character-set-type-pairs type2)
3128                       :test (lambda (x y) (and (>= (car x) (car y))
3129                                                (<= (cdr x) (cdr y)))))
3130        (return nil)))
3131    t))
3132
3133 (!define-type-method (character-set :simple-union2) (type1 type2)
3134   ;; KLUDGE: the canonizing in the MAKE-CHARACTER-SET-TYPE function
3135   ;; actually does the union for us.  It might be a little fragile to
3136   ;; rely on it.
3137   (make-character-set-type
3138    :pairs (merge 'list
3139                 (copy-alist (character-set-type-pairs type1))
3140                 (copy-alist (character-set-type-pairs type2))
3141                 #'< :key #'car)))
3142
3143 (!define-type-method (character-set :simple-intersection2) (type1 type2)
3144   ;; KLUDGE: brute force.
3145 #|
3146   (let (pairs)
3147     (dolist (pair1 (character-set-type-pairs type1)
3148             (make-character-set-type
3149              :pairs (sort pairs #'< :key #'car)))
3150       (dolist (pair2 (character-set-type-pairs type2))
3151        (cond
3152          ((<= (car pair1) (car pair2) (cdr pair1))
3153           (push (cons (car pair2) (min (cdr pair1) (cdr pair2))) pairs))
3154          ((<= (car pair2) (car pair1) (cdr pair2))
3155           (push (cons (car pair1) (min (cdr pair1) (cdr pair2))) pairs))))))
3156 |#
3157   (make-character-set-type
3158    :pairs (intersect-type-pairs
3159            (character-set-type-pairs type1)
3160            (character-set-type-pairs type2))))
3161
3162 ;;;
3163 ;;; Intersect two ordered lists of pairs
3164 ;;; Each list is of the form ((start1 . end1) ... (startn . endn)),
3165 ;;; where start1 <= end1 < start2 <= end2 < ... < startn <= endn.
3166 ;;; Each pair represents the integer interval start..end.
3167 ;;;
3168 (defun intersect-type-pairs (alist1 alist2)
3169   (if (and alist1 alist2)
3170       (let ((res nil)
3171             (pair1 (pop alist1))
3172             (pair2 (pop alist2)))
3173         (loop
3174          (when (> (car pair1) (car pair2))
3175            (rotatef pair1 pair2)
3176            (rotatef alist1 alist2))
3177          (let ((pair1-cdr (cdr pair1)))
3178            (cond
3179             ((> (car pair2) pair1-cdr)
3180              ;; No over lap -- discard pair1
3181              (unless alist1 (return))
3182              (setq pair1 (pop alist1)))
3183             ((<= (cdr pair2) pair1-cdr)
3184              (push (cons (car pair2) (cdr pair2)) res)
3185              (cond
3186               ((= (cdr pair2) pair1-cdr)
3187                (unless alist1 (return))
3188                (unless alist2 (return))
3189                (setq pair1 (pop alist1)
3190                      pair2 (pop alist2)))
3191               (t ;; (< (cdr pair2) pair1-cdr)
3192                (unless alist2 (return))
3193                (setq pair1 (cons (1+ (cdr pair2)) pair1-cdr))
3194                (setq pair2 (pop alist2)))))
3195             (t ;; (> (cdr pair2) (cdr pair1))
3196              (push (cons (car pair2) pair1-cdr) res)
3197              (unless alist1 (return))
3198              (setq pair2 (cons (1+ pair1-cdr) (cdr pair2)))
3199              (setq pair1 (pop alist1))))))
3200         (nreverse res))
3201     nil))
3202
3203 \f
3204 ;;; Return the type that describes all objects that are in X but not
3205 ;;; in Y. If we can't determine this type, then return NIL.
3206 ;;;
3207 ;;; For now, we only are clever dealing with union and member types.
3208 ;;; If either type is not a union type, then we pretend that it is a
3209 ;;; union of just one type. What we do is remove from X all the types
3210 ;;; that are a subtype any type in Y. If any type in X intersects with
3211 ;;; a type in Y but is not a subtype, then we give up.
3212 ;;;
3213 ;;; We must also special-case any member type that appears in the
3214 ;;; union. We remove from X's members all objects that are TYPEP to Y.
3215 ;;; If Y has any members, we must be careful that none of those
3216 ;;; members are CTYPEP to any of Y's non-member types. We give up in
3217 ;;; this case, since to compute that difference we would have to break
3218 ;;; the type from X into some collection of types that represents the
3219 ;;; type without that particular element. This seems too hairy to be
3220 ;;; worthwhile, given its low utility.
3221 (defun type-difference (x y)
3222   (let ((x-types (if (union-type-p x) (union-type-types x) (list x)))
3223         (y-types (if (union-type-p y) (union-type-types y) (list y))))
3224     (collect ((res))
3225       (dolist (x-type x-types)
3226         (if (member-type-p x-type)
3227             (collect ((members))
3228               (dolist (mem (member-type-members x-type))
3229                 (multiple-value-bind (val win) (ctypep mem y)
3230                   (unless win (return-from type-difference nil))
3231                   (unless val
3232                     (members mem))))
3233               (when (members)
3234                 (res (make-member-type :members (members)))))
3235             (dolist (y-type y-types (res x-type))
3236               (multiple-value-bind (val win) (csubtypep x-type y-type)
3237                 (unless win (return-from type-difference nil))
3238                 (when val (return))
3239                 (when (types-equal-or-intersect x-type y-type)
3240                   (return-from type-difference nil))))))
3241       (let ((y-mem (find-if #'member-type-p y-types)))
3242         (when y-mem
3243           (let ((members (member-type-members y-mem)))
3244             (dolist (x-type x-types)
3245               (unless (member-type-p x-type)
3246                 (dolist (member members)
3247                   (multiple-value-bind (val win) (ctypep member x-type)
3248                     (when (or (not win) val)
3249                       (return-from type-difference nil)))))))))
3250       (apply #'type-union (res)))))
3251 \f
3252 (!def-type-translator array (&optional (element-type '*)
3253                                        (dimensions '*))
3254   (specialize-array-type
3255    (make-array-type :dimensions (canonical-array-dimensions dimensions)
3256                     :complexp :maybe
3257                     :element-type (if (eq element-type '*)
3258                                       *wild-type*
3259                                       (specifier-type element-type)))))
3260
3261 (!def-type-translator simple-array (&optional (element-type '*)
3262                                               (dimensions '*))
3263   (specialize-array-type
3264    (make-array-type :dimensions (canonical-array-dimensions dimensions)
3265                     :complexp nil
3266                     :element-type (if (eq element-type '*)
3267                                       *wild-type*
3268                                       (specifier-type element-type)))))
3269 \f
3270 ;;;; utilities shared between cross-compiler and target system
3271
3272 ;;; Does the type derived from compilation of an actual function
3273 ;;; definition satisfy declarations of a function's type?
3274 (defun defined-ftype-matches-declared-ftype-p (defined-ftype declared-ftype)
3275   (declare (type ctype defined-ftype declared-ftype))
3276   (flet ((is-built-in-class-function-p (ctype)
3277            (and (built-in-classoid-p ctype)
3278                 (eq (built-in-classoid-name ctype) 'function))))
3279     (cond (;; DECLARED-FTYPE could certainly be #<BUILT-IN-CLASS FUNCTION>;
3280            ;; that's what happens when we (DECLAIM (FTYPE FUNCTION FOO)).
3281            (is-built-in-class-function-p declared-ftype)
3282            ;; In that case, any definition satisfies the declaration.
3283            t)
3284           (;; It's not clear whether or how DEFINED-FTYPE might be
3285            ;; #<BUILT-IN-CLASS FUNCTION>, but it's not obviously
3286            ;; invalid, so let's handle that case too, just in case.
3287            (is-built-in-class-function-p defined-ftype)
3288            ;; No matter what DECLARED-FTYPE might be, we can't prove
3289            ;; that an object of type FUNCTION doesn't satisfy it, so
3290            ;; we return success no matter what.
3291            t)
3292           (;; Otherwise both of them must be FUN-TYPE objects.
3293            t
3294            ;; FIXME: For now we only check compatibility of the return
3295            ;; type, not argument types, and we don't even check the
3296            ;; return type very precisely (as per bug 94a). It would be
3297            ;; good to do a better job. Perhaps to check the
3298            ;; compatibility of the arguments, we should (1) redo
3299            ;; VALUES-TYPES-EQUAL-OR-INTERSECT as
3300            ;; ARGS-TYPES-EQUAL-OR-INTERSECT, and then (2) apply it to
3301            ;; the ARGS-TYPE slices of the FUN-TYPEs. (ARGS-TYPE
3302            ;; is a base class both of VALUES-TYPE and of FUN-TYPE.)
3303            (values-types-equal-or-intersect
3304             (fun-type-returns defined-ftype)
3305             (fun-type-returns declared-ftype))))))
3306
3307 ;;; This messy case of CTYPE for NUMBER is shared between the
3308 ;;; cross-compiler and the target system.
3309 (defun ctype-of-number (x)
3310   (let ((num (if (complexp x) (realpart x) x)))
3311     (multiple-value-bind (complexp low high)
3312         (if (complexp x)
3313             (let ((imag (imagpart x)))
3314               (values :complex (min num imag) (max num imag)))
3315             (values :real num num))
3316       (make-numeric-type :class (etypecase num
3317                                   (integer (if (complexp x)
3318                                                (if (integerp (imagpart x))
3319                                                    'integer
3320                                                    'rational)
3321                                                'integer))
3322                                   (rational 'rational)
3323                                   (float 'float))
3324                          :format (and (floatp num) (float-format-name num))
3325                          :complexp complexp
3326                          :low low
3327                          :high high))))
3328 \f
3329 (locally
3330   ;; Why SAFETY 0? To suppress the is-it-the-right-structure-type
3331   ;; checking for declarations in structure accessors. Otherwise we
3332   ;; can get caught in a chicken-and-egg bootstrapping problem, whose
3333   ;; symptom on x86 OpenBSD sbcl-0.pre7.37.flaky5.22 is an illegal
3334   ;; instruction trap. I haven't tracked it down, but I'm guessing it
3335   ;; has to do with setting LAYOUTs when the LAYOUT hasn't been set
3336   ;; yet. -- WHN
3337   (declare (optimize (safety 0)))
3338   (!defun-from-collected-cold-init-forms !late-type-cold-init))
3339
3340 (/show0 "late-type.lisp end of file")