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