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