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