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