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