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