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