3f0a53d0151329ba2a004accab2aac98527dbde0
[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 ;;; TYPE-UNION (and the OR type) doesn't properly canonicalize an
26 ;;; exhaustive partition or coalesce contiguous ranges of numeric
27 ;;; types.
28 ;;;
29 ;;; There are all sorts of nasty problems with open bounds on FLOAT
30 ;;; types (and probably FLOAT types in general.)
31 ;;;
32 ;;; RATIO and BIGNUM are not recognized as numeric types.
33
34 ;;; FIXME: This really should go away. Alas, it doesn't seem to be so
35 ;;; simple to make it go away.. (See bug 123 in BUGS file.)
36 (defvar *use-implementation-types* t ; actually initialized in cold init
37   #!+sb-doc
38   "*USE-IMPLEMENTATION-TYPES* is a semi-public flag which determines how
39    restrictive we are in determining type membership. If two types are the
40    same in the implementation, then we will consider them them the same when
41    this switch is on. When it is off, we try to be as restrictive as the
42    language allows, allowing us to detect more errors. Currently, this only
43    affects array types.")
44 (!cold-init-forms (setq *use-implementation-types* t))
45
46 ;;; These functions are used as method for types which need a complex
47 ;;; subtypep method to handle some superclasses, but cover a subtree
48 ;;; of the type graph (i.e. there is no simple way for any other type
49 ;;; class to be a subtype.) There are always still complex ways,
50 ;;; namely UNION and MEMBER types, so we must give TYPE1's method a
51 ;;; chance to run, instead of immediately returning NIL, T.
52 (defun delegate-complex-subtypep-arg2 (type1 type2)
53   (let ((subtypep-arg1
54          (type-class-complex-subtypep-arg1
55           (type-class-info type1))))
56     (if subtypep-arg1
57         (funcall subtypep-arg1 type1 type2)
58         (values nil t))))
59 (defun delegate-complex-intersection2 (type1 type2)
60   (let ((method (type-class-complex-intersection2 (type-class-info type1))))
61     (if (and method (not (eq method #'delegate-complex-intersection2)))
62         (funcall method type2 type1)
63         (hierarchical-intersection2 type1 type2))))
64
65 ;;; This is used by !DEFINE-SUPERCLASSES to define the SUBTYPE-ARG1
66 ;;; method. INFO is a list of conses
67 ;;;   (SUPERCLASS-CLASS . {GUARD-TYPE-SPECIFIER | NIL}).
68 (defun !has-superclasses-complex-subtypep-arg1 (type1 type2 info)
69   ;; If TYPE2 might be concealing something related to our class
70   ;; hierarchy
71   (if (type-might-contain-other-types-p type2)
72       ;; too confusing, gotta punt 
73       (values nil nil)
74       ;; ordinary case expected by old CMU CL code, where the taxonomy
75       ;; of TYPE2's representation accurately reflects the taxonomy of
76       ;; the underlying set
77       (values
78        ;; FIXME: This old CMU CL code probably deserves a comment
79        ;; explaining to us mere mortals how it works...
80        (and (sb!xc:typep type2 'sb!xc:class)
81             (dolist (x info nil)
82               (when (or (not (cdr x))
83                         (csubtypep type1 (specifier-type (cdr x))))
84                 (return
85                  (or (eq type2 (car x))
86                      (let ((inherits (layout-inherits (class-layout (car x)))))
87                        (dotimes (i (length inherits) nil)
88                          (when (eq type2 (layout-class (svref inherits i)))
89                            (return t)))))))))
90        t)))
91
92 ;;; This function takes a list of specs, each of the form
93 ;;;    (SUPERCLASS-NAME &OPTIONAL GUARD).
94 ;;; Consider one spec (with no guard): any instance of the named
95 ;;; TYPE-CLASS is also a subtype of the named superclass and of any of
96 ;;; its superclasses. If there are multiple specs, then some will have
97 ;;; guards. We choose the first spec whose guard is a supertype of
98 ;;; TYPE1 and use its superclass. In effect, a sequence of guards
99 ;;;    G0, G1, G2
100 ;;; is actually
101 ;;;    G0,(and G1 (not G0)), (and G2 (not (or G0 G1))).
102 ;;;
103 ;;; WHEN controls when the forms are executed.
104 (defmacro !define-superclasses (type-class-name specs when)
105   (let ((type-class (gensym "TYPE-CLASS-"))
106         (info (gensym "INFO")))
107     `(,when
108        (let ((,type-class (type-class-or-lose ',type-class-name))
109              (,info (mapcar (lambda (spec)
110                               (destructuring-bind
111                                   (super &optional guard)
112                                   spec
113                                 (cons (sb!xc:find-class super) guard)))
114                             ',specs)))
115          (setf (type-class-complex-subtypep-arg1 ,type-class)
116                (lambda (type1 type2)
117                  (!has-superclasses-complex-subtypep-arg1 type1 type2 ,info)))
118          (setf (type-class-complex-subtypep-arg2 ,type-class)
119                #'delegate-complex-subtypep-arg2)
120          (setf (type-class-complex-intersection2 ,type-class)
121                #'delegate-complex-intersection2)))))
122 \f
123 ;;;; FUNCTION and VALUES types
124 ;;;;
125 ;;;; Pretty much all of the general type operations are illegal on
126 ;;;; VALUES types, since we can't discriminate using them, do
127 ;;;; SUBTYPEP, etc. FUNCTION types are acceptable to the normal type
128 ;;;; operations, but are generally considered to be equivalent to
129 ;;;; FUNCTION. These really aren't true types in any type theoretic
130 ;;;; sense, but we still parse them into CTYPE structures for two
131 ;;;; reasons:
132
133 ;;;; -- Parsing and unparsing work the same way, and indeed we can't
134 ;;;;    tell whether a type is a function or values type without
135 ;;;;    parsing it.
136 ;;;; -- Many of the places that can be annotated with real types can
137 ;;;;    also be annotated with function or values types.
138
139 ;;; the description of a &KEY argument
140 (defstruct (key-info #-sb-xc-host (:pure t)
141                      (:copier nil))
142   ;; the key (not necessarily a keyword in ANSI Common Lisp)
143   (name (missing-arg) :type symbol)
144   ;; the type of the argument value
145   (type (missing-arg) :type ctype))
146
147 (!define-type-method (values :simple-subtypep :complex-subtypep-arg1)
148                      (type1 type2)
149   (declare (ignore type2))
150   ;; FIXME: should be TYPE-ERROR, here and in next method
151   (error "SUBTYPEP is illegal on this type:~%  ~S" (type-specifier type1)))
152
153 (!define-type-method (values :complex-subtypep-arg2)
154                      (type1 type2)
155   (declare (ignore type1))
156   (error "SUBTYPEP is illegal on this type:~%  ~S" (type-specifier type2)))
157
158 (!define-type-method (values :unparse) (type)
159   (cons 'values (unparse-args-types type)))
160
161 ;;; Return true if LIST1 and LIST2 have the same elements in the same
162 ;;; positions according to TYPE=. We return NIL, NIL if there is an
163 ;;; uncertain comparison.
164 (defun type=-list (list1 list2)
165   (declare (list list1 list2))
166   (do ((types1 list1 (cdr types1))
167        (types2 list2 (cdr types2)))
168       ((or (null types1) (null types2))
169        (if (or types1 types2)
170            (values nil t)
171            (values t t)))
172     (multiple-value-bind (val win)
173         (type= (first types1) (first types2))
174       (unless win
175         (return (values nil nil)))
176       (unless val
177         (return (values nil t))))))
178
179 (!define-type-method (values :simple-=) (type1 type2)
180   (let ((rest1 (args-type-rest type1))
181         (rest2 (args-type-rest type2)))
182     (cond ((or (args-type-keyp type1) (args-type-keyp type2)
183                (args-type-allowp type1) (args-type-allowp type2))
184            (values nil nil))
185           ((and rest1 rest2 (type/= rest1 rest2))
186            (type= rest1 rest2))
187           ((or rest1 rest2)
188            (values nil t))
189           (t
190            (multiple-value-bind (req-val req-win)
191                (type=-list (values-type-required type1)
192                            (values-type-required type2))
193              (multiple-value-bind (opt-val opt-win)
194                  (type=-list (values-type-optional type1)
195                              (values-type-optional type2))
196                (values (and req-val opt-val) (and req-win opt-win))))))))
197
198 (!define-type-class function)
199
200 ;;; a flag that we can bind to cause complex function types to be
201 ;;; unparsed as FUNCTION. This is useful when we want a type that we
202 ;;; can pass to TYPEP.
203 (defvar *unparse-fun-type-simplify*)
204 (!cold-init-forms (setq *unparse-fun-type-simplify* nil))
205
206 (!define-type-method (function :unparse) (type)
207   (if *unparse-fun-type-simplify*
208       'function
209       (list 'function
210             (if (fun-type-wild-args type)
211                 '*
212                 (unparse-args-types type))
213             (type-specifier
214              (fun-type-returns type)))))
215
216 ;;; Since all function types are equivalent to FUNCTION, they are all
217 ;;; subtypes of each other.
218 (!define-type-method (function :simple-subtypep) (type1 type2)
219   (declare (ignore type1 type2))
220   (values t t))
221
222 (!define-superclasses function ((function)) !cold-init-forms)
223
224 ;;; The union or intersection of two FUNCTION types is FUNCTION.
225 (!define-type-method (function :simple-union2) (type1 type2)
226   (declare (ignore type1 type2))
227   (specifier-type 'function))
228 (!define-type-method (function :simple-intersection2) (type1 type2)
229   (declare (ignore type1 type2))
230   (specifier-type 'function))
231
232 ;;; ### Not very real, but good enough for redefining transforms
233 ;;; according to type:
234 (!define-type-method (function :simple-=) (type1 type2)
235   (values (equalp type1 type2) t))
236
237 (!define-type-class constant :inherits values)
238
239 (!define-type-method (constant :unparse) (type)
240   `(constant-arg ,(type-specifier (constant-type-type type))))
241
242 (!define-type-method (constant :simple-=) (type1 type2)
243   (type= (constant-type-type type1) (constant-type-type type2)))
244
245 (!def-type-translator constant-arg (type)
246   (make-constant-type :type (specifier-type type)))
247
248 ;;; Given a LAMBDA-LIST-like values type specification and an ARGS-TYPE
249 ;;; structure, fill in the slots in the structure accordingly. This is
250 ;;; used for both FUNCTION and VALUES types.
251 (declaim (ftype (function (list args-type) (values)) parse-args-types))
252 (defun parse-args-types (lambda-list result)
253   (multiple-value-bind (required optional restp rest keyp keys allowp aux)
254       (parse-lambda-list lambda-list)
255     (when aux
256       (error "&AUX in a FUNCTION or VALUES type: ~S." lambda-list))
257     (setf (args-type-required result) (mapcar #'specifier-type required))
258     (setf (args-type-optional result) (mapcar #'specifier-type optional))
259     (setf (args-type-rest result) (if restp (specifier-type rest) nil))
260     (setf (args-type-keyp result) keyp)
261     (collect ((key-info))
262       (dolist (key keys)
263         (unless (proper-list-of-length-p key 2)
264           (error "Keyword type description is not a two-list: ~S." key))
265         (let ((kwd (first key)))
266           (when (find kwd (key-info) :key #'key-info-name)
267             (error "~@<repeated keyword ~S in lambda list: ~2I~_~S~:>"
268                    kwd lambda-list))
269           (key-info (make-key-info :name kwd
270                                    :type (specifier-type (second key))))))
271       (setf (args-type-keywords result) (key-info)))
272     (setf (args-type-allowp result) allowp)
273     (values)))
274
275 ;;; Return the lambda-list-like type specification corresponding
276 ;;; to an ARGS-TYPE.
277 (declaim (ftype (function (args-type) list) unparse-args-types))
278 (defun unparse-args-types (type)
279   (collect ((result))
280
281     (dolist (arg (args-type-required type))
282       (result (type-specifier arg)))
283
284     (when (args-type-optional type)
285       (result '&optional)
286       (dolist (arg (args-type-optional type))
287         (result (type-specifier arg))))
288
289     (when (args-type-rest type)
290       (result '&rest)
291       (result (type-specifier (args-type-rest type))))
292
293     (when (args-type-keyp type)
294       (result '&key)
295       (dolist (key (args-type-keywords type))
296         (result (list (key-info-name key)
297                       (type-specifier (key-info-type key))))))
298
299     (when (args-type-allowp type)
300       (result '&allow-other-keys))
301
302     (result)))
303
304 (!def-type-translator function (&optional (args '*) (result '*))
305   (let ((res (make-fun-type :returns (values-specifier-type result))))
306     (if (eq args '*)
307         (setf (fun-type-wild-args res) t)
308         (parse-args-types args res))
309     res))
310
311 (!def-type-translator values (&rest values)
312   (let ((res (make-values-type)))
313     (parse-args-types values res)
314     res))
315 \f
316 ;;;; VALUES types interfaces
317 ;;;;
318 ;;;; We provide a few special operations that can be meaningfully used
319 ;;;; on VALUES types (as well as on any other type).
320
321 ;;; Return the type of the first value indicated by TYPE. This is used
322 ;;; by people who don't want to have to deal with VALUES types.
323 #!-sb-fluid (declaim (freeze-type values-type))
324 ; (inline single-value-type))
325 (defun single-value-type (type)
326   (declare (type ctype type))
327   (cond ((values-type-p type)
328          (or (car (args-type-required type))
329              (if (args-type-optional type)
330                  (type-union (car (args-type-optional type))
331                              (specifier-type 'null)))
332              (args-type-rest type)
333              (specifier-type 'null)))
334         ((eq type *wild-type*)
335          *universal-type*)
336         (t
337          type)))
338
339 ;;; Return the minimum number of arguments that a function can be
340 ;;; called with, and the maximum number or NIL. If not a function
341 ;;; type, return NIL, NIL.
342 (defun fun-type-nargs (type)
343   (declare (type ctype type))
344   (if (fun-type-p type)
345       (let ((fixed (length (args-type-required type))))
346         (if (or (args-type-rest type)
347                 (args-type-keyp type)
348                 (args-type-allowp type))
349             (values fixed nil)
350             (values fixed (+ fixed (length (args-type-optional type))))))
351       (values nil nil)))
352
353 ;;; Determine whether TYPE corresponds to a definite number of values.
354 ;;; The first value is a list of the types for each value, and the
355 ;;; second value is the number of values. If the number of values is
356 ;;; not fixed, then return NIL and :UNKNOWN.
357 (defun values-types (type)
358   (declare (type ctype type))
359   (cond ((eq type *wild-type*)
360          (values nil :unknown))
361         ((not (values-type-p type))
362          (values (list type) 1))
363         ((or (args-type-optional type)
364              (args-type-rest type)
365              (args-type-keyp type)
366              (args-type-allowp type))
367          (values nil :unknown))
368         (t
369          (let ((req (args-type-required type)))
370            (values (mapcar #'single-value-type req) (length req))))))
371
372 ;;; Return two values:
373 ;;; 1. A list of all the positional (fixed and optional) types.
374 ;;; 2. The &REST type (if any). If keywords allowed, *UNIVERSAL-TYPE*.
375 ;;;    If no keywords or &REST, then the DEFAULT-TYPE.
376 (defun values-type-types (type &optional (default-type *empty-type*))
377   (declare (type values-type type))
378   (values (append (args-type-required type)
379                   (args-type-optional type))
380           (cond ((args-type-keyp type) *universal-type*)
381                 ((args-type-rest type))
382                 (t
383                  default-type))))
384
385 ;;; Return a list of OPERATION applied to the types in TYPES1 and
386 ;;; TYPES2, padding with REST2 as needed. TYPES1 must not be shorter
387 ;;; than TYPES2. The second value is T if OPERATION always returned a
388 ;;; true second value.
389 (defun fixed-values-op (types1 types2 rest2 operation)
390   (declare (list types1 types2) (type ctype rest2) (type function operation))
391   (let ((exact t))
392     (values (mapcar (lambda (t1 t2)
393                       (multiple-value-bind (res win)
394                           (funcall operation t1 t2)
395                         (unless win
396                           (setq exact nil))
397                         res))
398                     types1
399                     (append types2
400                             (make-list (- (length types1) (length types2))
401                                        :initial-element rest2)))
402             exact)))
403
404 ;;; If Type isn't a values type, then make it into one:
405 ;;;    <type>  ==>  (values type &rest t)
406 (defun coerce-to-values (type)
407   (declare (type ctype type))
408   (if (values-type-p type)
409       type
410       (make-values-type :required (list type) :rest *universal-type*)))
411
412 ;;; Do the specified OPERATION on TYPE1 and TYPE2, which may be any
413 ;;; type, including VALUES types. With VALUES types such as:
414 ;;;    (VALUES a0 a1)
415 ;;;    (VALUES b0 b1)
416 ;;; we compute the more useful result
417 ;;;    (VALUES (<operation> a0 b0) (<operation> a1 b1))
418 ;;; rather than the precise result
419 ;;;    (<operation> (values a0 a1) (values b0 b1))
420 ;;; This has the virtue of always keeping the VALUES type specifier
421 ;;; outermost, and retains all of the information that is really
422 ;;; useful for static type analysis. We want to know what is always
423 ;;; true of each value independently. It is worthless to know that if
424 ;;; the first value is B0 then the second will be B1.
425 ;;;
426 ;;; If the VALUES count signatures differ, then we produce a result with
427 ;;; the required VALUE count chosen by NREQ when applied to the number
428 ;;; of required values in TYPE1 and TYPE2. Any &KEY values become
429 ;;; &REST T (anyone who uses keyword values deserves to lose.)
430 ;;;
431 ;;; The second value is true if the result is definitely empty or if
432 ;;; OPERATION returned true as its second value each time we called
433 ;;; it. Since we approximate the intersection of VALUES types, the
434 ;;; second value being true doesn't mean the result is exact.
435 (defun args-type-op (type1 type2 operation nreq default-type)
436   (declare (type ctype type1 type2 default-type)
437            (type function operation nreq))
438   (if (or (values-type-p type1) (values-type-p type2))
439       (let ((type1 (coerce-to-values type1))
440             (type2 (coerce-to-values type2)))
441         (multiple-value-bind (types1 rest1)
442             (values-type-types type1 default-type)
443           (multiple-value-bind (types2 rest2)
444               (values-type-types type2 default-type)
445             (multiple-value-bind (rest rest-exact)
446                 (funcall operation rest1 rest2)
447               (multiple-value-bind (res res-exact)
448                   (if (< (length types1) (length types2))
449                       (fixed-values-op types2 types1 rest1 operation)
450                       (fixed-values-op types1 types2 rest2 operation))
451                 (let* ((req (funcall nreq
452                                      (length (args-type-required type1))
453                                      (length (args-type-required type2))))
454                        (required (subseq res 0 req))
455                        (opt (subseq res req))
456                        (opt-last (position rest opt :test-not #'type=
457                                            :from-end t)))
458                   (if (find *empty-type* required :test #'type=)
459                       (values *empty-type* t)
460                       (values (make-values-type
461                                :required required
462                                :optional (if opt-last
463                                              (subseq opt 0 (1+ opt-last))
464                                              ())
465                                :rest (if (eq rest default-type) nil rest))
466                               (and rest-exact res-exact)))))))))
467       (funcall operation type1 type2)))
468
469 ;;; Do a union or intersection operation on types that might be values
470 ;;; types. The result is optimized for utility rather than exactness,
471 ;;; but it is guaranteed that it will be no smaller (more restrictive)
472 ;;; than the precise result.
473 ;;;
474 ;;; The return convention seems to be analogous to
475 ;;; TYPES-EQUAL-OR-INTERSECT. -- WHN 19990910.
476 (defun-cached (values-type-union :hash-function type-cache-hash
477                                  :hash-bits 8
478                                  :default nil
479                                  :init-wrapper !cold-init-forms)
480               ((type1 eq) (type2 eq))
481   (declare (type ctype type1 type2))
482   (cond ((or (eq type1 *wild-type*) (eq type2 *wild-type*)) *wild-type*)
483         ((eq type1 *empty-type*) type2)
484         ((eq type2 *empty-type*) type1)
485         (t
486          (values (args-type-op type1 type2 #'type-union #'min *empty-type*)))))
487 (defun-cached (values-type-intersection :hash-function type-cache-hash
488                                         :hash-bits 8
489                                         :values 2
490                                         :default (values nil :empty)
491                                         :init-wrapper !cold-init-forms)
492               ((type1 eq) (type2 eq))
493   (declare (type ctype type1 type2))
494   (cond ((eq type1 *wild-type*) (values type2 t))
495         ((eq type2 *wild-type*) (values type1 t))
496         (t
497          (args-type-op type1 type2
498                        #'type-intersection
499                        #'max
500                        (specifier-type 'null)))))
501
502 ;;; This is like TYPES-EQUAL-OR-INTERSECT, except that it sort of
503 ;;; works on VALUES types. Note that due to the semantics of
504 ;;; VALUES-TYPE-INTERSECTION, this might return (VALUES T T) when
505 ;;; there isn't really any intersection.
506 (defun values-types-equal-or-intersect (type1 type2)
507   (cond ((or (eq type1 *empty-type*) (eq type2 *empty-type*))
508          (values t t))
509         ((or (values-type-p type1) (values-type-p type2))
510          (multiple-value-bind (res win) (values-type-intersection type1 type2)
511            (values (not (eq res *empty-type*))
512                    win)))
513         (t
514          (types-equal-or-intersect type1 type2))))
515
516 ;;; a SUBTYPEP-like operation that can be used on any types, including
517 ;;; VALUES types
518 (defun-cached (values-subtypep :hash-function type-cache-hash
519                                :hash-bits 8
520                                :values 2
521                                :default (values nil :empty)
522                                :init-wrapper !cold-init-forms)
523               ((type1 eq) (type2 eq))
524   (declare (type ctype type1 type2))
525   (cond ((eq type2 *wild-type*) (values t t))
526         ((eq type1 *wild-type*)
527          (values (eq type2 *universal-type*) t))
528         ((not (values-types-equal-or-intersect type1 type2))
529          (values nil t))
530         (t
531          (if (or (values-type-p type1) (values-type-p type2))
532              (let ((type1 (coerce-to-values type1))
533                    (type2 (coerce-to-values type2)))
534                (multiple-value-bind (types1 rest1) (values-type-types type1)
535                  (multiple-value-bind (types2 rest2) (values-type-types type2)
536                    (cond ((< (length (values-type-required type1))
537                              (length (values-type-required type2)))
538                           (values nil t))
539                          ((< (length types1) (length types2))
540                           (values nil nil))
541                          ((or (values-type-keyp type1)
542                               (values-type-keyp type2))
543                           (values nil nil))
544                          (t
545                           (do ((t1 types1 (rest t1))
546                                (t2 types2 (rest t2)))
547                               ((null t2)
548                                (csubtypep rest1 rest2))
549                             (multiple-value-bind (res win-p)
550                                 (csubtypep (first t1) (first t2))
551                               (unless win-p
552                                 (return (values nil nil)))
553                               (unless res
554                                 (return (values nil t))))))))))
555              (csubtypep type1 type2)))))
556 \f
557 ;;;; type method interfaces
558
559 ;;; like SUBTYPEP, only works on CTYPE structures
560 (defun-cached (csubtypep :hash-function type-cache-hash
561                          :hash-bits 8
562                          :values 2
563                          :default (values nil :empty)
564                          :init-wrapper !cold-init-forms)
565               ((type1 eq) (type2 eq))
566   (declare (type ctype type1 type2))
567   (cond ((or (eq type1 type2)
568              (eq type1 *empty-type*)
569              (eq type2 *wild-type*))
570          (values t t))
571         ((eq type1 *wild-type*)
572          (values nil t))
573         (t
574          (!invoke-type-method :simple-subtypep :complex-subtypep-arg2
575                               type1 type2
576                               :complex-arg1 :complex-subtypep-arg1))))
577
578 ;;; Just parse the type specifiers and call CSUBTYPE.
579 (defun sb!xc:subtypep (type1 type2)
580   #!+sb-doc
581   "Return two values indicating the relationship between type1 and type2.
582   If values are T and T, type1 definitely is a subtype of type2.
583   If values are NIL and T, type1 definitely is not a subtype of type2.
584   If values are NIL and NIL, it couldn't be determined."
585   (csubtypep (specifier-type type1) (specifier-type type2)))
586
587 ;;; If two types are definitely equivalent, return true. The second
588 ;;; value indicates whether the first value is definitely correct.
589 ;;; This should only fail in the presence of HAIRY types.
590 (defun-cached (type= :hash-function type-cache-hash
591                      :hash-bits 8
592                      :values 2
593                      :default (values nil :empty)
594                      :init-wrapper !cold-init-forms)
595               ((type1 eq) (type2 eq))
596   (declare (type ctype type1 type2))
597   (if (eq type1 type2)
598       (values t t)
599       (!invoke-type-method :simple-= :complex-= type1 type2)))
600
601 ;;; Not exactly the negation of TYPE=, since when the relationship is
602 ;;; uncertain, we still return NIL, NIL. This is useful in cases where
603 ;;; the conservative assumption is =.
604 (defun type/= (type1 type2)
605   (declare (type ctype type1 type2))
606   (multiple-value-bind (res win) (type= type1 type2)
607     (if win
608         (values (not res) t)
609         (values nil nil))))
610
611 ;;; the type method dispatch case of TYPE-UNION2
612 (defun %type-union2 (type1 type2)
613   ;; As in %TYPE-INTERSECTION2, it seems to be a good idea to give
614   ;; both argument orders a chance at COMPLEX-INTERSECTION2. Unlike
615   ;; %TYPE-INTERSECTION2, though, I don't have a specific case which
616   ;; demonstrates this is actually necessary. Also unlike
617   ;; %TYPE-INTERSECTION2, there seems to be no need to distinguish
618   ;; between not finding a method and having a method return NIL.
619   (flet ((1way (x y)
620            (!invoke-type-method :simple-union2 :complex-union2
621                                 x y
622                                 :default nil)))
623     (declare (inline 1way))
624     (or (1way type1 type2)
625         (1way type2 type1))))
626
627 ;;; Find a type which includes both types. Any inexactness is
628 ;;; represented by the fuzzy element types; we return a single value
629 ;;; that is precise to the best of our knowledge. This result is
630 ;;; simplified into the canonical form, thus is not a UNION-TYPE
631 ;;; unless we find no other way to represent the result.
632 (defun-cached (type-union2 :hash-function type-cache-hash
633                            :hash-bits 8
634                            :init-wrapper !cold-init-forms)
635               ((type1 eq) (type2 eq))
636   ;; KLUDGE: This was generated from TYPE-INTERSECTION2 by Ye Olde Cut And
637   ;; Paste technique of programming. If it stays around (as opposed to
638   ;; e.g. fading away in favor of some CLOS solution) the shared logic
639   ;; should probably become shared code. -- WHN 2001-03-16
640   (declare (type ctype type1 type2))
641   (cond ((eq type1 type2)
642          type1)
643         ((csubtypep type1 type2) type2)
644         ((csubtypep type2 type1) type1)
645         ((or (union-type-p type1)
646              (union-type-p type2))
647          ;; Unions of UNION-TYPE should have the UNION-TYPE-TYPES
648          ;; values broken out and united separately. The full TYPE-UNION
649          ;; function knows how to do this, so let it handle it.
650          (type-union type1 type2))
651         (t
652          ;; the ordinary case: we dispatch to type methods
653          (%type-union2 type1 type2))))
654
655 ;;; the type method dispatch case of TYPE-INTERSECTION2
656 (defun %type-intersection2 (type1 type2)
657   ;; We want to give both argument orders a chance at
658   ;; COMPLEX-INTERSECTION2. Without that, the old CMU CL type
659   ;; methods could give noncommutative results, e.g.
660   ;;   (TYPE-INTERSECTION2 *EMPTY-TYPE* SOME-HAIRY-TYPE)
661   ;;     => NIL, NIL
662   ;;   (TYPE-INTERSECTION2 SOME-HAIRY-TYPE *EMPTY-TYPE*)
663   ;;     => #<NAMED-TYPE NIL>, T
664   ;; We also need to distinguish between the case where we found a
665   ;; type method, and it returned NIL, and the case where we fell
666   ;; through without finding any type method. An example of the first
667   ;; case is the intersection of a HAIRY-TYPE with some ordinary type.
668   ;; An example of the second case is the intersection of two
669   ;; completely-unrelated types, e.g. CONS and NUMBER, or SYMBOL and
670   ;; ARRAY.
671   ;;
672   ;; (Why yes, CLOS probably *would* be nicer..)
673   (flet ((1way (x y)
674            (!invoke-type-method :simple-intersection2 :complex-intersection2
675                                 x y
676                                 :default :no-type-method-found)))
677     (declare (inline 1way))
678     (let ((xy (1way type1 type2)))
679       (or (and (not (eql xy :no-type-method-found)) xy)
680           (let ((yx (1way type2 type1)))
681             (or (and (not (eql yx :no-type-method-found)) yx)
682                 (cond ((and (eql xy :no-type-method-found)
683                             (eql yx :no-type-method-found))
684                        *empty-type*)
685                       (t
686                        (aver (and (not xy) (not yx))) ; else handled above
687                        nil))))))))
688
689 (defun-cached (type-intersection2 :hash-function type-cache-hash
690                                   :hash-bits 8
691                                   :values 1
692                                   :default nil
693                                   :init-wrapper !cold-init-forms)
694               ((type1 eq) (type2 eq))
695   (declare (type ctype type1 type2))
696   (cond ((eq type1 type2)
697          ;; FIXME: For some reason, this doesn't catch e.g. type1 =
698          ;; type2 = (SPECIFIER-TYPE
699          ;; 'SOME-UNKNOWN-TYPE). Investigate. - CSR, 2002-04-10
700          type1)
701         ((or (intersection-type-p type1)
702              (intersection-type-p type2))
703          ;; Intersections of INTERSECTION-TYPE should have the
704          ;; INTERSECTION-TYPE-TYPES values broken out and intersected
705          ;; separately. The full TYPE-INTERSECTION function knows how
706          ;; to do that, so let it handle it.
707          (type-intersection type1 type2))
708         (t
709          ;; the ordinary case: we dispatch to type methods
710          (%type-intersection2 type1 type2))))
711
712 ;;; Return as restrictive and simple a type as we can discover that is
713 ;;; no more restrictive than the intersection of TYPE1 and TYPE2. At
714 ;;; worst, we arbitrarily return one of the arguments as the first
715 ;;; value (trying not to return a hairy type).
716 (defun type-approx-intersection2 (type1 type2)
717   (cond ((type-intersection2 type1 type2))
718         ((hairy-type-p type1) type2)
719         (t type1)))
720
721 ;;; a test useful for checking whether a derived type matches a
722 ;;; declared type
723 ;;;
724 ;;; The first value is true unless the types don't intersect and
725 ;;; aren't equal. The second value is true if the first value is
726 ;;; definitely correct. NIL is considered to intersect with any type.
727 ;;; If T is a subtype of either type, then we also return T, T. This
728 ;;; way we recognize that hairy types might intersect with T.
729 (defun types-equal-or-intersect (type1 type2)
730   (declare (type ctype type1 type2))
731   (if (or (eq type1 *empty-type*) (eq type2 *empty-type*))
732       (values t t)
733       (let ((intersection2 (type-intersection2 type1 type2)))
734         (cond ((not intersection2)
735                (if (or (csubtypep *universal-type* type1)
736                        (csubtypep *universal-type* type2))
737                    (values t t)
738                    (values t nil)))
739               ((eq intersection2 *empty-type*) (values nil t))
740               (t (values t t))))))
741
742 ;;; Return a Common Lisp type specifier corresponding to the TYPE
743 ;;; object.
744 (defun type-specifier (type)
745   (declare (type ctype type))
746   (funcall (type-class-unparse (type-class-info type)) type))
747
748 ;;; (VALUES-SPECIFIER-TYPE and SPECIFIER-TYPE moved from here to
749 ;;; early-type.lisp by WHN ca. 19990201.)
750
751 ;;; Take a list of type specifiers, computing the translation of each
752 ;;; specifier and defining it as a builtin type.
753 (declaim (ftype (function (list) (values)) precompute-types))
754 (defun precompute-types (specs)
755   (dolist (spec specs)
756     (let ((res (specifier-type spec)))
757       (unless (unknown-type-p res)
758         (setf (info :type :builtin spec) res)
759         (setf (info :type :kind spec) :primitive))))
760   (values))
761 \f
762 ;;;; general TYPE-UNION and TYPE-INTERSECTION operations
763 ;;;;
764 ;;;; These are fully general operations on CTYPEs: they'll always
765 ;;;; return a CTYPE representing the result.
766
767 ;;; shared logic for unions and intersections: Stuff TYPE into the
768 ;;; vector TYPES, finding pairs of types which can be simplified by
769 ;;; SIMPLIFY2 (TYPE-UNION2 or TYPE-INTERSECTION2) and replacing them
770 ;;; by their simplified forms.
771 (defun accumulate1-compound-type (type types %compound-type-p simplify2)
772   (declare (type ctype type))
773   (declare (type (vector ctype) types))
774   (declare (type function simplify2))
775   ;; Any input object satisfying %COMPOUND-TYPE-P should've been
776   ;; broken into components before it reached us.
777   (aver (not (funcall %compound-type-p type)))
778   (dotimes (i (length types) (vector-push-extend type types))
779     (let ((simplified2 (funcall simplify2 type (aref types i))))
780       (when simplified2
781         ;; Discard the old (AREF TYPES I).
782         (setf (aref types i) (vector-pop types))
783         ;; Merge the new SIMPLIFIED2 into TYPES, by tail recursing.
784         ;; (Note that the tail recursion is indirect: we go through
785         ;; ACCUMULATE, not ACCUMULATE1, so that if SIMPLIFIED2 is
786         ;; handled properly if it satisfies %COMPOUND-TYPE-P.)
787         (return (accumulate-compound-type simplified2
788                                           types
789                                           %compound-type-p
790                                           simplify2)))))
791   ;; Voila.
792   (values))
793
794 ;;; shared logic for unions and intersections: Use
795 ;;; ACCUMULATE1-COMPOUND-TYPE to merge TYPE into TYPES, either
796 ;;; all in one step or, if %COMPOUND-TYPE-P is satisfied,
797 ;;; component by component.
798 (defun accumulate-compound-type (type types %compound-type-p simplify2)
799   (declare (type function %compound-type-p simplify2))
800   (flet ((accumulate1 (x)
801            (accumulate1-compound-type x types %compound-type-p simplify2)))
802     (declare (inline accumulate1))
803     (if (funcall %compound-type-p type)
804         (map nil #'accumulate1 (compound-type-types type))
805         (accumulate1 type)))
806   (values))
807
808 ;;; shared logic for unions and intersections: Return a vector of
809 ;;; types representing the same types as INPUT-TYPES, but with 
810 ;;; COMPOUND-TYPEs satisfying %COMPOUND-TYPE-P broken up into their
811 ;;; component types, and with any SIMPLY2 simplifications applied.
812 (defun simplified-compound-types (input-types %compound-type-p simplify2)
813   (let ((simplified-types (make-array (length input-types)
814                                       :fill-pointer 0
815                                       :adjustable t
816                                       :element-type 'ctype
817                                       ;; (This INITIAL-ELEMENT shouldn't
818                                       ;; matter, but helps avoid type
819                                       ;; warnings at compile time.)
820                                       :initial-element *empty-type*)))
821     (dolist (input-type input-types)
822       (accumulate-compound-type input-type
823                                 simplified-types
824                                 %compound-type-p
825                                 simplify2))
826     simplified-types))
827
828 ;;; shared logic for unions and intersections: Make a COMPOUND-TYPE
829 ;;; object whose components are the types in TYPES, or skip to special
830 ;;; cases when TYPES is short.
831 (defun make-compound-type-or-something (constructor types enumerable identity)
832   (declare (type function constructor))
833   (declare (type (vector ctype) types))
834   (declare (type ctype identity))
835   (case (length types)
836     (0 identity)
837     (1 (aref types 0))
838     (t (funcall constructor
839                 enumerable
840                 ;; FIXME: This should be just (COERCE TYPES 'LIST), but as
841                 ;; of sbcl-0.6.11.17 the COERCE optimizer is really
842                 ;; brain-dead, so that would generate a full call to
843                 ;; SPECIFIER-TYPE at runtime, so we get into bootstrap
844                 ;; problems in cold init because 'LIST is a compound
845                 ;; type, so we need to MAKE-COMPOUND-TYPE-OR-SOMETHING
846                 ;; before we know what 'LIST is. Once the COERCE
847                 ;; optimizer is less brain-dead, we can make this
848                 ;; (COERCE TYPES 'LIST) again.
849                 #+sb-xc-host (coerce types 'list)
850                 #-sb-xc-host (coerce-to-list types)))))
851
852 (defun maybe-distribute-one-union (union-type types)
853   (let* ((intersection (apply #'type-intersection types))
854          (union (mapcar (lambda (x) (type-intersection x intersection))
855                         (union-type-types union-type))))
856     (if (notany (lambda (x) (or (hairy-type-p x)
857                                 (intersection-type-p x)))
858                 union)
859         union
860         nil)))
861
862 (defun type-intersection (&rest input-types)
863   (let ((simplified-types (simplified-compound-types input-types
864                                                      #'intersection-type-p
865                                                      #'type-intersection2)))
866     (declare (type (vector ctype) simplified-types))
867     ;; We want to have a canonical representation of types (or failing
868     ;; that, punt to HAIRY-TYPE). Canonical representation would have
869     ;; intersections inside unions but not vice versa, since you can
870     ;; always achieve that by the distributive rule. But we don't want
871     ;; to just apply the distributive rule, since it would be too easy
872     ;; to end up with unreasonably huge type expressions. So instead
873     ;; we try to generate a simple type by distributing the union; if
874     ;; the type can't be made simple, we punt to HAIRY-TYPE.
875     (if (and (> (length simplified-types) 1)
876              (some #'union-type-p simplified-types))
877         (let* ((first-union (find-if #'union-type-p simplified-types))
878                (other-types (coerce (remove first-union simplified-types) 'list))
879                (distributed (maybe-distribute-one-union first-union other-types)))
880           (if distributed
881               (apply #'type-union distributed)
882               (make-hairy-type
883                :specifier `(and ,@(map 'list #'type-specifier simplified-types)))))
884         (make-compound-type-or-something #'%make-intersection-type
885                                          simplified-types
886                                          (some #'type-enumerable
887                                                simplified-types)
888                                          *universal-type*))))
889
890 (defun type-union (&rest input-types)
891   (let ((simplified-types (simplified-compound-types input-types
892                                                      #'union-type-p
893                                                      #'type-union2)))
894     (make-compound-type-or-something #'%make-union-type
895                                      simplified-types
896                                      (every #'type-enumerable simplified-types)
897                                      *empty-type*)))
898 \f
899 ;;;; built-in types
900
901 (!define-type-class named)
902
903 (defvar *wild-type*)
904 (defvar *empty-type*)
905 (defvar *universal-type*)
906 (defvar *universal-fun-type*)
907 (!cold-init-forms
908  (macrolet ((frob (name var)
909               `(progn
910                  (setq ,var (make-named-type :name ',name))
911                  (setf (info :type :kind ',name) :primitive)
912                  (setf (info :type :builtin ',name) ,var))))
913    ;; KLUDGE: In ANSI, * isn't really the name of a type, it's just a
914    ;; special symbol which can be stuck in some places where an
915    ;; ordinary type can go, e.g. (ARRAY * 1) instead of (ARRAY T 1).
916    ;; At some point, in order to become more standard, we should
917    ;; convert all the classic CMU CL legacy *s and *WILD-TYPE*s into
918    ;; Ts and *UNIVERSAL-TYPE*s.
919    (frob * *wild-type*)
920    (frob nil *empty-type*)
921    (frob t *universal-type*))
922  (setf *universal-fun-type*
923        (make-fun-type :wild-args t
924                       :returns *wild-type*)))
925
926 (!define-type-method (named :simple-=) (type1 type2)
927   ;; FIXME: BUG 85: This assertion failed when I added it in
928   ;; sbcl-0.6.11.13. It probably shouldn't fail; but for now it's
929   ;; just commented out.
930   ;;(aver (not (eq type1 *wild-type*))) ; * isn't really a type.
931   (values (eq type1 type2) t))
932
933 (!define-type-method (named :simple-subtypep) (type1 type2)
934   (aver (not (eq type1 *wild-type*))) ; * isn't really a type.
935   (values (or (eq type1 *empty-type*) (eq type2 *wild-type*)) t))
936
937 (!define-type-method (named :complex-subtypep-arg1) (type1 type2)
938   ;; This AVER causes problems if we write accurate methods for the
939   ;; union (and possibly intersection) types which then delegate to
940   ;; us; while a user shouldn't get here, because of the odd status of
941   ;; *wild-type* a type-intersection executed by the compiler can. -
942   ;; CSR, 2002-04-10
943   ;;
944   ;; (aver (not (eq type1 *wild-type*))) ; * isn't really a type.
945   (cond ((eq type1 *empty-type*)
946          t)
947         (;; When TYPE2 might be the universal type in disguise
948          (type-might-contain-other-types-p type2)
949          ;; Now that the UNION and HAIRY COMPLEX-SUBTYPEP-ARG2 methods
950          ;; can delegate to us (more or less as CALL-NEXT-METHOD) when
951          ;; they're uncertain, we can't just barf on COMPOUND-TYPE and
952          ;; HAIRY-TYPEs as we used to. Instead we deal with the
953          ;; problem (where at least part of the problem is cases like
954          ;;   (SUBTYPEP T '(SATISFIES FOO))
955          ;; or
956          ;;   (SUBTYPEP T '(AND (SATISFIES FOO) (SATISFIES BAR)))
957          ;; where the second type is a hairy type like SATISFIES, or
958          ;; is a compound type which might contain a hairy type) by
959          ;; returning uncertainty.
960          (values nil nil))
961         (t
962          ;; By elimination, TYPE1 is the universal type.
963          (aver (or (eq type1 *wild-type*) (eq type1 *universal-type*)))
964          ;; This case would have been picked off by the SIMPLE-SUBTYPEP
965          ;; method, and so shouldn't appear here.
966          (aver (not (eq type2 *universal-type*)))
967          ;; Since TYPE2 is not EQ *UNIVERSAL-TYPE* and is not the
968          ;; universal type in disguise, TYPE2 is not a superset of TYPE1.
969          (values nil t))))
970
971 (!define-type-method (named :complex-subtypep-arg2) (type1 type2)
972   (aver (not (eq type2 *wild-type*))) ; * isn't really a type.
973   (cond ((eq type2 *universal-type*)
974          (values t t))
975         ((hairy-type-p type1)
976          (invoke-complex-subtypep-arg1-method type1 type2))
977         (t
978          ;; FIXME: This seems to rely on there only being 2 or 3
979          ;; HAIRY-TYPE values, and the exclusion of various
980          ;; possibilities above. It would be good to explain it and/or
981          ;; rewrite it so that it's clearer.
982          (values (not (eq type2 *empty-type*)) t))))
983
984 (!define-type-method (named :complex-intersection2) (type1 type2)
985   ;; FIXME: This assertion failed when I added it in sbcl-0.6.11.13.
986   ;; Perhaps when bug 85 is fixed it can be reenabled.
987   ;;(aver (not (eq type2 *wild-type*))) ; * isn't really a type.
988   (hierarchical-intersection2 type1 type2))
989
990 (!define-type-method (named :complex-union2) (type1 type2)
991   ;; Perhaps when bug 85 is fixed this can be reenabled.
992   ;;(aver (not (eq type2 *wild-type*))) ; * isn't really a type.
993   (hierarchical-union2 type1 type2))
994
995 (!define-type-method (named :unparse) (x)
996   (named-type-name x))
997 \f
998 ;;;; hairy and unknown types
999
1000 (!define-type-method (hairy :unparse) (x) (hairy-type-specifier x))
1001
1002 (!define-type-method (hairy :simple-subtypep) (type1 type2)
1003   (let ((hairy-spec1 (hairy-type-specifier type1))
1004         (hairy-spec2 (hairy-type-specifier type2)))
1005     (cond ((and (consp hairy-spec1) (eq (car hairy-spec1) 'not)
1006                 (consp hairy-spec2) (eq (car hairy-spec2) 'not))
1007            (csubtypep (specifier-type (cadr hairy-spec2))
1008                       (specifier-type (cadr hairy-spec1))))
1009           ((equal hairy-spec1 hairy-spec2)
1010            (values t t))
1011           (t
1012            (values nil nil)))))
1013
1014 (!define-type-method (hairy :complex-subtypep-arg2) (type1 type2)
1015   (let ((hairy-spec (hairy-type-specifier type2)))
1016     (cond ((and (consp hairy-spec) (eq (car hairy-spec) 'not))
1017            (let* ((complement-type2 (specifier-type (cadr hairy-spec)))
1018                   (intersection2 (type-intersection2 type1
1019                                                      complement-type2)))
1020              (if intersection2
1021                  (values (eq intersection2 *empty-type*) t)
1022                  (invoke-complex-subtypep-arg1-method type1 type2))))
1023           (t
1024            (invoke-complex-subtypep-arg1-method type1 type2)))))
1025
1026 (!define-type-method (hairy :complex-subtypep-arg1) (type1 type2)
1027   ;; "Incrementally extended heuristic algorithms tend inexorably toward the
1028   ;; incomprehensible." -- http://www.unlambda.com/~james/lambda/lambda.txt
1029   (let ((hairy-spec (hairy-type-specifier type1)))
1030      (cond ((and (consp hairy-spec) (eq (car hairy-spec) 'not))
1031             ;; You may not believe this. I couldn't either. But then I
1032             ;; sat down and drew lots of Venn diagrams. Comments
1033             ;; involving a and b refer to the call (subtypep '(not a)
1034             ;; 'b) -- CSR, 2002-02-27.
1035             (block nil
1036               ;; (Several logical truths in this block are true as
1037               ;; long as b/=T. As of sbcl-0.7.1.28, it seems
1038               ;; impossible to construct a case with b=T where we
1039               ;; actually reach this type method, but we'll test for
1040               ;; and exclude this case anyway, since future
1041               ;; maintenance might make it possible for it to end up
1042               ;; in this code.)
1043               (multiple-value-bind (equal certain)
1044                   (type= type2 (specifier-type t))
1045                 (unless certain
1046                   (return (values nil nil)))
1047                 (when equal
1048                   (return (values t t))))
1049               (let ((complement-type1 (specifier-type (cadr hairy-spec))))
1050                 ;; Do the special cases first, in order to give us a
1051                 ;; chance if subtype/supertype relationships are hairy.
1052                 (multiple-value-bind (equal certain) 
1053                     (type= complement-type1 type2)
1054                   ;; If a = b, ~a is not a subtype of b (unless b=T,
1055                   ;; which was excluded above).
1056                   (unless certain
1057                     (return (values nil nil)))
1058                   (when equal
1059                     (return (values nil t))))
1060                 ;; KLUDGE: ANSI requires that the SUBTYPEP result
1061                 ;; between any two built-in atomic type specifiers
1062                 ;; never be uncertain. This is hard to do cleanly for
1063                 ;; the built-in types whose definitions include
1064                 ;; (NOT FOO), i.e. CONS and RATIO. However, we can do
1065                 ;; it with this hack, which uses our global knowledge
1066                 ;; that our implementation of the type system uses
1067                 ;; disjoint implementation types to represent disjoint
1068                 ;; sets (except when types are contained in other types).
1069                 ;; (This is a KLUDGE because it's fragile. Various
1070                 ;; changes in internal representation in the type
1071                 ;; system could make it start confidently returning
1072                 ;; incorrect results.) -- WHN 2002-03-08
1073                 (unless (or (type-might-contain-other-types-p complement-type1)
1074                             (type-might-contain-other-types-p type2))
1075                   ;; Because of the way our types which don't contain
1076                   ;; other types are disjoint subsets of the space of
1077                   ;; possible values, (SUBTYPEP '(NOT AA) 'B)=NIL when
1078                   ;; AA and B are simple (and B is not T, as checked above).
1079                   (return (values nil t)))
1080                 ;; The old (TYPE= TYPE1 TYPE2) branch would never be
1081                 ;; taken, as TYPE1 and TYPE2 will only be equal if
1082                 ;; they're both NOT types, and then the
1083                 ;; :SIMPLE-SUBTYPEP method would be used instead.
1084                 ;; But a CSUBTYPEP relationship might still hold:
1085                 (multiple-value-bind (equal certain)
1086                     (csubtypep complement-type1 type2)
1087                   ;; If a is a subtype of b, ~a is not a subtype of b
1088                   ;; (unless b=T, which was excluded above).
1089                   (unless certain
1090                     (return (values nil nil)))
1091                   (when equal
1092                     (return (values nil t))))
1093                 (multiple-value-bind (equal certain)
1094                     (csubtypep type2 complement-type1)
1095                   ;; If b is a subtype of a, ~a is not a subtype of b.
1096                   ;; (FIXME: That's not true if a=T. Do we know at
1097                   ;; this point that a is not T?)
1098                   (unless certain
1099                     (return (values nil nil)))
1100                   (when equal
1101                     (return (values nil t))))
1102                 ;; old CSR comment ca. 0.7.2, now obsoleted by the
1103                 ;; SIMPLE-CTYPE? KLUDGE case above:
1104                 ;;   Other cases here would rely on being able to catch
1105                 ;;   all possible cases, which the fragility of this
1106                 ;;   type system doesn't inspire me; for instance, if a
1107                 ;;   is type= to ~b, then we want T, T; if this is not
1108                 ;;   the case and the types are disjoint (have an
1109                 ;;   intersection of *empty-type*) then we want NIL, T;
1110                 ;;   else if the union of a and b is the
1111                 ;;   *universal-type* then we want T, T. So currently we
1112                 ;;   still claim to be unsure about e.g. (subtypep '(not
1113                 ;;   fixnum) 'single-float).
1114                 )))
1115            (t
1116             (values nil nil)))))
1117
1118 (!define-type-method (hairy :complex-=) (type1 type2)
1119   (declare (ignore type1 type2))
1120   (values nil nil))
1121
1122 (!define-type-method (hairy :simple-intersection2 :complex-intersection2)
1123                      (type1 type2)
1124   (if (type= type1 type2)
1125       type1
1126       nil))
1127
1128 (!define-type-method (hairy :simple-=) (type1 type2)
1129   (if (equal (hairy-type-specifier type1)
1130              (hairy-type-specifier type2))
1131       (values t t)
1132       (values nil nil)))
1133
1134 (!def-type-translator not (&whole whole type)
1135   (declare (ignore type))
1136   ;; Check legality of arguments.
1137   (destructuring-bind (not typespec) whole
1138     (declare (ignore not))
1139     (let ((spec (type-specifier (specifier-type typespec)))) ; must be legal typespec
1140       (if (and (listp spec) (eq (car spec) 'not))
1141           ;; canonicalize (not (not foo))
1142           (specifier-type (cadr spec))
1143           (make-hairy-type :specifier whole)))))
1144
1145 (!def-type-translator satisfies (&whole whole fun)
1146   (declare (ignore fun))
1147   ;; Check legality of arguments.
1148   (destructuring-bind (satisfies predicate-name) whole
1149     (declare (ignore satisfies))
1150     (unless (symbolp predicate-name)
1151       (error 'simple-type-error
1152              :datum predicate-name
1153              :expected-type 'symbol
1154              :format-control "~S is not a symbol."
1155              :format-arguments (list predicate-name))))
1156   ;; Create object.
1157   (make-hairy-type :specifier whole))
1158 \f
1159 ;;;; numeric types
1160
1161 (!define-type-class number)
1162
1163 (!define-type-method (number :simple-=) (type1 type2)
1164   (values
1165    (and (eq (numeric-type-class type1) (numeric-type-class type2))
1166         (eq (numeric-type-format type1) (numeric-type-format type2))
1167         (eq (numeric-type-complexp type1) (numeric-type-complexp type2))
1168         (equal (numeric-type-low type1) (numeric-type-low type2))
1169         (equal (numeric-type-high type1) (numeric-type-high type2)))
1170    t))
1171
1172 (!define-type-method (number :unparse) (type)
1173   (let* ((complexp (numeric-type-complexp type))
1174          (low (numeric-type-low type))
1175          (high (numeric-type-high type))
1176          (base (case (numeric-type-class type)
1177                  (integer 'integer)
1178                  (rational 'rational)
1179                  (float (or (numeric-type-format type) 'float))
1180                  (t 'real))))
1181     (let ((base+bounds
1182            (cond ((and (eq base 'integer) high low)
1183                   (let ((high-count (logcount high))
1184                         (high-length (integer-length high)))
1185                     (cond ((= low 0)
1186                            (cond ((= high 0) '(integer 0 0))
1187                                  ((= high 1) 'bit)
1188                                  ((and (= high-count high-length)
1189                                        (plusp high-length))
1190                                   `(unsigned-byte ,high-length))
1191                                  (t
1192                                   `(mod ,(1+ high)))))
1193                           ((and (= low sb!xc:most-negative-fixnum)
1194                                 (= high sb!xc:most-positive-fixnum))
1195                            'fixnum)
1196                           ((and (= low (lognot high))
1197                                 (= high-count high-length)
1198                                 (> high-count 0))
1199                            `(signed-byte ,(1+ high-length)))
1200                           (t
1201                            `(integer ,low ,high)))))
1202                  (high `(,base ,(or low '*) ,high))
1203                  (low
1204                   (if (and (eq base 'integer) (= low 0))
1205                       'unsigned-byte
1206                       `(,base ,low)))
1207                  (t base))))
1208       (ecase complexp
1209         (:real
1210          base+bounds)
1211         (:complex
1212          (if (eq base+bounds 'real)
1213              'complex
1214              `(complex ,base+bounds)))
1215         ((nil)
1216          (aver (eq base+bounds 'real))
1217          'number)))))
1218
1219 ;;; Return true if X is "less than or equal" to Y, taking open bounds
1220 ;;; into consideration. CLOSED is the predicate used to test the bound
1221 ;;; on a closed interval (e.g. <=), and OPEN is the predicate used on
1222 ;;; open bounds (e.g. <). Y is considered to be the outside bound, in
1223 ;;; the sense that if it is infinite (NIL), then the test succeeds,
1224 ;;; whereas if X is infinite, then the test fails (unless Y is also
1225 ;;; infinite).
1226 ;;;
1227 ;;; This is for comparing bounds of the same kind, e.g. upper and
1228 ;;; upper. Use NUMERIC-BOUND-TEST* for different kinds of bounds.
1229 #!-negative-zero-is-not-zero
1230 (defmacro numeric-bound-test (x y closed open)
1231   `(cond ((not ,y) t)
1232          ((not ,x) nil)
1233          ((consp ,x)
1234           (if (consp ,y)
1235               (,closed (car ,x) (car ,y))
1236               (,closed (car ,x) ,y)))
1237          (t
1238           (if (consp ,y)
1239               (,open ,x (car ,y))
1240               (,closed ,x ,y)))))
1241
1242 #!+negative-zero-is-not-zero
1243 (defmacro numeric-bound-test-zero (op x y)
1244   `(if (and (zerop ,x) (zerop ,y) (floatp ,x) (floatp ,y))
1245        (,op (float-sign ,x) (float-sign ,y))
1246        (,op ,x ,y)))
1247
1248 #!+negative-zero-is-not-zero
1249 (defmacro numeric-bound-test (x y closed open)
1250   `(cond ((not ,y) t)
1251          ((not ,x) nil)
1252          ((consp ,x)
1253           (if (consp ,y)
1254               (numeric-bound-test-zero ,closed (car ,x) (car ,y))
1255               (numeric-bound-test-zero ,closed (car ,x) ,y)))
1256          (t
1257           (if (consp ,y)
1258               (numeric-bound-test-zero ,open ,x (car ,y))
1259               (numeric-bound-test-zero ,closed ,x ,y)))))
1260
1261 ;;; This is used to compare upper and lower bounds. This is different
1262 ;;; from the same-bound case:
1263 ;;; -- Since X = NIL is -infinity, whereas y = NIL is +infinity, we
1264 ;;;    return true if *either* arg is NIL.
1265 ;;; -- an open inner bound is "greater" and also squeezes the interval,
1266 ;;;    causing us to use the OPEN test for those cases as well.
1267 #!-negative-zero-is-not-zero
1268 (defmacro numeric-bound-test* (x y closed open)
1269   `(cond ((not ,y) t)
1270          ((not ,x) t)
1271          ((consp ,x)
1272           (if (consp ,y)
1273               (,open (car ,x) (car ,y))
1274               (,open (car ,x) ,y)))
1275          (t
1276           (if (consp ,y)
1277               (,open ,x (car ,y))
1278               (,closed ,x ,y)))))
1279
1280 #!+negative-zero-is-not-zero
1281 (defmacro numeric-bound-test* (x y closed open)
1282   `(cond ((not ,y) t)
1283          ((not ,x) t)
1284          ((consp ,x)
1285           (if (consp ,y)
1286               (numeric-bound-test-zero ,open (car ,x) (car ,y))
1287               (numeric-bound-test-zero ,open (car ,x) ,y)))
1288          (t
1289           (if (consp ,y)
1290               (numeric-bound-test-zero ,open ,x (car ,y))
1291               (numeric-bound-test-zero ,closed ,x ,y)))))
1292
1293 ;;; Return whichever of the numeric bounds X and Y is "maximal"
1294 ;;; according to the predicates CLOSED (e.g. >=) and OPEN (e.g. >).
1295 ;;; This is only meaningful for maximizing like bounds, i.e. upper and
1296 ;;; upper. If MAX-P is true, then we return NIL if X or Y is NIL,
1297 ;;; otherwise we return the other arg.
1298 (defmacro numeric-bound-max (x y closed open max-p)
1299   (once-only ((n-x x)
1300               (n-y y))
1301     `(cond ((not ,n-x) ,(if max-p nil n-y))
1302            ((not ,n-y) ,(if max-p nil n-x))
1303            ((consp ,n-x)
1304             (if (consp ,n-y)
1305                 (if (,closed (car ,n-x) (car ,n-y)) ,n-x ,n-y)
1306                 (if (,open (car ,n-x) ,n-y) ,n-x ,n-y)))
1307            (t
1308             (if (consp ,n-y)
1309                 (if (,open (car ,n-y) ,n-x) ,n-y ,n-x)
1310                 (if (,closed ,n-y ,n-x) ,n-y ,n-x))))))
1311
1312 (!define-type-method (number :simple-subtypep) (type1 type2)
1313   (let ((class1 (numeric-type-class type1))
1314         (class2 (numeric-type-class type2))
1315         (complexp2 (numeric-type-complexp type2))
1316         (format2 (numeric-type-format type2))
1317         (low1 (numeric-type-low type1))
1318         (high1 (numeric-type-high type1))
1319         (low2 (numeric-type-low type2))
1320         (high2 (numeric-type-high type2)))
1321     ;; If one is complex and the other isn't, they are disjoint.
1322     (cond ((not (or (eq (numeric-type-complexp type1) complexp2)
1323                     (null complexp2)))
1324            (values nil t))
1325           ;; If the classes are specified and different, the types are
1326           ;; disjoint unless type2 is rational and type1 is integer.
1327           ((not (or (eq class1 class2)
1328                     (null class2)
1329                     (and (eq class1 'integer)
1330                          (eq class2 'rational))))
1331            (values nil t))
1332           ;; If the float formats are specified and different, the types
1333           ;; are disjoint.
1334           ((not (or (eq (numeric-type-format type1) format2)
1335                     (null format2)))
1336            (values nil t))
1337           ;; Check the bounds.
1338           ((and (numeric-bound-test low1 low2 >= >)
1339                 (numeric-bound-test high1 high2 <= <))
1340            (values t t))
1341           (t
1342            (values nil t)))))
1343
1344 (!define-superclasses number ((generic-number)) !cold-init-forms)
1345
1346 ;;; If the high bound of LOW is adjacent to the low bound of HIGH,
1347 ;;; then return true, otherwise NIL.
1348 (defun numeric-types-adjacent (low high)
1349   (let ((low-bound (numeric-type-high low))
1350         (high-bound (numeric-type-low high)))
1351     (cond ((not (and low-bound high-bound)) nil)
1352           ((and (consp low-bound) (consp high-bound)) nil)
1353           ((consp low-bound)
1354            #!-negative-zero-is-not-zero
1355            (let ((low-value (car low-bound)))
1356              (or (eql low-value high-bound)
1357                  (and (eql low-value -0f0) (eql high-bound 0f0))
1358                  (and (eql low-value 0f0) (eql high-bound -0f0))
1359                  (and (eql low-value -0d0) (eql high-bound 0d0))
1360                  (and (eql low-value 0d0) (eql high-bound -0d0))))
1361            #!+negative-zero-is-not-zero
1362            (eql (car low-bound) high-bound))
1363           ((consp high-bound)
1364            #!-negative-zero-is-not-zero
1365            (let ((high-value (car high-bound)))
1366              (or (eql high-value low-bound)
1367                  (and (eql high-value -0f0) (eql low-bound 0f0))
1368                  (and (eql high-value 0f0) (eql low-bound -0f0))
1369                  (and (eql high-value -0d0) (eql low-bound 0d0))
1370                  (and (eql high-value 0d0) (eql low-bound -0d0))))
1371            #!+negative-zero-is-not-zero
1372            (eql (car high-bound) low-bound))
1373           #!+negative-zero-is-not-zero
1374           ((or (and (eql low-bound -0f0) (eql high-bound 0f0))
1375                (and (eql low-bound -0d0) (eql high-bound 0d0))))
1376           ((and (eq (numeric-type-class low) 'integer)
1377                 (eq (numeric-type-class high) 'integer))
1378            (eql (1+ low-bound) high-bound))
1379           (t
1380            nil))))
1381
1382 ;;; Return a numeric type that is a supertype for both TYPE1 and TYPE2.
1383 ;;;
1384 ;;; ### Note: we give up early to keep from dropping lots of information on
1385 ;;; the floor by returning overly general types.
1386 (!define-type-method (number :simple-union2) (type1 type2)
1387   (declare (type numeric-type type1 type2))
1388   (cond ((csubtypep type1 type2) type2)
1389         ((csubtypep type2 type1) type1)
1390         (t
1391          (let ((class1 (numeric-type-class type1))
1392                (format1 (numeric-type-format type1))
1393                (complexp1 (numeric-type-complexp type1))
1394                (class2 (numeric-type-class type2))
1395                (format2 (numeric-type-format type2))
1396                (complexp2 (numeric-type-complexp type2)))
1397            (when (and (eq class1 class2)
1398                       (eq format1 format2)
1399                       (eq complexp1 complexp2)
1400                       (or (numeric-types-intersect type1 type2)
1401                           (numeric-types-adjacent type1 type2)
1402                           (numeric-types-adjacent type2 type1)))
1403              (make-numeric-type
1404               :class class1
1405               :format format1
1406               :complexp complexp1
1407               :low (numeric-bound-max (numeric-type-low type1)
1408                                       (numeric-type-low type2)
1409                                       <= < t)
1410               :high (numeric-bound-max (numeric-type-high type1)
1411                                        (numeric-type-high type2)
1412                                        >= > t)))))))
1413
1414 (!cold-init-forms
1415   (setf (info :type :kind 'number) :primitive)
1416   (setf (info :type :builtin 'number)
1417         (make-numeric-type :complexp nil)))
1418
1419 (!def-type-translator complex (&optional (typespec '*))
1420   (if (eq typespec '*)
1421       (make-numeric-type :complexp :complex)
1422       (labels ((not-numeric ()
1423                  (error "The component type for COMPLEX is not numeric: ~S"
1424                         typespec))
1425                (not-real ()
1426                  (error "The component type for COMPLEX is not real: ~S"
1427                         typespec))
1428                (complex1 (component-type)
1429                  (unless (numeric-type-p component-type)
1430                    (not-numeric))
1431                  (when (eq (numeric-type-complexp component-type) :complex)
1432                    (not-real))
1433                  (modified-numeric-type component-type :complexp :complex))
1434                (complex-union (component)
1435                  (unless (numberp component)
1436                    (not-numeric))
1437                  ;; KLUDGE: This TYPECASE more or less does
1438                  ;; (UPGRADED-COMPLEX-PART-TYPE (TYPE-OF COMPONENT)),
1439                  ;; (plus a small hack to treat (EQL COMPONENT 0) specially)
1440                  ;; but uses logic cut and pasted from the DEFUN of
1441                  ;; UPGRADED-COMPLEX-PART-TYPE. That's fragile, because
1442                  ;; changing the definition of UPGRADED-COMPLEX-PART-TYPE
1443                  ;; would tend to break the code here. Unfortunately,
1444                  ;; though, reusing UPGRADED-COMPLEX-PART-TYPE here
1445                  ;; would cause another kind of fragility, because
1446                  ;; ANSI's definition of TYPE-OF is so weak that e.g.
1447                  ;; (UPGRADED-COMPLEX-PART-TYPE (TYPE-OF 1/2)) could
1448                  ;; end up being (UPGRADED-COMPLEX-PART-TYPE 'REAL)
1449                  ;; instead of (UPGRADED-COMPLEX-PART-TYPE 'RATIONAL).
1450                  ;; So using TYPE-OF would mean that ANSI-conforming
1451                  ;; maintenance changes in TYPE-OF could break the code here.
1452                  ;; It's not clear how best to fix this. -- WHN 2002-01-21,
1453                  ;; trying to summarize CSR's concerns in his patch
1454                  (typecase component
1455                    (complex (error "The component type for COMPLEX (EQL X) ~
1456                                     is complex: ~S"
1457                                    component))
1458                    ((eql 0) (specifier-type nil)) ; as required by ANSI
1459                    (single-float (specifier-type '(complex single-float)))
1460                    (double-float (specifier-type '(complex double-float)))
1461                    #!+long-float
1462                    (long-float (specifier-type '(complex long-float)))
1463                    (rational (specifier-type '(complex rational)))
1464                    (t (specifier-type '(complex real))))))
1465         (let ((ctype (specifier-type typespec)))
1466           (typecase ctype
1467             (numeric-type (complex1 ctype))
1468             (union-type (apply #'type-union
1469                                ;; FIXME: This code could suffer from
1470                                ;; (admittedly very obscure) cases of
1471                                ;; bug 145 e.g. when TYPE is
1472                                ;;   (OR (AND INTEGER (SATISFIES ODDP))
1473                                ;;       (AND FLOAT (SATISFIES FOO))
1474                                ;; and not even report the problem very well.
1475                                (mapcar #'complex1
1476                                        (union-type-types ctype))))
1477             ;; MEMBER-TYPE is almost the same as UNION-TYPE, but
1478             ;; there's a gotcha: (COMPLEX (EQL 0)) is, according to
1479             ;; ANSI, equal to type NIL, the empty set.
1480             (member-type (apply #'type-union
1481                                 (mapcar #'complex-union
1482                                         (member-type-members ctype))))
1483             (t
1484              (multiple-value-bind (subtypep certainly)
1485                  (csubtypep ctype (specifier-type 'real))
1486                (if (and (not subtypep) certainly)
1487                    (not-real)
1488                    ;; ANSI just says that TYPESPEC is any subtype of
1489                    ;; type REAL, not necessarily a NUMERIC-TYPE. In
1490                    ;; particular, at this point TYPESPEC could legally be
1491                    ;; an intersection type like (AND REAL (SATISFIES ODDP)),
1492                    ;; in which case we fall through the logic above and
1493                    ;; end up here, stumped.
1494                    (bug "~@<(known bug #145): The type ~S is too hairy to be 
1495                          used for a COMPLEX component.~:@>"
1496                         typespec)))))))))
1497
1498 ;;; If X is *, return NIL, otherwise return the bound, which must be a
1499 ;;; member of TYPE or a one-element list of a member of TYPE.
1500 #!-sb-fluid (declaim (inline canonicalized-bound))
1501 (defun canonicalized-bound (bound type)
1502   (cond ((eq bound '*) nil)
1503         ((or (sb!xc:typep bound type)
1504              (and (consp bound)
1505                   (sb!xc:typep (car bound) type)
1506                   (null (cdr bound))))
1507           bound)
1508         (t
1509          (error "Bound is not ~S, a ~S or a list of a ~S: ~S"
1510                 '*
1511                 type
1512                 type
1513                 bound))))
1514
1515 (!def-type-translator integer (&optional (low '*) (high '*))
1516   (let* ((l (canonicalized-bound low 'integer))
1517          (lb (if (consp l) (1+ (car l)) l))
1518          (h (canonicalized-bound high 'integer))
1519          (hb (if (consp h) (1- (car h)) h)))
1520     (if (and hb lb (< hb lb))
1521         ;; previously we threw an error here:
1522         ;; (error "Lower bound ~S is greater than upper bound ~S." l h))
1523         ;; but ANSI doesn't say anything about that, so:
1524         (specifier-type 'nil)
1525       (make-numeric-type :class 'integer
1526                          :complexp :real
1527                          :enumerable (not (null (and l h)))
1528                          :low lb
1529                          :high hb))))
1530
1531 (defmacro !def-bounded-type (type class format)
1532   `(!def-type-translator ,type (&optional (low '*) (high '*))
1533      (let ((lb (canonicalized-bound low ',type))
1534            (hb (canonicalized-bound high ',type)))
1535        (if (not (numeric-bound-test* lb hb <= <))
1536            ;; as above, previously we did
1537            ;; (error "Lower bound ~S is not less than upper bound ~S." low high))
1538            ;; but it is correct to do
1539            (specifier-type 'nil)
1540          (make-numeric-type :class ',class :format ',format :low lb :high hb)))))
1541
1542 (!def-bounded-type rational rational nil)
1543
1544 ;;; Unlike CMU CL, we represent the types FLOAT and REAL as
1545 ;;; UNION-TYPEs of more primitive types, in order to make
1546 ;;; type representation more unique, avoiding problems in the
1547 ;;; simplification of things like
1548 ;;;   (subtypep '(or (single-float -1.0 1.0) (single-float 0.1))
1549 ;;;             '(or (real -1 7) (single-float 0.1) (single-float -1.0 1.0)))
1550 ;;; When we allowed REAL to remain as a separate NUMERIC-TYPE,
1551 ;;; it was too easy for the first argument to be simplified to
1552 ;;; '(SINGLE-FLOAT -1.0), and for the second argument to be simplified
1553 ;;; to '(OR (REAL -1 7) (SINGLE-FLOAT 0.1)) and then for the
1554 ;;; SUBTYPEP to fail (returning NIL,T instead of T,T) because
1555 ;;; the first argument can't be seen to be a subtype of any of the
1556 ;;; terms in the second argument.
1557 ;;;
1558 ;;; The old CMU CL way was:
1559 ;;;   (!def-bounded-type float float nil)
1560 ;;;   (!def-bounded-type real nil nil)
1561 ;;;
1562 ;;; FIXME: If this new way works for a while with no weird new
1563 ;;; problems, we can go back and rip out support for separate FLOAT
1564 ;;; and REAL flavors of NUMERIC-TYPE. The new way was added in
1565 ;;; sbcl-0.6.11.22, 2001-03-21.
1566 ;;;
1567 ;;; FIXME: It's probably necessary to do something to fix the
1568 ;;; analogous problem with INTEGER and RATIONAL types. Perhaps
1569 ;;; bounded RATIONAL types should be represented as (OR RATIO INTEGER).
1570 (defun coerce-bound (bound type inner-coerce-bound-fun)
1571   (declare (type function inner-coerce-bound-fun))
1572   (cond ((eql bound '*)
1573          bound)
1574         ((consp bound)
1575          (destructuring-bind (inner-bound) bound
1576            (list (funcall inner-coerce-bound-fun inner-bound type))))
1577         (t
1578          (funcall inner-coerce-bound-fun bound type))))
1579 (defun inner-coerce-real-bound (bound type)
1580   (ecase type
1581     (rational (rationalize bound))
1582     (float (if (floatp bound)
1583                bound
1584                ;; Coerce to the widest float format available, to
1585                ;; avoid unnecessary loss of precision:
1586                (coerce bound 'long-float)))))
1587 (defun coerced-real-bound (bound type)
1588   (coerce-bound bound type #'inner-coerce-real-bound))
1589 (defun coerced-float-bound (bound type)
1590   (coerce-bound bound type #'coerce))
1591 (!def-type-translator real (&optional (low '*) (high '*))
1592   (specifier-type `(or (float ,(coerced-real-bound  low 'float)
1593                               ,(coerced-real-bound high 'float))
1594                        (rational ,(coerced-real-bound  low 'rational)
1595                                  ,(coerced-real-bound high 'rational)))))
1596 (!def-type-translator float (&optional (low '*) (high '*))
1597   (specifier-type 
1598    `(or (single-float ,(coerced-float-bound  low 'single-float)
1599                       ,(coerced-float-bound high 'single-float))
1600         (double-float ,(coerced-float-bound  low 'double-float)
1601                       ,(coerced-float-bound high 'double-float))
1602         #!+long-float ,(error "stub: no long float support yet"))))
1603
1604 (defmacro !define-float-format (f)
1605   `(!def-bounded-type ,f float ,f))
1606
1607 (!define-float-format short-float)
1608 (!define-float-format single-float)
1609 (!define-float-format double-float)
1610 (!define-float-format long-float)
1611
1612 (defun numeric-types-intersect (type1 type2)
1613   (declare (type numeric-type type1 type2))
1614   (let* ((class1 (numeric-type-class type1))
1615          (class2 (numeric-type-class type2))
1616          (complexp1 (numeric-type-complexp type1))
1617          (complexp2 (numeric-type-complexp type2))
1618          (format1 (numeric-type-format type1))
1619          (format2 (numeric-type-format type2))
1620          (low1 (numeric-type-low type1))
1621          (high1 (numeric-type-high type1))
1622          (low2 (numeric-type-low type2))
1623          (high2 (numeric-type-high type2)))
1624     ;; If one is complex and the other isn't, then they are disjoint.
1625     (cond ((not (or (eq complexp1 complexp2)
1626                     (null complexp1) (null complexp2)))
1627            nil)
1628           ;; If either type is a float, then the other must either be
1629           ;; specified to be a float or unspecified. Otherwise, they
1630           ;; are disjoint.
1631           ((and (eq class1 'float)
1632                 (not (member class2 '(float nil)))) nil)
1633           ((and (eq class2 'float)
1634                 (not (member class1 '(float nil)))) nil)
1635           ;; If the float formats are specified and different, the
1636           ;; types are disjoint.
1637           ((not (or (eq format1 format2) (null format1) (null format2)))
1638            nil)
1639           (t
1640            ;; Check the bounds. This is a bit odd because we must
1641            ;; always have the outer bound of the interval as the
1642            ;; second arg.
1643            (if (numeric-bound-test high1 high2 <= <)
1644                (or (and (numeric-bound-test low1 low2 >= >)
1645                         (numeric-bound-test* low1 high2 <= <))
1646                    (and (numeric-bound-test low2 low1 >= >)
1647                         (numeric-bound-test* low2 high1 <= <)))
1648                (or (and (numeric-bound-test* low2 high1 <= <)
1649                         (numeric-bound-test low2 low1 >= >))
1650                    (and (numeric-bound-test high2 high1 <= <)
1651                         (numeric-bound-test* high2 low1 >= >))))))))
1652
1653 ;;; Take the numeric bound X and convert it into something that can be
1654 ;;; used as a bound in a numeric type with the specified CLASS and
1655 ;;; FORMAT. If UP-P is true, then we round up as needed, otherwise we
1656 ;;; round down. UP-P true implies that X is a lower bound, i.e. (N) > N.
1657 ;;;
1658 ;;; This is used by NUMERIC-TYPE-INTERSECTION to mash the bound into
1659 ;;; the appropriate type number. X may only be a float when CLASS is
1660 ;;; FLOAT.
1661 ;;;
1662 ;;; ### Note: it is possible for the coercion to a float to overflow
1663 ;;; or underflow. This happens when the bound doesn't fit in the
1664 ;;; specified format. In this case, we should really return the
1665 ;;; appropriate {Most | Least}-{Positive | Negative}-XXX-Float float
1666 ;;; of desired format. But these conditions aren't currently signalled
1667 ;;; in any useful way.
1668 ;;;
1669 ;;; Also, when converting an open rational bound into a float we
1670 ;;; should probably convert it to a closed bound of the closest float
1671 ;;; in the specified format. KLUDGE: In general, open float bounds are
1672 ;;; screwed up. -- (comment from original CMU CL)
1673 (defun round-numeric-bound (x class format up-p)
1674   (if x
1675       (let ((cx (if (consp x) (car x) x)))
1676         (ecase class
1677           ((nil rational) x)
1678           (integer
1679            (if (and (consp x) (integerp cx))
1680                (if up-p (1+ cx) (1- cx))
1681                (if up-p (ceiling cx) (floor cx))))
1682           (float
1683            (let ((res (if format (coerce cx format) (float cx))))
1684              (if (consp x) (list res) res)))))
1685       nil))
1686
1687 ;;; Handle the case of type intersection on two numeric types. We use
1688 ;;; TYPES-EQUAL-OR-INTERSECT to throw out the case of types with no
1689 ;;; intersection. If an attribute in TYPE1 is unspecified, then we use
1690 ;;; TYPE2's attribute, which must be at least as restrictive. If the
1691 ;;; types intersect, then the only attributes that can be specified
1692 ;;; and different are the class and the bounds.
1693 ;;;
1694 ;;; When the class differs, we use the more restrictive class. The
1695 ;;; only interesting case is RATIONAL/INTEGER, since RATIONAL includes
1696 ;;; INTEGER.
1697 ;;;
1698 ;;; We make the result lower (upper) bound the maximum (minimum) of
1699 ;;; the argument lower (upper) bounds. We convert the bounds into the
1700 ;;; appropriate numeric type before maximizing. This avoids possible
1701 ;;; confusion due to mixed-type comparisons (but I think the result is
1702 ;;; the same).
1703 (!define-type-method (number :simple-intersection2) (type1 type2)
1704   (declare (type numeric-type type1 type2))
1705   (if (numeric-types-intersect type1 type2)
1706       (let* ((class1 (numeric-type-class type1))
1707              (class2 (numeric-type-class type2))
1708              (class (ecase class1
1709                       ((nil) class2)
1710                       ((integer float) class1)
1711                       (rational (if (eq class2 'integer)
1712                                        'integer
1713                                        'rational))))
1714              (format (or (numeric-type-format type1)
1715                          (numeric-type-format type2))))
1716         (make-numeric-type
1717          :class class
1718          :format format
1719          :complexp (or (numeric-type-complexp type1)
1720                        (numeric-type-complexp type2))
1721          :low (numeric-bound-max
1722                (round-numeric-bound (numeric-type-low type1)
1723                                     class format t)
1724                (round-numeric-bound (numeric-type-low type2)
1725                                     class format t)
1726                > >= nil)
1727          :high (numeric-bound-max
1728                 (round-numeric-bound (numeric-type-high type1)
1729                                      class format nil)
1730                 (round-numeric-bound (numeric-type-high type2)
1731                                      class format nil)
1732                 < <= nil)))
1733       *empty-type*))
1734
1735 ;;; Given two float formats, return the one with more precision. If
1736 ;;; either one is null, return NIL.
1737 (defun float-format-max (f1 f2)
1738   (when (and f1 f2)
1739     (dolist (f *float-formats* (error "bad float format: ~S" f1))
1740       (when (or (eq f f1) (eq f f2))
1741         (return f)))))
1742
1743 ;;; Return the result of an operation on TYPE1 and TYPE2 according to
1744 ;;; the rules of numeric contagion. This is always NUMBER, some float
1745 ;;; format (possibly complex) or RATIONAL. Due to rational
1746 ;;; canonicalization, there isn't much we can do here with integers or
1747 ;;; rational complex numbers.
1748 ;;;
1749 ;;; If either argument is not a NUMERIC-TYPE, then return NUMBER. This
1750 ;;; is useful mainly for allowing types that are technically numbers,
1751 ;;; but not a NUMERIC-TYPE.
1752 (defun numeric-contagion (type1 type2)
1753   (if (and (numeric-type-p type1) (numeric-type-p type2))
1754       (let ((class1 (numeric-type-class type1))
1755             (class2 (numeric-type-class type2))
1756             (format1 (numeric-type-format type1))
1757             (format2 (numeric-type-format type2))
1758             (complexp1 (numeric-type-complexp type1))
1759             (complexp2 (numeric-type-complexp type2)))
1760         (cond ((or (null complexp1)
1761                    (null complexp2))
1762                (specifier-type 'number))
1763               ((eq class1 'float)
1764                (make-numeric-type
1765                 :class 'float
1766                 :format (ecase class2
1767                           (float (float-format-max format1 format2))
1768                           ((integer rational) format1)
1769                           ((nil)
1770                            ;; A double-float with any real number is a
1771                            ;; double-float.
1772                            #!-long-float
1773                            (if (eq format1 'double-float)
1774                              'double-float
1775                              nil)
1776                            ;; A long-float with any real number is a
1777                            ;; long-float.
1778                            #!+long-float
1779                            (if (eq format1 'long-float)
1780                              'long-float
1781                              nil)))
1782                 :complexp (if (or (eq complexp1 :complex)
1783                                   (eq complexp2 :complex))
1784                               :complex
1785                               :real)))
1786               ((eq class2 'float) (numeric-contagion type2 type1))
1787               ((and (eq complexp1 :real) (eq complexp2 :real))
1788                (make-numeric-type
1789                 :class (and class1 class2 'rational)
1790                 :complexp :real))
1791               (t
1792                (specifier-type 'number))))
1793       (specifier-type 'number)))
1794 \f
1795 ;;;; array types
1796
1797 (!define-type-class array)
1798
1799 ;;; What this does depends on the setting of the
1800 ;;; *USE-IMPLEMENTATION-TYPES* switch. If true, return the specialized
1801 ;;; element type, otherwise return the original element type.
1802 (defun specialized-element-type-maybe (type)
1803   (declare (type array-type type))
1804   (if *use-implementation-types*
1805       (array-type-specialized-element-type type)
1806       (array-type-element-type type)))
1807
1808 (!define-type-method (array :simple-=) (type1 type2)
1809   (values (and (equal (array-type-dimensions type1)
1810                       (array-type-dimensions type2))
1811                (eq (array-type-complexp type1)
1812                    (array-type-complexp type2))
1813                (type= (specialized-element-type-maybe type1)
1814                       (specialized-element-type-maybe type2)))
1815           t))
1816
1817 (!define-type-method (array :unparse) (type)
1818   (let ((dims (array-type-dimensions type))
1819         (eltype (type-specifier (array-type-element-type type)))
1820         (complexp (array-type-complexp type)))
1821     (cond ((eq dims '*)
1822            (if (eq eltype '*)
1823                (if complexp 'array 'simple-array)
1824                (if complexp `(array ,eltype) `(simple-array ,eltype))))
1825           ((= (length dims) 1)
1826            (if complexp
1827                (if (eq (car dims) '*)
1828                    (case eltype
1829                      (bit 'bit-vector)
1830                      (base-char 'base-string)
1831                      (character 'string)
1832                      (* 'vector)
1833                      (t `(vector ,eltype)))
1834                    (case eltype
1835                      (bit `(bit-vector ,(car dims)))
1836                      (base-char `(base-string ,(car dims)))
1837                      (character `(string ,(car dims)))
1838                      (t `(vector ,eltype ,(car dims)))))
1839                (if (eq (car dims) '*)
1840                    (case eltype
1841                      (bit 'simple-bit-vector)
1842                      (base-char 'simple-base-string)
1843                      (character 'simple-string)
1844                      ((t) 'simple-vector)
1845                      (t `(simple-array ,eltype (*))))
1846                    (case eltype
1847                      (bit `(simple-bit-vector ,(car dims)))
1848                      (base-char `(simple-base-string ,(car dims)))
1849                      (character `(simple-string ,(car dims)))
1850                      ((t) `(simple-vector ,(car dims)))
1851                      (t `(simple-array ,eltype ,dims))))))
1852           (t
1853            (if complexp
1854                `(array ,eltype ,dims)
1855                `(simple-array ,eltype ,dims))))))
1856
1857 (!define-type-method (array :simple-subtypep) (type1 type2)
1858   (let ((dims1 (array-type-dimensions type1))
1859         (dims2 (array-type-dimensions type2))
1860         (complexp2 (array-type-complexp type2)))
1861     (cond (;; not subtypep unless dimensions are compatible
1862            (not (or (eq dims2 '*)
1863                     (and (not (eq dims1 '*))
1864                          ;; (sbcl-0.6.4 has trouble figuring out that
1865                          ;; DIMS1 and DIMS2 must be lists at this
1866                          ;; point, and knowing that is important to
1867                          ;; compiling EVERY efficiently.)
1868                          (= (length (the list dims1))
1869                             (length (the list dims2)))
1870                          (every (lambda (x y)
1871                                   (or (eq y '*) (eql x y)))
1872                                 (the list dims1)
1873                                 (the list dims2)))))
1874            (values nil t))
1875           ;; not subtypep unless complexness is compatible
1876           ((not (or (eq complexp2 :maybe)
1877                     (eq (array-type-complexp type1) complexp2)))
1878            (values nil t))
1879           ;; Since we didn't fail any of the tests above, we win
1880           ;; if the TYPE2 element type is wild.
1881           ((eq (array-type-element-type type2) *wild-type*)
1882            (values t t))
1883           (;; Since we didn't match any of the special cases above, we
1884            ;; can't give a good answer unless both the element types
1885            ;; have been defined.
1886            (or (unknown-type-p (array-type-element-type type1))
1887                (unknown-type-p (array-type-element-type type2)))
1888            (values nil nil))
1889           (;; Otherwise, the subtype relationship holds iff the
1890            ;; types are equal, and they're equal iff the specialized
1891            ;; element types are identical.
1892            t
1893            (values (type= (specialized-element-type-maybe type1)
1894                           (specialized-element-type-maybe type2))
1895                    t)))))
1896
1897 (!define-superclasses array
1898   ((string string)
1899    (vector vector)
1900    (array))
1901   !cold-init-forms)
1902
1903 (defun array-types-intersect (type1 type2)
1904   (declare (type array-type type1 type2))
1905   (let ((dims1 (array-type-dimensions type1))
1906         (dims2 (array-type-dimensions type2))
1907         (complexp1 (array-type-complexp type1))
1908         (complexp2 (array-type-complexp type2)))
1909     ;; See whether dimensions are compatible.
1910     (cond ((not (or (eq dims1 '*) (eq dims2 '*)
1911                     (and (= (length dims1) (length dims2))
1912                          (every (lambda (x y)
1913                                   (or (eq x '*) (eq y '*) (= x y)))
1914                                 dims1 dims2))))
1915            (values nil t))
1916           ;; See whether complexpness is compatible.
1917           ((not (or (eq complexp1 :maybe)
1918                     (eq complexp2 :maybe)
1919                     (eq complexp1 complexp2)))
1920            (values nil t))
1921           ;; If either element type is wild, then they intersect.
1922           ;; Otherwise, the types must be identical.
1923           ((or (eq (array-type-element-type type1) *wild-type*)
1924                (eq (array-type-element-type type2) *wild-type*)
1925                (type= (specialized-element-type-maybe type1)
1926                       (specialized-element-type-maybe type2)))
1927
1928            (values t t))
1929           (t
1930            (values nil t)))))
1931
1932 (!define-type-method (array :simple-intersection2) (type1 type2)
1933   (declare (type array-type type1 type2))
1934   (if (array-types-intersect type1 type2)
1935       (let ((dims1 (array-type-dimensions type1))
1936             (dims2 (array-type-dimensions type2))
1937             (complexp1 (array-type-complexp type1))
1938             (complexp2 (array-type-complexp type2))
1939             (eltype1 (array-type-element-type type1))
1940             (eltype2 (array-type-element-type type2)))
1941         (specialize-array-type
1942          (make-array-type
1943           :dimensions (cond ((eq dims1 '*) dims2)
1944                             ((eq dims2 '*) dims1)
1945                             (t
1946                              (mapcar (lambda (x y) (if (eq x '*) y x))
1947                                      dims1 dims2)))
1948           :complexp (if (eq complexp1 :maybe) complexp2 complexp1)
1949           :element-type (if (eq eltype1 *wild-type*) eltype2 eltype1))))
1950       *empty-type*))
1951
1952 ;;; Check a supplied dimension list to determine whether it is legal,
1953 ;;; and return it in canonical form (as either '* or a list).
1954 (defun canonical-array-dimensions (dims)
1955   (typecase dims
1956     ((member *) dims)
1957     (integer
1958      (when (minusp dims)
1959        (error "Arrays can't have a negative number of dimensions: ~S" dims))
1960      (when (>= dims sb!xc:array-rank-limit)
1961        (error "array type with too many dimensions: ~S" dims))
1962      (make-list dims :initial-element '*))
1963     (list
1964      (when (>= (length dims) sb!xc:array-rank-limit)
1965        (error "array type with too many dimensions: ~S" dims))
1966      (dolist (dim dims)
1967        (unless (eq dim '*)
1968          (unless (and (integerp dim)
1969                       (>= dim 0)
1970                       (< dim sb!xc:array-dimension-limit))
1971            (error "bad dimension in array type: ~S" dim))))
1972      dims)
1973     (t
1974      (error "Array dimensions is not a list, integer or *:~%  ~S" dims))))
1975 \f
1976 ;;;; MEMBER types
1977
1978 (!define-type-class member)
1979
1980 (!define-type-method (member :unparse) (type)
1981   (let ((members (member-type-members type)))
1982     (if (equal members '(nil))
1983         'null
1984         `(member ,@members))))
1985
1986 (!define-type-method (member :simple-subtypep) (type1 type2)
1987   (values (subsetp (member-type-members type1) (member-type-members type2))
1988           t))
1989
1990 (!define-type-method (member :complex-subtypep-arg1) (type1 type2)
1991   (every/type (swapped-args-fun #'ctypep)
1992               type2
1993               (member-type-members type1)))
1994
1995 ;;; We punt if the odd type is enumerable and intersects with the
1996 ;;; MEMBER type. If not enumerable, then it is definitely not a
1997 ;;; subtype of the MEMBER type.
1998 (!define-type-method (member :complex-subtypep-arg2) (type1 type2)
1999   (cond ((not (type-enumerable type1)) (values nil t))
2000         ((types-equal-or-intersect type1 type2)
2001          (invoke-complex-subtypep-arg1-method type1 type2))
2002         (t (values nil t))))
2003
2004 (!define-type-method (member :simple-intersection2) (type1 type2)
2005   (let ((mem1 (member-type-members type1))
2006         (mem2 (member-type-members type2)))
2007     (cond ((subsetp mem1 mem2) type1)
2008           ((subsetp mem2 mem1) type2)
2009           (t
2010            (let ((res (intersection mem1 mem2)))
2011              (if res
2012                  (make-member-type :members res)
2013                  *empty-type*))))))
2014
2015 (!define-type-method (member :complex-intersection2) (type1 type2)
2016   (block punt                
2017     (collect ((members))
2018       (let ((mem2 (member-type-members type2)))
2019         (dolist (member mem2)
2020           (multiple-value-bind (val win) (ctypep member type1)
2021             (unless win
2022               (return-from punt nil))
2023             (when val (members member))))
2024         (cond ((subsetp mem2 (members)) type2)
2025               ((null (members)) *empty-type*)
2026               (t
2027                (make-member-type :members (members))))))))
2028
2029 ;;; We don't need a :COMPLEX-UNION2, since the only interesting case is
2030 ;;; a union type, and the member/union interaction is handled by the
2031 ;;; union type method.
2032 (!define-type-method (member :simple-union2) (type1 type2)
2033   (let ((mem1 (member-type-members type1))
2034         (mem2 (member-type-members type2)))
2035     (cond ((subsetp mem1 mem2) type2)
2036           ((subsetp mem2 mem1) type1)
2037           (t
2038            (make-member-type :members (union mem1 mem2))))))
2039
2040 (!define-type-method (member :simple-=) (type1 type2)
2041   (let ((mem1 (member-type-members type1))
2042         (mem2 (member-type-members type2)))
2043     (values (and (subsetp mem1 mem2)
2044                  (subsetp mem2 mem1))
2045             t)))
2046
2047 (!define-type-method (member :complex-=) (type1 type2)
2048   (if (type-enumerable type1)
2049       (multiple-value-bind (val win) (csubtypep type2 type1)
2050         (if (or val (not win))
2051             (values nil nil)
2052             (values nil t)))
2053       (values nil t)))
2054
2055 (!def-type-translator member (&rest members)
2056   (if members
2057     (make-member-type :members (remove-duplicates members))
2058     *empty-type*))
2059 \f
2060 ;;;; intersection types
2061 ;;;;
2062 ;;;; Until version 0.6.10.6, SBCL followed the original CMU CL approach
2063 ;;;; of punting on all AND types, not just the unreasonably complicated
2064 ;;;; ones. The change was motivated by trying to get the KEYWORD type
2065 ;;;; to behave sensibly:
2066 ;;;;    ;; reasonable definition
2067 ;;;;    (DEFTYPE KEYWORD () '(AND SYMBOL (SATISFIES KEYWORDP)))
2068 ;;;;    ;; reasonable behavior
2069 ;;;;    (AVER (SUBTYPEP 'KEYWORD 'SYMBOL))
2070 ;;;; Without understanding a little about the semantics of AND, we'd
2071 ;;;; get (SUBTYPEP 'KEYWORD 'SYMBOL)=>NIL,NIL and, for entirely
2072 ;;;; parallel reasons, (SUBTYPEP 'RATIO 'NUMBER)=>NIL,NIL. That's
2073 ;;;; not so good..)
2074 ;;;;
2075 ;;;; We still follow the example of CMU CL to some extent, by punting
2076 ;;;; (to the opaque HAIRY-TYPE) on sufficiently complicated types
2077 ;;;; involving AND.
2078
2079 (!define-type-class intersection)
2080
2081 ;;; A few intersection types have special names. The others just get
2082 ;;; mechanically unparsed.
2083 (!define-type-method (intersection :unparse) (type)
2084   (declare (type ctype type))
2085   (or (find type '(ratio bignum keyword) :key #'specifier-type :test #'type=)
2086       `(and ,@(mapcar #'type-specifier (intersection-type-types type)))))
2087
2088 ;;; shared machinery for type equality: true if every type in the set
2089 ;;; TYPES1 matches a type in the set TYPES2 and vice versa
2090 (defun type=-set (types1 types2)
2091   (flet (;; true if every type in the set X matches a type in the set Y
2092          (type<=-set (x y)
2093            (declare (type list x y))
2094            (every (lambda (xelement)
2095                     (position xelement y :test #'type=))
2096                   x)))
2097     (values (and (type<=-set types1 types2)
2098                  (type<=-set types2 types1))
2099             t)))
2100
2101 ;;; Two intersection types are equal if their subtypes are equal sets.
2102 ;;;
2103 ;;; FIXME: Might it be better to use
2104 ;;;   (AND (SUBTYPEP X Y) (SUBTYPEP Y X))
2105 ;;; instead, since SUBTYPEP is the usual relationship that we care
2106 ;;; most about, so it would be good to leverage any ingenuity there
2107 ;;; in this more obscure method?
2108 (!define-type-method (intersection :simple-=) (type1 type2)
2109   (type=-set (intersection-type-types type1)
2110              (intersection-type-types type2)))
2111
2112 (defun %intersection-complex-subtypep-arg1 (type1 type2)
2113   (any/type (swapped-args-fun #'csubtypep)
2114             type2
2115             (intersection-type-types type1)))
2116
2117 (!define-type-method (intersection :simple-subtypep) (type1 type2)
2118   (every/type #'%intersection-complex-subtypep-arg1
2119               type1
2120               (intersection-type-types type2)))
2121
2122 (!define-type-method (intersection :complex-subtypep-arg1) (type1 type2)
2123   (%intersection-complex-subtypep-arg1 type1 type2))
2124
2125 (!define-type-method (intersection :complex-subtypep-arg2) (type1 type2)
2126   (every/type #'csubtypep type1 (intersection-type-types type2)))
2127
2128 (!def-type-translator and (&whole whole &rest type-specifiers)
2129   (apply #'type-intersection
2130          (mapcar #'specifier-type
2131                  type-specifiers)))
2132 \f
2133 ;;;; union types
2134
2135 (!define-type-class union)
2136
2137 ;;; The LIST type has a special name. Other union types just get
2138 ;;; mechanically unparsed.
2139 (!define-type-method (union :unparse) (type)
2140   (declare (type ctype type))
2141   (if (type= type (specifier-type 'list))
2142       'list
2143       `(or ,@(mapcar #'type-specifier (union-type-types type)))))
2144
2145 ;;; Two union types are equal if they are each subtypes of each
2146 ;;; other. We need to be this clever because our complex subtypep
2147 ;;; methods are now more accurate; we don't get infinite recursion
2148 ;;; because the simple-subtypep method delegates to complex-subtypep
2149 ;;; of the individual types of type1. - CSR, 2002-04-09
2150 ;;;
2151 ;;; Previous comment, now obsolete, but worth keeping around because
2152 ;;; it is true, though too strong a condition:
2153 ;;;
2154 ;;; Two union types are equal if their subtypes are equal sets.
2155 (!define-type-method (union :simple-=) (type1 type2)
2156   (multiple-value-bind (subtype certain?)
2157       (csubtypep type1 type2)
2158     (if subtype
2159         (csubtypep type2 type1)
2160         ;; we might as well become as certain as possible.
2161         (if certain?
2162             (values nil t)
2163             (multiple-value-bind (subtype certain?)
2164                 (csubtypep type2 type1)
2165               (declare (ignore subtype))
2166               (values nil certain?))))))
2167
2168 (!define-type-method (union :complex-=) (type1 type2)
2169   (declare (ignore type1))
2170   (if (some #'hairy-type-p (union-type-types type2))
2171       (values nil nil)
2172       (values nil t)))
2173
2174 ;;; Similarly, a union type is a subtype of another if and only if
2175 ;;; every element of TYPE1 is a subtype of TYPE2.
2176 (defun union-simple-subtypep (type1 type2)
2177   (every/type (swapped-args-fun #'union-complex-subtypep-arg2)
2178               type2
2179               (union-type-types type1)))
2180
2181 (!define-type-method (union :simple-subtypep) (type1 type2)
2182   (union-simple-subtypep type1 type2))
2183   
2184 (defun union-complex-subtypep-arg1 (type1 type2)
2185   (every/type (swapped-args-fun #'csubtypep)
2186               type2
2187               (union-type-types type1)))
2188
2189 (!define-type-method (union :complex-subtypep-arg1) (type1 type2)
2190   (union-complex-subtypep-arg1 type1 type2))
2191
2192 (defun union-complex-subtypep-arg2 (type1 type2)
2193   (multiple-value-bind (sub-value sub-certain?)
2194       ;; was: (any/type #'csubtypep type1 (union-type-types type2)),
2195       ;; which turns out to be too restrictive, causing bug 91.
2196       ;;
2197       ;; the following reimplementation might look dodgy.  It is
2198       ;; dodgy. It depends on the union :complex-= method not doing
2199       ;; very much work -- certainly, not using subtypep. Reasoning:
2200       (progn
2201         ;; At this stage, we know that type2 is a union type and type1
2202         ;; isn't. We might as well check this, though:
2203         (aver (union-type-p type2))
2204         (aver (not (union-type-p type1)))
2205         ;;     A is a subset of (B1 u B2)
2206         ;; <=> A n (B1 u B2) = A
2207         ;; <=> (A n B1) u (A n B2) = A
2208         ;;
2209         ;; But, we have to be careful not to delegate this type= to
2210         ;; something that could invoke subtypep, which might get us
2211         ;; back here -> stack explosion. We therefore ensure that the
2212         ;; second type (which is the one that's dispatched on) is
2213         ;; either a union type (where we've ensured that the complex-=
2214         ;; method will not call subtypep) or something with no union
2215         ;; types involved, in which case we'll never come back here.
2216         ;;
2217         ;; If we don't do this, then e.g.
2218         ;; (SUBTYPEP '(MEMBER 3) '(OR (SATISFIES FOO) (SATISFIES BAR)))
2219         ;; would loop infinitely, as the member :complex-= method is
2220         ;; implemented in terms of subtypep.
2221         ;;
2222         ;; Ouch. - CSR, 2002-04-10
2223         (type= type1
2224                (apply #'type-union
2225                       (mapcar (lambda (x) (type-intersection type1 x))
2226                               (union-type-types type2)))))
2227     (if sub-certain?
2228         (values sub-value sub-certain?)
2229         ;; The ANY/TYPE expression above is a sufficient condition for
2230         ;; subsetness, but not a necessary one, so we might get a more
2231         ;; certain answer by this CALL-NEXT-METHOD-ish step when the
2232         ;; ANY/TYPE expression is uncertain.
2233         (invoke-complex-subtypep-arg1-method type1 type2))))
2234
2235 (!define-type-method (union :complex-subtypep-arg2) (type1 type2)
2236   (union-complex-subtypep-arg2 type1 type2))
2237
2238 (!define-type-method (union :simple-intersection2 :complex-intersection2)
2239                      (type1 type2)
2240   ;; The CSUBTYPEP clauses here let us simplify e.g.
2241   ;;   (TYPE-INTERSECTION2 (SPECIFIER-TYPE 'LIST)
2242   ;;                       (SPECIFIER-TYPE '(OR LIST VECTOR)))
2243   ;; (where LIST is (OR CONS NULL)).
2244   ;;
2245   ;; The tests are more or less (CSUBTYPEP TYPE1 TYPE2) and vice
2246   ;; versa, but it's important that we pre-expand them into
2247   ;; specialized operations on individual elements of
2248   ;; UNION-TYPE-TYPES, instead of using the ordinary call to
2249   ;; CSUBTYPEP, in order to avoid possibly invoking any methods which
2250   ;; might in turn invoke (TYPE-INTERSECTION2 TYPE1 TYPE2) and thus
2251   ;; cause infinite recursion.
2252   ;;
2253   ;; Within this method, type2 is guaranteed to be a union type:
2254   (aver (union-type-p type2))
2255   ;; Make sure to call only the applicable methods...
2256   (cond ((and (union-type-p type1)
2257               (union-simple-subtypep type1 type2)) type1)
2258         ((and (union-type-p type1)
2259               (union-simple-subtypep type2 type1)) type2)
2260         ((and (not (union-type-p type1))
2261               (union-complex-subtypep-arg2 type1 type2))
2262          type1)
2263         ((and (not (union-type-p type1))
2264               (union-complex-subtypep-arg1 type2 type1))
2265          type2)
2266         (t 
2267          ;; KLUDGE: This code accumulates a sequence of TYPE-UNION2
2268          ;; operations in a particular order, and gives up if any of
2269          ;; the sub-unions turn out not to be simple. In other cases
2270          ;; ca. sbcl-0.6.11.15, that approach to taking a union was a
2271          ;; bad idea, since it can overlook simplifications which
2272          ;; might occur if the terms were accumulated in a different
2273          ;; order. It's possible that that will be a problem here too.
2274          ;; However, I can't think of a good example to demonstrate
2275          ;; it, and without an example to demonstrate it I can't write
2276          ;; test cases, and without test cases I don't want to
2277          ;; complicate the code to address what's still a hypothetical
2278          ;; problem. So I punted. -- WHN 2001-03-20
2279          (let ((accumulator *empty-type*))
2280            (dolist (t2 (union-type-types type2) accumulator)
2281              (setf accumulator
2282                    (type-union2 accumulator
2283                                 (type-intersection type1 t2)))
2284              ;; When our result isn't simple any more (because
2285              ;; TYPE-UNION2 was unable to give us a simple result)
2286              (unless accumulator
2287                (return nil)))))))
2288
2289 (!def-type-translator or (&rest type-specifiers)
2290   (apply #'type-union
2291          (mapcar #'specifier-type
2292                  type-specifiers)))
2293 \f
2294 ;;;; CONS types
2295
2296 (!define-type-class cons)
2297
2298 (!def-type-translator cons (&optional (car-type-spec '*) (cdr-type-spec '*))
2299   (make-cons-type (specifier-type car-type-spec)
2300                   (specifier-type cdr-type-spec)))
2301  
2302 (!define-type-method (cons :unparse) (type)
2303   (let ((car-eltype (type-specifier (cons-type-car-type type)))
2304         (cdr-eltype (type-specifier (cons-type-cdr-type type))))
2305     (if (and (member car-eltype '(t *))
2306              (member cdr-eltype '(t *)))
2307         'cons
2308         `(cons ,car-eltype ,cdr-eltype))))
2309  
2310 (!define-type-method (cons :simple-=) (type1 type2)
2311   (declare (type cons-type type1 type2))
2312   (and (type= (cons-type-car-type type1) (cons-type-car-type type2))
2313        (type= (cons-type-cdr-type type1) (cons-type-cdr-type type2))))
2314  
2315 (!define-type-method (cons :simple-subtypep) (type1 type2)
2316   (declare (type cons-type type1 type2))
2317   (multiple-value-bind (val-car win-car)
2318       (csubtypep (cons-type-car-type type1) (cons-type-car-type type2))
2319     (multiple-value-bind (val-cdr win-cdr)
2320         (csubtypep (cons-type-cdr-type type1) (cons-type-cdr-type type2))
2321       (if (and val-car val-cdr)
2322           (values t (and win-car win-cdr))
2323           (values nil (or win-car win-cdr))))))
2324  
2325 ;;; Give up if a precise type is not possible, to avoid returning
2326 ;;; overly general types.
2327 (!define-type-method (cons :simple-union2) (type1 type2)
2328   (declare (type cons-type type1 type2))
2329   (let ((car-type1 (cons-type-car-type type1))
2330         (car-type2 (cons-type-car-type type2))
2331         (cdr-type1 (cons-type-cdr-type type1))
2332         (cdr-type2 (cons-type-cdr-type type2)))
2333     (cond ((type= car-type1 car-type2)
2334            (make-cons-type car-type1
2335                            (type-union cdr-type1 cdr-type2)))
2336           ((type= cdr-type1 cdr-type2)
2337            (make-cons-type (type-union cdr-type1 cdr-type2)
2338                            cdr-type1)))))
2339
2340 (!define-type-method (cons :simple-intersection2) (type1 type2)
2341   (declare (type cons-type type1 type2))
2342   (let (car-int2
2343         cdr-int2)
2344     (and (setf car-int2 (type-intersection2 (cons-type-car-type type1)
2345                                             (cons-type-car-type type2)))
2346          (setf cdr-int2 (type-intersection2 (cons-type-cdr-type type1)
2347                                             (cons-type-cdr-type type2)))
2348          (make-cons-type car-int2 cdr-int2))))
2349 \f
2350 ;;; Return the type that describes all objects that are in X but not
2351 ;;; in Y. If we can't determine this type, then return NIL.
2352 ;;;
2353 ;;; For now, we only are clever dealing with union and member types.
2354 ;;; If either type is not a union type, then we pretend that it is a
2355 ;;; union of just one type. What we do is remove from X all the types
2356 ;;; that are a subtype any type in Y. If any type in X intersects with
2357 ;;; a type in Y but is not a subtype, then we give up.
2358 ;;;
2359 ;;; We must also special-case any member type that appears in the
2360 ;;; union. We remove from X's members all objects that are TYPEP to Y.
2361 ;;; If Y has any members, we must be careful that none of those
2362 ;;; members are CTYPEP to any of Y's non-member types. We give up in
2363 ;;; this case, since to compute that difference we would have to break
2364 ;;; the type from X into some collection of types that represents the
2365 ;;; type without that particular element. This seems too hairy to be
2366 ;;; worthwhile, given its low utility.
2367 (defun type-difference (x y)
2368   (let ((x-types (if (union-type-p x) (union-type-types x) (list x)))
2369         (y-types (if (union-type-p y) (union-type-types y) (list y))))
2370     (collect ((res))
2371       (dolist (x-type x-types)
2372         (if (member-type-p x-type)
2373             (collect ((members))
2374               (dolist (mem (member-type-members x-type))
2375                 (multiple-value-bind (val win) (ctypep mem y)
2376                   (unless win (return-from type-difference nil))
2377                   (unless val
2378                     (members mem))))
2379               (when (members)
2380                 (res (make-member-type :members (members)))))
2381             (dolist (y-type y-types (res x-type))
2382               (multiple-value-bind (val win) (csubtypep x-type y-type)
2383                 (unless win (return-from type-difference nil))
2384                 (when val (return))
2385                 (when (types-equal-or-intersect x-type y-type)
2386                   (return-from type-difference nil))))))
2387       (let ((y-mem (find-if #'member-type-p y-types)))
2388         (when y-mem
2389           (let ((members (member-type-members y-mem)))
2390             (dolist (x-type x-types)
2391               (unless (member-type-p x-type)
2392                 (dolist (member members)
2393                   (multiple-value-bind (val win) (ctypep member x-type)
2394                     (when (or (not win) val)
2395                       (return-from type-difference nil)))))))))
2396       (apply #'type-union (res)))))
2397 \f
2398 (!def-type-translator array (&optional (element-type '*)
2399                                        (dimensions '*))
2400   (specialize-array-type
2401    (make-array-type :dimensions (canonical-array-dimensions dimensions)
2402                     :element-type (specifier-type element-type))))
2403
2404 (!def-type-translator simple-array (&optional (element-type '*)
2405                                               (dimensions '*))
2406   (specialize-array-type
2407    (make-array-type :dimensions (canonical-array-dimensions dimensions)
2408                     :element-type (specifier-type element-type)
2409                     :complexp nil)))
2410 \f
2411 ;;;; utilities shared between cross-compiler and target system
2412
2413 ;;; Does the type derived from compilation of an actual function
2414 ;;; definition satisfy declarations of a function's type?
2415 (defun defined-ftype-matches-declared-ftype-p (defined-ftype declared-ftype)
2416   (declare (type ctype defined-ftype declared-ftype))
2417   (flet ((is-built-in-class-function-p (ctype)
2418            (and (built-in-class-p ctype)
2419                 (eq (built-in-class-%name ctype) 'function))))
2420     (cond (;; DECLARED-FTYPE could certainly be #<BUILT-IN-CLASS FUNCTION>;
2421            ;; that's what happens when we (DECLAIM (FTYPE FUNCTION FOO)).
2422            (is-built-in-class-function-p declared-ftype)
2423            ;; In that case, any definition satisfies the declaration.
2424            t)
2425           (;; It's not clear whether or how DEFINED-FTYPE might be
2426            ;; #<BUILT-IN-CLASS FUNCTION>, but it's not obviously
2427            ;; invalid, so let's handle that case too, just in case.
2428            (is-built-in-class-function-p defined-ftype)
2429            ;; No matter what DECLARED-FTYPE might be, we can't prove
2430            ;; that an object of type FUNCTION doesn't satisfy it, so
2431            ;; we return success no matter what.
2432            t)
2433           (;; Otherwise both of them must be FUN-TYPE objects.
2434            t
2435            ;; FIXME: For now we only check compatibility of the return
2436            ;; type, not argument types, and we don't even check the
2437            ;; return type very precisely (as per bug 94a). It would be
2438            ;; good to do a better job. Perhaps to check the
2439            ;; compatibility of the arguments, we should (1) redo
2440            ;; VALUES-TYPES-EQUAL-OR-INTERSECT as
2441            ;; ARGS-TYPES-EQUAL-OR-INTERSECT, and then (2) apply it to
2442            ;; the ARGS-TYPE slices of the FUN-TYPEs. (ARGS-TYPE
2443            ;; is a base class both of VALUES-TYPE and of FUN-TYPE.)
2444            (values-types-equal-or-intersect
2445             (fun-type-returns defined-ftype)
2446             (fun-type-returns declared-ftype))))))
2447            
2448 ;;; This messy case of CTYPE for NUMBER is shared between the
2449 ;;; cross-compiler and the target system.
2450 (defun ctype-of-number (x)
2451   (let ((num (if (complexp x) (realpart x) x)))
2452     (multiple-value-bind (complexp low high)
2453         (if (complexp x)
2454             (let ((imag (imagpart x)))
2455               (values :complex (min num imag) (max num imag)))
2456             (values :real num num))
2457       (make-numeric-type :class (etypecase num
2458                                   (integer 'integer)
2459                                   (rational 'rational)
2460                                   (float 'float))
2461                          :format (and (floatp num) (float-format-name num))
2462                          :complexp complexp
2463                          :low low
2464                          :high high))))
2465 \f
2466 (locally
2467   ;; Why SAFETY 0? To suppress the is-it-the-right-structure-type
2468   ;; checking for declarations in structure accessors. Otherwise we
2469   ;; can get caught in a chicken-and-egg bootstrapping problem, whose
2470   ;; symptom on x86 OpenBSD sbcl-0.pre7.37.flaky5.22 is an illegal
2471   ;; instruction trap. I haven't tracked it down, but I'm guessing it
2472   ;; has to do with setting LAYOUTs when the LAYOUT hasn't been set
2473   ;; yet. -- WHN
2474   (declare (optimize (safety 0)))
2475   (!defun-from-collected-cold-init-forms !late-type-cold-init))
2476
2477 (/show0 "late-type.lisp end of file")