0.6.7.22: removed CVS dollar-Header-dollar tags from sources
[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 (!begin-collecting-cold-init-forms)
20
21 ;;; ### Remaining incorrectnesses:
22 ;;;
23 ;;; TYPE-UNION (and the OR type) doesn't properly canonicalize an
24 ;;; exhaustive partition or coalesce contiguous ranges of numeric
25 ;;; types.
26 ;;;
27 ;;; There are all sorts of nasty problems with open bounds on FLOAT
28 ;;; types (and probably FLOAT types in general.)
29 ;;;
30 ;;; RATIO and BIGNUM are not recognized as numeric types.
31
32 ;;; FIXME: It seems to me that this should be set to NIL by default,
33 ;;; and perhaps not even optionally set to T.
34 (defvar *use-implementation-types* t
35   #!+sb-doc
36   "*USE-IMPLEMENTATION-TYPES* is a semi-public flag which determines how
37    restrictive we are in determining type membership. If two types are the
38    same in the implementation, then we will consider them them the same when
39    this switch is on. When it is off, we try to be as restrictive as the
40    language allows, allowing us to detect more errors. Currently, this only
41    affects array types.")
42
43 (!cold-init-forms (setq *use-implementation-types* t))
44
45 ;;; These functions are used as method for types which need a complex
46 ;;; subtypep method to handle some superclasses, but cover a subtree
47 ;;; of the type graph (i.e. there is no simple way for any other type
48 ;;; class to be a subtype.) There are always still complex ways,
49 ;;; namely UNION and MEMBER types, so we must give TYPE1's method a
50 ;;; chance to run, instead of immediately returning NIL, T.
51 (defun delegate-complex-subtypep-arg2 (type1 type2)
52   (let ((subtypep-arg1
53          (type-class-complex-subtypep-arg1
54           (type-class-info type1))))
55     (if subtypep-arg1
56         (funcall subtypep-arg1 type1 type2)
57         (values nil t))))
58 (defun delegate-complex-intersection (type1 type2)
59   (let ((method (type-class-complex-intersection (type-class-info type1))))
60     (if (and method (not (eq method #'delegate-complex-intersection)))
61         (funcall method type2 type1)
62         (vanilla-intersection type1 type2))))
63
64 ;;; This is used by DEFINE-SUPERCLASSES to define the SUBTYPE-ARG1
65 ;;; method. INFO is a list of conses (SUPERCLASS-CLASS .
66 ;;; {GUARD-TYPE-SPECIFIER | NIL}). This will never be called with a
67 ;;; hairy type as TYPE2, since the hairy type TYPE2 method gets first
68 ;;; crack.
69 ;;;
70 ;;; FIXME: Declare this as INLINE, since it's only used in one place.
71 (defun has-superclasses-complex-subtypep-arg1 (type1 type2 info)
72   (values
73    (and (sb!xc:typep type2 'sb!xc:class)
74         (dolist (x info nil)
75           (when (or (not (cdr x))
76                     (csubtypep type1 (specifier-type (cdr x))))
77             (return
78              (or (eq type2 (car x))
79                  (let ((inherits (layout-inherits (class-layout (car x)))))
80                    (dotimes (i (length inherits) nil)
81                      (when (eq type2 (layout-class (svref inherits i)))
82                        (return t)))))))))
83    t))
84
85 ;;; This function takes a list of specs, each of the form
86 ;;;    (SUPERCLASS-NAME &OPTIONAL GUARD).
87 ;;; Consider one spec (with no guard): any instance of the named
88 ;;; TYPE-CLASS is also a subtype of the named superclass and of any of
89 ;;; its superclasses. If there are multiple specs, then some will have
90 ;;; guards. We choose the first spec whose guard is a supertype of
91 ;;; TYPE1 and use its superclass. In effect, a sequence of guards
92 ;;;    G0, G1, G2
93 ;;; is actually
94 ;;;    G0,(and G1 (not G0)), (and G2 (not (or G0 G1))).
95 ;;;
96 ;;; WHEN controls when the forms are executed.
97 (defmacro define-superclasses (type-class-name specs when)
98   (let ((type-class (gensym "TYPE-CLASS-"))
99         (info (gensym "INFO")))
100     `(,when
101        (let ((,type-class (type-class-or-lose ',type-class-name))
102              (,info (mapcar (lambda (spec)
103                               (destructuring-bind
104                                   (super &optional guard)
105                                   spec
106                                 (cons (sb!xc:find-class super) guard)))
107                             ',specs)))
108          (setf (type-class-complex-subtypep-arg1 ,type-class)
109                (lambda (type1 type2)
110                  (has-superclasses-complex-subtypep-arg1 type1 type2 ,info)))
111          (setf (type-class-complex-subtypep-arg2 ,type-class)
112                #'delegate-complex-subtypep-arg2)
113          (setf (type-class-complex-intersection ,type-class)
114                #'delegate-complex-intersection)))))
115 \f
116 ;;;; FUNCTION and VALUES types
117 ;;;;
118 ;;;; Pretty much all of the general type operations are illegal on
119 ;;;; VALUES types, since we can't discriminate using them, do
120 ;;;; SUBTYPEP, etc. FUNCTION types are acceptable to the normal type
121 ;;;; operations, but are generally considered to be equivalent to
122 ;;;; FUNCTION. These really aren't true types in any type theoretic
123 ;;;; sense, but we still parse them into CTYPE structures for two
124 ;;;; reasons:
125
126 ;;;; -- Parsing and unparsing work the same way, and indeed we can't
127 ;;;;    tell whether a type is a function or values type without
128 ;;;;    parsing it.
129 ;;;; -- Many of the places that can be annotated with real types can
130 ;;;;    also be annotated with function or values types.
131
132 ;;; the description of a keyword argument
133 (defstruct (key-info #-sb-xc-host (:pure t))
134   ;; the keyword
135   (name (required-argument) :type keyword)
136   ;; the type of the argument value
137   (type (required-argument) :type ctype))
138
139 (define-type-method (values :simple-subtypep :complex-subtypep-arg1)
140                     (type1 type2)
141   (declare (ignore type2))
142   (error "Subtypep is illegal on this type:~%  ~S" (type-specifier type1)))
143
144 (define-type-method (values :complex-subtypep-arg2)
145                     (type1 type2)
146   (declare (ignore type1))
147   (error "Subtypep is illegal on this type:~%  ~S" (type-specifier type2)))
148
149 (define-type-method (values :unparse) (type)
150   (cons 'values (unparse-args-types type)))
151
152 ;;; Return true if LIST1 and LIST2 have the same elements in the same
153 ;;; positions according to TYPE=. We return NIL, NIL if there is an
154 ;;; uncertain comparison.
155 (defun type=-list (list1 list2)
156   (declare (list list1 list2))
157   (do ((types1 list1 (cdr types1))
158        (types2 list2 (cdr types2)))
159       ((or (null types1) (null types2))
160        (if (or types1 types2)
161            (values nil t)
162            (values t t)))
163     (multiple-value-bind (val win)
164         (type= (first types1) (first types2))
165       (unless win
166         (return (values nil nil)))
167       (unless val
168         (return (values nil t))))))
169
170 (define-type-method (values :simple-=) (type1 type2)
171   (let ((rest1 (args-type-rest type1))
172         (rest2 (args-type-rest type2)))
173     (cond ((or (args-type-keyp type1) (args-type-keyp type2)
174                (args-type-allowp type1) (args-type-allowp type2))
175            (values nil nil))
176           ((and rest1 rest2 (type/= rest1 rest2))
177            (type= rest1 rest2))
178           ((or rest1 rest2)
179            (values nil t))
180           (t
181            (multiple-value-bind (req-val req-win)
182                (type=-list (values-type-required type1)
183                            (values-type-required type2))
184              (multiple-value-bind (opt-val opt-win)
185                  (type=-list (values-type-optional type1)
186                              (values-type-optional type2))
187                (values (and req-val opt-val) (and req-win opt-win))))))))
188
189 (define-type-class function)
190
191 ;;; a flag that we can bind to cause complex function types to be
192 ;;; unparsed as FUNCTION. This is useful when we want a type that we
193 ;;; can pass to TYPEP.
194 (defvar *unparse-function-type-simplify*)
195 (!cold-init-forms (setq *unparse-function-type-simplify* nil))
196
197 (define-type-method (function :unparse) (type)
198   (if *unparse-function-type-simplify*
199       'function
200       (list 'function
201             (if (function-type-wild-args type)
202                 '*
203                 (unparse-args-types type))
204             (type-specifier
205              (function-type-returns type)))))
206
207 ;;; Since all function types are equivalent to FUNCTION, they are all
208 ;;; subtypes of each other.
209 (define-type-method (function :simple-subtypep) (type1 type2)
210   (declare (ignore type1 type2))
211   (values t t))
212
213 (define-superclasses function ((function)) !cold-init-forms)
214
215 ;;; The union or intersection of two FUNCTION types is FUNCTION.
216 (define-type-method (function :simple-union) (type1 type2)
217   (declare (ignore type1 type2))
218   (specifier-type 'function))
219 (define-type-method (function :simple-intersection) (type1 type2)
220   (declare (ignore type1 type2))
221   (values (specifier-type 'function) t))
222
223 ;;; ### Not very real, but good enough for redefining transforms
224 ;;; according to type:
225 (define-type-method (function :simple-=) (type1 type2)
226   (values (equalp type1 type2) t))
227
228 (define-type-class constant :inherits values)
229
230 (define-type-method (constant :unparse) (type)
231   `(constant-argument ,(type-specifier (constant-type-type type))))
232
233 (define-type-method (constant :simple-=) (type1 type2)
234   (type= (constant-type-type type1) (constant-type-type type2)))
235
236 (def-type-translator constant-argument (type)
237   (make-constant-type :type (specifier-type type)))
238
239 ;;; Given a LAMBDA-LIST-like values type specification and an ARGS-TYPE
240 ;;; structure, fill in the slots in the structure accordingly. This is
241 ;;; used for both FUNCTION and VALUES types.
242 (declaim (ftype (function (list args-type) (values)) parse-args-types))
243 (defun parse-args-types (lambda-list result)
244   (multiple-value-bind (required optional restp rest keyp keys allowp aux)
245       (parse-lambda-list lambda-list)
246     (when aux
247       (error "&Aux in a FUNCTION or VALUES type: ~S." lambda-list))
248     (setf (args-type-required result) (mapcar #'specifier-type required))
249     (setf (args-type-optional result) (mapcar #'specifier-type optional))
250     (setf (args-type-rest result) (if restp (specifier-type rest) nil))
251     (setf (args-type-keyp result) keyp)
252     (collect ((key-info))
253       (dolist (key keys)
254         (unless (proper-list-of-length-p key 2)
255           (error "Keyword type description is not a two-list: ~S." key))
256         (let ((kwd (first key)))
257           (when (find kwd (key-info) :key #'key-info-name)
258             (error "Repeated keyword ~S in lambda list: ~S." kwd lambda-list))
259           (key-info (make-key-info :name kwd
260                                    :type (specifier-type (second key))))))
261       (setf (args-type-keywords result) (key-info)))
262     (setf (args-type-allowp result) allowp)
263     (values)))
264
265 ;;; Return the lambda-list-like type specification corresponding
266 ;;; to an ARGS-TYPE.
267 (declaim (ftype (function (args-type) list) unparse-args-types))
268 (defun unparse-args-types (type)
269   (collect ((result))
270
271     (dolist (arg (args-type-required type))
272       (result (type-specifier arg)))
273
274     (when (args-type-optional type)
275       (result '&optional)
276       (dolist (arg (args-type-optional type))
277         (result (type-specifier arg))))
278
279     (when (args-type-rest type)
280       (result '&rest)
281       (result (type-specifier (args-type-rest type))))
282
283     (when (args-type-keyp type)
284       (result '&key)
285       (dolist (key (args-type-keywords type))
286         (result (list (key-info-name key)
287                       (type-specifier (key-info-type key))))))
288
289     (when (args-type-allowp type)
290       (result '&allow-other-keys))
291
292     (result)))
293
294 (def-type-translator function (&optional (args '*) (result '*))
295   (let ((res (make-function-type
296               :returns (values-specifier-type result))))
297     (if (eq args '*)
298         (setf (function-type-wild-args res) t)
299         (parse-args-types args res))
300     res))
301
302 (def-type-translator values (&rest values)
303   (let ((res (make-values-type)))
304     (parse-args-types values res)
305     res))
306 \f
307 ;;;; VALUES types interfaces
308 ;;;;
309 ;;;; We provide a few special operations that can be meaningfully used
310 ;;;; on VALUES types (as well as on any other type).
311
312 ;;; Return the type of the first value indicated by Type. This is used
313 ;;; by people who don't want to have to deal with values types.
314 #!-sb-fluid (declaim (freeze-type values-type) (inline single-value-type))
315 (defun single-value-type (type)
316   (declare (type ctype type))
317   (cond ((values-type-p type)
318          (or (car (args-type-required type))
319              (car (args-type-optional type))
320              (args-type-rest type)
321              *universal-type*))
322         ((eq type *wild-type*)
323          *universal-type*)
324         (t
325          type)))
326
327 ;;; Return the minmum number of arguments that a function can be
328 ;;; called with, and the maximum number or NIL. If not a function
329 ;;; type, return NIL, NIL.
330 (defun function-type-nargs (type)
331   (declare (type ctype type))
332   (if (function-type-p type)
333       (let ((fixed (length (args-type-required type))))
334         (if (or (args-type-rest type)
335                 (args-type-keyp type)
336                 (args-type-allowp type))
337             (values fixed nil)
338             (values fixed (+ fixed (length (args-type-optional type))))))
339       (values nil nil)))
340
341 ;;; Determine if Type corresponds to a definite number of values. The
342 ;;; first value is a list of the types for each value, and the second
343 ;;; value is the number of values. If the number of values is not
344 ;;; fixed, then return NIL and :Unknown.
345 (defun values-types (type)
346   (declare (type ctype type))
347   (cond ((eq type *wild-type*)
348          (values nil :unknown))
349         ((not (values-type-p type))
350          (values (list type) 1))
351         ((or (args-type-optional type)
352              (args-type-rest type)
353              (args-type-keyp type)
354              (args-type-allowp type))
355          (values nil :unknown))
356         (t
357          (let ((req (args-type-required type)))
358            (values (mapcar #'single-value-type req) (length req))))))
359
360 ;;; Return two values:
361 ;;; 1. A list of all the positional (fixed and optional) types.
362 ;;; 2. The &REST type (if any). If keywords allowed, *UNIVERSAL-TYPE*.
363 ;;;    If no keywords or rest, *EMPTY-TYPE*.
364 (defun values-type-types (type)
365   (declare (type values-type type))
366   (values (append (args-type-required type)
367                   (args-type-optional type))
368           (cond ((args-type-keyp type) *universal-type*)
369                 ((args-type-rest type))
370                 (t
371                  *empty-type*))))
372
373 ;;; Return a list of OPERATION applied to the types in TYPES1 and
374 ;;; TYPES2, padding with REST2 as needed. TYPES1 must not be shorter
375 ;;; than TYPES2. The second value is T if OPERATION always returned a
376 ;;; true second value.
377 (defun fixed-values-op (types1 types2 rest2 operation)
378   (declare (list types1 types2) (type ctype rest2) (type function operation))
379   (let ((exact t))
380     (values (mapcar #'(lambda (t1 t2)
381                         (multiple-value-bind (res win)
382                             (funcall operation t1 t2)
383                           (unless win
384                             (setq exact nil))
385                           res))
386                     types1
387                     (append types2
388                             (make-list (- (length types1) (length types2))
389                                        :initial-element rest2)))
390             exact)))
391
392 ;;; If Type isn't a values type, then make it into one:
393 ;;;    <type>  ==>  (values type &rest t)
394 (defun coerce-to-values (type)
395   (declare (type ctype type))
396   (if (values-type-p type)
397       type
398       (make-values-type :required (list type) :rest *universal-type*)))
399
400 ;;; Do the specified OPERATION on TYPE1 and TYPE2, which may be any
401 ;;; type, including VALUES types. With VALUES types such as:
402 ;;;    (VALUES a0 a1)
403 ;;;    (VALUES b0 b1)
404 ;;; we compute the more useful result
405 ;;;    (VALUES (<operation> a0 b0) (<operation> a1 b1))
406 ;;; rather than the precise result
407 ;;;    (<operation> (values a0 a1) (values b0 b1))
408 ;;; This has the virtue of always keeping the VALUES type specifier
409 ;;; outermost, and retains all of the information that is really
410 ;;; useful for static type analysis. We want to know what is always
411 ;;; true of each value independently. It is worthless to know that IF
412 ;;; the first value is B0 then the second will be B1.
413 ;;;
414 ;;; If the VALUES count signatures differ, then we produce a result with
415 ;;; the required VALUE count chosen by NREQ when applied to the number
416 ;;; of required values in TYPE1 and TYPE2. Any &KEY values become
417 ;;; &REST T (anyone who uses keyword values deserves to lose.)
418 ;;;
419 ;;; The second value is true if the result is definitely empty or if
420 ;;; OPERATION returned true as its second value each time we called
421 ;;; it. Since we approximate the intersection of VALUES types, the
422 ;;; second value being true doesn't mean the result is exact.
423 (defun args-type-op (type1 type2 operation nreq)
424   (declare (type ctype type1 type2) (type function operation nreq))
425   (if (or (values-type-p type1) (values-type-p type2))
426       (let ((type1 (coerce-to-values type1))
427             (type2 (coerce-to-values type2)))
428         (multiple-value-bind (types1 rest1) (values-type-types type1)
429           (multiple-value-bind (types2 rest2) (values-type-types type2)
430             (multiple-value-bind (rest rest-exact)
431                 (funcall operation rest1 rest2)
432               (multiple-value-bind (res res-exact)
433                   (if (< (length types1) (length types2))
434                       (fixed-values-op types2 types1 rest1 operation)
435                       (fixed-values-op types1 types2 rest2 operation))
436                 (let* ((req (funcall nreq
437                                      (length (args-type-required type1))
438                                      (length (args-type-required type2))))
439                        (required (subseq res 0 req))
440                        (opt (subseq res req))
441                        (opt-last (position rest opt :test-not #'type=
442                                            :from-end t)))
443                   (if (find *empty-type* required :test #'type=)
444                       (values *empty-type* t)
445                       (values (make-values-type
446                                :required required
447                                :optional (if opt-last
448                                              (subseq opt 0 (1+ opt-last))
449                                              ())
450                                :rest (if (eq rest *empty-type*) nil rest))
451                               (and rest-exact res-exact)))))))))
452       (funcall operation type1 type2)))
453
454 ;;; Do a union or intersection operation on types that might be values
455 ;;; types. The result is optimized for utility rather than exactness,
456 ;;; but it is guaranteed that it will be no smaller (more restrictive)
457 ;;; than the precise result.
458 ;;;
459 ;;; The return convention seems to be analogous to
460 ;;; TYPES-INTERSECT. -- WHN 19990910.
461 (defun-cached (values-type-union :hash-function type-cache-hash
462                                  :hash-bits 8
463                                  :default nil
464                                  :init-wrapper !cold-init-forms)
465               ((type1 eq) (type2 eq))
466   (declare (type ctype type1 type2))
467   (cond ((or (eq type1 *wild-type*) (eq type2 *wild-type*)) *wild-type*)
468         ((eq type1 *empty-type*) type2)
469         ((eq type2 *empty-type*) type1)
470         (t
471          (values (args-type-op type1 type2 #'type-union #'min)))))
472 (defun-cached (values-type-intersection :hash-function type-cache-hash
473                                         :hash-bits 8
474                                         :values 2
475                                         :default (values nil :empty)
476                                         :init-wrapper !cold-init-forms)
477               ((type1 eq) (type2 eq))
478   (declare (type ctype type1 type2))
479   (cond ((eq type1 *wild-type*) (values type2 t))
480         ((eq type2 *wild-type*) (values type1 t))
481         (t
482          (args-type-op type1 type2 #'type-intersection #'max))))
483
484 ;;; This is like TYPES-INTERSECT, except that it sort of works on
485 ;;; VALUES types. Note that due to the semantics of
486 ;;; VALUES-TYPE-INTERSECTION, this might return (VALUES T T) when
487 ;;; there isn't really any intersection (?).
488 ;;;
489 ;;; The return convention seems to be analogous to
490 ;;; TYPES-INTERSECT. -- WHN 19990910.
491 (defun values-types-intersect (type1 type2)
492   (cond ((or (eq type1 *empty-type*) (eq type2 *empty-type*))
493          (values 't t))
494         ((or (values-type-p type1) (values-type-p type2))
495          (multiple-value-bind (res win) (values-type-intersection type1 type2)
496            (values (not (eq res *empty-type*))
497                    win)))
498         (t
499          (types-intersect type1 type2))))
500
501 ;;; a SUBTYPEP-like operation that can be used on any types, including
502 ;;; VALUES types
503 (defun-cached (values-subtypep :hash-function type-cache-hash
504                                :hash-bits 8
505                                :values 2
506                                :default (values nil :empty)
507                                :init-wrapper !cold-init-forms)
508               ((type1 eq) (type2 eq))
509   (declare (type ctype type1 type2))
510   (cond ((eq type2 *wild-type*) (values t t))
511         ((eq type1 *wild-type*)
512          (values (eq type2 *universal-type*) t))
513         ((not (values-types-intersect type1 type2))
514          (values nil t))
515         (t
516          (if (or (values-type-p type1) (values-type-p type2))
517              (let ((type1 (coerce-to-values type1))
518                    (type2 (coerce-to-values type2)))
519                (multiple-value-bind (types1 rest1) (values-type-types type1)
520                  (multiple-value-bind (types2 rest2) (values-type-types type2)
521                    (cond ((< (length (values-type-required type1))
522                              (length (values-type-required type2)))
523                           (values nil t))
524                          ((< (length types1) (length types2))
525                           (values nil nil))
526                          ((or (values-type-keyp type1)
527                               (values-type-keyp type2))
528                           (values nil nil))
529                          (t
530                           (do ((t1 types1 (rest t1))
531                                (t2 types2 (rest t2)))
532                               ((null t2)
533                                (csubtypep rest1 rest2))
534                             (multiple-value-bind (res win-p)
535                                 (csubtypep (first t1) (first t2))
536                               (unless win-p
537                                 (return (values nil nil)))
538                               (unless res
539                                 (return (values nil t))))))))))
540              (csubtypep type1 type2)))))
541 \f
542 ;;;; type method interfaces
543
544 ;;; like SUBTYPEP, only works on CTYPE structures
545 (defun-cached (csubtypep :hash-function type-cache-hash
546                          :hash-bits 8
547                          :values 2
548                          :default (values nil :empty)
549                          :init-wrapper !cold-init-forms)
550               ((type1 eq) (type2 eq))
551   (declare (type ctype type1 type2))
552   (cond ((or (eq type1 type2)
553              (eq type1 *empty-type*)
554              (eq type2 *wild-type*))
555          (values t t))
556         ((or (eq type1 *wild-type*)
557              (eq type2 *empty-type*))
558          (values nil t))
559         (t
560          (invoke-type-method :simple-subtypep :complex-subtypep-arg2
561                              type1 type2
562                              :complex-arg1 :complex-subtypep-arg1))))
563
564 ;;; Just parse the type specifiers and call CSUBTYPE.
565 (defun sb!xc:subtypep (type1 type2)
566   #!+sb-doc
567   "Return two values indicating the relationship between type1 and type2.
568   If values are T and T, type1 definitely is a subtype of type2.
569   If values are NIL and T, type1 definitely is not a subtype of type2.
570   If values are NIL and NIL, it couldn't be determined."
571   (csubtypep (specifier-type type1) (specifier-type type2)))
572
573 ;;; If two types are definitely equivalent, return true. The second
574 ;;; value indicates whether the first value is definitely correct.
575 ;;; This should only fail in the presence of HAIRY types.
576 (defun-cached (type= :hash-function type-cache-hash
577                      :hash-bits 8
578                      :values 2
579                      :default (values nil :empty)
580                      :init-wrapper !cold-init-forms)
581               ((type1 eq) (type2 eq))
582   (declare (type ctype type1 type2))
583   (if (eq type1 type2)
584       (values t t)
585       (invoke-type-method :simple-= :complex-= type1 type2)))
586
587 ;;; Not exactly the negation of TYPE=, since when the relationship is
588 ;;; uncertain, we still return NIL, NIL. This is useful in cases where
589 ;;; the conservative assumption is =.
590 (defun type/= (type1 type2)
591   (declare (type ctype type1 type2))
592   (multiple-value-bind (res win) (type= type1 type2)
593     (if win
594         (values (not res) t)
595         (values nil nil))))
596
597 ;;; Find a type which includes both types. Any inexactness is
598 ;;; represented by the fuzzy element types; we return a single value
599 ;;; that is precise to the best of our knowledge. This result is
600 ;;; simplified into the canonical form, thus is not a UNION type
601 ;;; unless there is no other way to represent the result.
602 (defun-cached (type-union :hash-function type-cache-hash
603                           :hash-bits 8
604                           :init-wrapper !cold-init-forms)
605               ((type1 eq) (type2 eq))
606   (declare (type ctype type1 type2))
607   (if (eq type1 type2)
608       type1
609       (let ((res (invoke-type-method :simple-union :complex-union
610                                      type1 type2
611                                      :default :vanilla)))
612         (cond ((eq res :vanilla)
613                (or (vanilla-union type1 type2)
614                    (make-union-type (list type1 type2))))
615               (res)
616               (t
617                (make-union-type (list type1 type2)))))))
618
619 ;;; Return as restrictive a type as we can discover that is no more
620 ;;; restrictive than the intersection of Type1 and Type2. The second
621 ;;; value is true if the result is exact. At worst, we randomly return
622 ;;; one of the arguments as the first value (trying not to return a
623 ;;; hairy type).
624 (defun-cached (type-intersection :hash-function type-cache-hash
625                                  :hash-bits 8
626                                  :values 2
627                                  :default (values nil :empty)
628                                  :init-wrapper !cold-init-forms)
629               ((type1 eq) (type2 eq))
630   (declare (type ctype type1 type2))
631   (if (eq type1 type2)
632       (values type1 t)
633       (invoke-type-method :simple-intersection :complex-intersection
634                           type1 type2
635                           :default (values *empty-type* t))))
636
637 ;;; The first value is true unless the types don't intersect. The
638 ;;; second value is true if the first value is definitely correct. NIL
639 ;;; is considered to intersect with any type. If T is a subtype of
640 ;;; either type, then we also return T, T. This way we consider hairy
641 ;;; types to intersect with T.
642 (defun types-intersect (type1 type2)
643   (declare (type ctype type1 type2))
644   (if (or (eq type1 *empty-type*) (eq type2 *empty-type*))
645       (values t t)
646       (multiple-value-bind (val winp) (type-intersection type1 type2)
647         (cond ((not winp)
648                (if (or (csubtypep *universal-type* type1)
649                        (csubtypep *universal-type* type2))
650                    (values t t)
651                    (values t nil)))
652               ((eq val *empty-type*) (values nil t))
653               (t (values t t))))))
654
655 ;;; Return a Common Lisp type specifier corresponding to the TYPE
656 ;;; object.
657 (defun type-specifier (type)
658   (declare (type ctype type))
659   (funcall (type-class-unparse (type-class-info type)) type))
660
661 ;;; (VALUES-SPECIFIER-TYPE and SPECIFIER-TYPE moved from here to
662 ;;; early-type.lisp by WHN ca. 19990201.)
663
664 ;;; Take a list of type specifiers, compute the translation and define
665 ;;; it as a builtin type.
666 (declaim (ftype (function (list) (values)) precompute-types))
667 (defun precompute-types (specs)
668   (dolist (spec specs)
669     (let ((res (specifier-type spec)))
670       (unless (unknown-type-p res)
671         (setf (info :type :builtin spec) res)
672         (setf (info :type :kind spec) :primitive))))
673   (values))
674 \f
675 ;;;; built-in types
676
677 (define-type-class named)
678
679 (defvar *wild-type*)
680 (defvar *empty-type*)
681 (defvar *universal-type*)
682
683 (!cold-init-forms
684  (macrolet ((frob (name var)
685               `(progn
686                  (setq ,var (make-named-type :name ',name))
687                  (setf (info :type :kind ',name) :primitive)
688                  (setf (info :type :builtin ',name) ,var))))
689    ;; KLUDGE: In ANSI, * isn't really the name of a type, it's just a
690    ;; special symbol which can be stuck in some places where an
691    ;; ordinary type can go, e.g. (ARRAY * 1) instead of (ARRAY T 1).
692    ;; At some point, in order to become more standard, we should
693    ;; convert all the classic CMU CL legacy *s and *WILD-TYPE*s into
694    ;; Ts and *UNIVERSAL-TYPE*s.
695    (frob * *wild-type*)
696    (frob nil *empty-type*)
697    (frob t *universal-type*)))
698
699 (define-type-method (named :simple-=) (type1 type2)
700   (values (eq type1 type2) t))
701
702 (define-type-method (named :simple-subtypep) (type1 type2)
703   (values (or (eq type1 *empty-type*) (eq type2 *wild-type*)) t))
704
705 (define-type-method (named :complex-subtypep-arg1) (type1 type2)
706   (assert (not (hairy-type-p type2)))
707   (values (eq type1 *empty-type*) t))
708
709 (define-type-method (named :complex-subtypep-arg2) (type1 type2)
710   (if (hairy-type-p type1)
711       (values nil nil)
712       (values (not (eq type2 *empty-type*)) t)))
713
714 (define-type-method (named :complex-intersection) (type1 type2)
715   (vanilla-intersection type1 type2))
716
717 (define-type-method (named :unparse) (x)
718   (named-type-name x))
719 \f
720 ;;;; hairy and unknown types
721
722 (define-type-method (hairy :unparse) (x) (hairy-type-specifier x))
723
724 (define-type-method (hairy :simple-subtypep) (type1 type2)
725   (let ((hairy-spec1 (hairy-type-specifier type1))
726         (hairy-spec2 (hairy-type-specifier type2)))
727     (cond ((and (consp hairy-spec1) (eq (car hairy-spec1) 'not)
728                 (consp hairy-spec2) (eq (car hairy-spec2) 'not))
729            (csubtypep (specifier-type (cadr hairy-spec2))
730                       (specifier-type (cadr hairy-spec1))))
731           ((equal hairy-spec1 hairy-spec2)
732            (values t t))
733           (t
734            (values nil nil)))))
735
736 (define-type-method (hairy :complex-subtypep-arg2) (type1 type2)
737   (let ((hairy-spec (hairy-type-specifier type2)))
738     (cond ((and (consp hairy-spec) (eq (car hairy-spec) 'not))
739            (multiple-value-bind (val win)
740                (type-intersection type1 (specifier-type (cadr hairy-spec)))
741              (if win
742                  (values (eq val *empty-type*) t)
743                  (values nil nil))))
744           (t
745            (values nil nil)))))
746
747 (define-type-method (hairy :complex-subtypep-arg1 :complex-=) (type1 type2)
748   (declare (ignore type1 type2))
749   (values nil nil))
750
751 (define-type-method (hairy :simple-intersection :complex-intersection)
752                     (type1 type2)
753   (declare (ignore type2))
754   (values type1 nil))
755
756 (define-type-method (hairy :complex-union) (type1 type2)
757   (make-union-type (list type1 type2)))
758
759 (define-type-method (hairy :simple-=) (type1 type2)
760   (if (equal (hairy-type-specifier type1)
761              (hairy-type-specifier type2))
762       (values t t)
763       (values nil nil)))
764
765 (def-type-translator not (&whole whole type)
766   (declare (ignore type))
767   (make-hairy-type :specifier whole))
768
769 (def-type-translator satisfies (&whole whole fun)
770   (declare (ignore fun))
771   (make-hairy-type :specifier whole))
772 \f
773 ;;;; numeric types
774
775 ;;; A list of all the float formats, in order of decreasing precision.
776 (eval-when (:compile-toplevel :load-toplevel :execute)
777   (defconstant float-formats
778     '(long-float double-float single-float short-float)))
779
780 ;;; The type of a float format.
781 (deftype float-format () `(member ,@float-formats))
782
783 #!+negative-zero-is-not-zero
784 (defun make-numeric-type (&key class format (complexp :real) low high
785                                enumerable)
786   (flet ((canonicalise-low-bound (x)
787            ;; Canonicalise a low bound of (-0.0) to 0.0.
788            (if (and (consp x) (floatp (car x)) (zerop (car x))
789                     (minusp (float-sign (car x))))
790                (float 0.0 (car x))
791                x))
792          (canonicalise-high-bound (x)
793            ;; Canonicalise a high bound of (+0.0) to -0.0.
794            (if (and (consp x) (floatp (car x)) (zerop (car x))
795                     (plusp (float-sign (car x))))
796                (float -0.0 (car x))
797                x)))
798     (%make-numeric-type :class class
799                         :format format
800                         :complexp complexp
801                         :low (canonicalise-low-bound low)
802                         :high (canonicalise-high-bound high)
803                         :enumerable enumerable)))
804
805 (define-type-class number)
806
807 (define-type-method (number :simple-=) (type1 type2)
808   (values
809    (and (eq (numeric-type-class type1) (numeric-type-class type2))
810         (eq (numeric-type-format type1) (numeric-type-format type2))
811         (eq (numeric-type-complexp type1) (numeric-type-complexp type2))
812         (equal (numeric-type-low type1) (numeric-type-low type2))
813         (equal (numeric-type-high type1) (numeric-type-high type2)))
814    t))
815
816 (define-type-method (number :unparse) (type)
817   (let* ((complexp (numeric-type-complexp type))
818          (low (numeric-type-low type))
819          (high (numeric-type-high type))
820          (base (case (numeric-type-class type)
821                  (integer 'integer)
822                  (rational 'rational)
823                  (float (or (numeric-type-format type) 'float))
824                  (t 'real))))
825     (let ((base+bounds
826            (cond ((and (eq base 'integer) high low)
827                   (let ((high-count (logcount high))
828                         (high-length (integer-length high)))
829                     (cond ((= low 0)
830                            (cond ((= high 0) '(integer 0 0))
831                                  ((= high 1) 'bit)
832                                  ((and (= high-count high-length)
833                                        (plusp high-length))
834                                   `(unsigned-byte ,high-length))
835                                  (t
836                                   `(mod ,(1+ high)))))
837                           ((and (= low sb!vm:*target-most-negative-fixnum*)
838                                 (= high sb!vm:*target-most-positive-fixnum*))
839                            'fixnum)
840                           ((and (= low (lognot high))
841                                 (= high-count high-length)
842                                 (> high-count 0))
843                            `(signed-byte ,(1+ high-length)))
844                           (t
845                            `(integer ,low ,high)))))
846                  (high `(,base ,(or low '*) ,high))
847                  (low
848                   (if (and (eq base 'integer) (= low 0))
849                       'unsigned-byte
850                       `(,base ,low)))
851                  (t base))))
852       (ecase complexp
853         (:real
854          base+bounds)
855         (:complex
856          (if (eq base+bounds 'real)
857              'complex
858              `(complex ,base+bounds)))
859         ((nil)
860          (assert (eq base+bounds 'real))
861          'number)))))
862
863 ;;; Return true if X is "less than or equal" to Y, taking open bounds
864 ;;; into consideration. CLOSED is the predicate used to test the bound
865 ;;; on a closed interval (e.g. <=), and OPEN is the predicate used on
866 ;;; open bounds (e.g. <). Y is considered to be the outside bound, in
867 ;;; the sense that if it is infinite (NIL), then the test succeeds,
868 ;;; whereas if X is infinite, then the test fails (unless Y is also
869 ;;; infinite).
870 ;;;
871 ;;; This is for comparing bounds of the same kind, e.g. upper and
872 ;;; upper. Use NUMERIC-BOUND-TEST* for different kinds of bounds.
873 #!-negative-zero-is-not-zero
874 (defmacro numeric-bound-test (x y closed open)
875   `(cond ((not ,y) t)
876          ((not ,x) nil)
877          ((consp ,x)
878           (if (consp ,y)
879               (,closed (car ,x) (car ,y))
880               (,closed (car ,x) ,y)))
881          (t
882           (if (consp ,y)
883               (,open ,x (car ,y))
884               (,closed ,x ,y)))))
885
886 #!+negative-zero-is-not-zero
887 (defmacro numeric-bound-test-zero (op x y)
888   `(if (and (zerop ,x) (zerop ,y) (floatp ,x) (floatp ,y))
889        (,op (float-sign ,x) (float-sign ,y))
890        (,op ,x ,y)))
891
892 #!+negative-zero-is-not-zero
893 (defmacro numeric-bound-test (x y closed open)
894   `(cond ((not ,y) t)
895          ((not ,x) nil)
896          ((consp ,x)
897           (if (consp ,y)
898               (numeric-bound-test-zero ,closed (car ,x) (car ,y))
899               (numeric-bound-test-zero ,closed (car ,x) ,y)))
900          (t
901           (if (consp ,y)
902               (numeric-bound-test-zero ,open ,x (car ,y))
903               (numeric-bound-test-zero ,closed ,x ,y)))))
904
905 ;;; This is used to compare upper and lower bounds. This is different
906 ;;; from the same-bound case:
907 ;;; -- Since X = NIL is -infinity, whereas y = NIL is +infinity, we
908 ;;;    return true if *either* arg is NIL.
909 ;;; -- an open inner bound is "greater" and also squeezes the interval,
910 ;;;    causing us to use the OPEN test for those cases as well.
911 #!-negative-zero-is-not-zero
912 (defmacro numeric-bound-test* (x y closed open)
913   `(cond ((not ,y) t)
914          ((not ,x) t)
915          ((consp ,x)
916           (if (consp ,y)
917               (,open (car ,x) (car ,y))
918               (,open (car ,x) ,y)))
919          (t
920           (if (consp ,y)
921               (,open ,x (car ,y))
922               (,closed ,x ,y)))))
923
924 #!+negative-zero-is-not-zero
925 (defmacro numeric-bound-test* (x y closed open)
926   `(cond ((not ,y) t)
927          ((not ,x) t)
928          ((consp ,x)
929           (if (consp ,y)
930               (numeric-bound-test-zero ,open (car ,x) (car ,y))
931               (numeric-bound-test-zero ,open (car ,x) ,y)))
932          (t
933           (if (consp ,y)
934               (numeric-bound-test-zero ,open ,x (car ,y))
935               (numeric-bound-test-zero ,closed ,x ,y)))))
936
937 ;;; Return whichever of the numeric bounds X and Y is "maximal"
938 ;;; according to the predicates CLOSED (e.g. >=) and OPEN (e.g. >).
939 ;;; This is only meaningful for maximizing like bounds, i.e. upper and
940 ;;; upper. If MAX-P is true, then we return NIL if X or Y is NIL,
941 ;;; otherwise we return the other arg.
942 (defmacro numeric-bound-max (x y closed open max-p)
943   (once-only ((n-x x)
944               (n-y y))
945     `(cond ((not ,n-x) ,(if max-p nil n-y))
946            ((not ,n-y) ,(if max-p nil n-x))
947            ((consp ,n-x)
948             (if (consp ,n-y)
949                 (if (,closed (car ,n-x) (car ,n-y)) ,n-x ,n-y)
950                 (if (,open (car ,n-x) ,n-y) ,n-x ,n-y)))
951            (t
952             (if (consp ,n-y)
953                 (if (,open (car ,n-y) ,n-x) ,n-y ,n-x)
954                 (if (,closed ,n-y ,n-x) ,n-y ,n-x))))))
955
956 (define-type-method (number :simple-subtypep) (type1 type2)
957   (let ((class1 (numeric-type-class type1))
958         (class2 (numeric-type-class type2))
959         (complexp2 (numeric-type-complexp type2))
960         (format2 (numeric-type-format type2))
961         (low1 (numeric-type-low type1))
962         (high1 (numeric-type-high type1))
963         (low2 (numeric-type-low type2))
964         (high2 (numeric-type-high type2)))
965     ;; If one is complex and the other isn't, they are disjoint.
966     (cond ((not (or (eq (numeric-type-complexp type1) complexp2)
967                     (null complexp2)))
968            (values nil t))
969           ;; If the classes are specified and different, the types are
970           ;; disjoint unless type2 is rational and type1 is integer.
971           ((not (or (eq class1 class2)
972                     (null class2)
973                     (and (eq class1 'integer)
974                          (eq class2 'rational))))
975            (values nil t))
976           ;; If the float formats are specified and different, the types
977           ;; are disjoint.
978           ((not (or (eq (numeric-type-format type1) format2)
979                     (null format2)))
980            (values nil t))
981           ;; Check the bounds.
982           ((and (numeric-bound-test low1 low2 >= >)
983                 (numeric-bound-test high1 high2 <= <))
984            (values t t))
985           (t
986            (values nil t)))))
987
988 (define-superclasses number ((generic-number)) !cold-init-forms)
989
990 ;;; If the high bound of LOW is adjacent to the low bound of HIGH,
991 ;;; then return true, otherwise NIL.
992 (defun numeric-types-adjacent (low high)
993   (let ((low-bound (numeric-type-high low))
994         (high-bound (numeric-type-low high)))
995     (cond ((not (and low-bound high-bound)) nil)
996           ((and (consp low-bound) (consp high-bound)) nil)
997           ((consp low-bound)
998            #!-negative-zero-is-not-zero
999            (let ((low-value (car low-bound)))
1000              (or (eql low-value high-bound)
1001                  (and (eql low-value -0f0) (eql high-bound 0f0))
1002                  (and (eql low-value 0f0) (eql high-bound -0f0))
1003                  (and (eql low-value -0d0) (eql high-bound 0d0))
1004                  (and (eql low-value 0d0) (eql high-bound -0d0))))
1005            #!+negative-zero-is-not-zero
1006            (eql (car low-bound) high-bound))
1007           ((consp high-bound)
1008            #!-negative-zero-is-not-zero
1009            (let ((high-value (car high-bound)))
1010              (or (eql high-value low-bound)
1011                  (and (eql high-value -0f0) (eql low-bound 0f0))
1012                  (and (eql high-value 0f0) (eql low-bound -0f0))
1013                  (and (eql high-value -0d0) (eql low-bound 0d0))
1014                  (and (eql high-value 0d0) (eql low-bound -0d0))))
1015            #!+negative-zero-is-not-zero
1016            (eql (car high-bound) low-bound))
1017           #!+negative-zero-is-not-zero
1018           ((or (and (eql low-bound -0f0) (eql high-bound 0f0))
1019                (and (eql low-bound -0d0) (eql high-bound 0d0))))
1020           ((and (eq (numeric-type-class low) 'integer)
1021                 (eq (numeric-type-class high) 'integer))
1022            (eql (1+ low-bound) high-bound))
1023           (t
1024            nil))))
1025
1026 ;;; Return a numeric type that is a supertype for both TYPE1 and TYPE2.
1027 ;;;
1028 ;;; ### Note: we give up early, so keep from dropping lots of information on
1029 ;;; the floor by returning overly general types.
1030 (define-type-method (number :simple-union) (type1 type2)
1031   (declare (type numeric-type type1 type2))
1032   (cond ((csubtypep type1 type2) type2)
1033         ((csubtypep type2 type1) type1)
1034         (t
1035          (let ((class1 (numeric-type-class type1))
1036                (format1 (numeric-type-format type1))
1037                (complexp1 (numeric-type-complexp type1))
1038                (class2 (numeric-type-class type2))
1039                (format2 (numeric-type-format type2))
1040                (complexp2 (numeric-type-complexp type2)))
1041            (when (and (eq class1 class2)
1042                       (eq format1 format2)
1043                       (eq complexp1 complexp2)
1044                       (or (numeric-types-intersect type1 type2)
1045                           (numeric-types-adjacent type1 type2)
1046                           (numeric-types-adjacent type2 type1)))
1047              (make-numeric-type
1048               :class class1
1049               :format format1
1050               :complexp complexp1
1051               :low (numeric-bound-max (numeric-type-low type1)
1052                                       (numeric-type-low type2)
1053                                       <= < t)
1054               :high (numeric-bound-max (numeric-type-high type1)
1055                                        (numeric-type-high type2)
1056                                        >= > t)))))))
1057
1058 (!cold-init-forms
1059   (setf (info :type :kind 'number) :primitive)
1060   (setf (info :type :builtin 'number)
1061         (make-numeric-type :complexp nil)))
1062
1063 (def-type-translator complex (&optional (spec '*))
1064   (if (eq spec '*)
1065       (make-numeric-type :complexp :complex)
1066       (let ((type (specifier-type spec)))
1067         (unless (numeric-type-p type)
1068           (error "Component type for Complex is not numeric: ~S." spec))
1069         (when (eq (numeric-type-complexp type) :complex)
1070           (error "Component type for Complex is complex: ~S." spec))
1071         (let ((res (copy-numeric-type type)))
1072           (setf (numeric-type-complexp res) :complex)
1073           res))))
1074
1075 ;;; If X is *, return NIL, otherwise return the bound, which must be a
1076 ;;; member of TYPE or a one-element list of a member of TYPE.
1077 #!-sb-fluid (declaim (inline canonicalized-bound))
1078 (defun canonicalized-bound (bound type)
1079   (cond ((eq bound '*) nil)
1080         ((or (sb!xc:typep bound type)
1081              (and (consp bound)
1082                   (sb!xc:typep (car bound) type)
1083                   (null (cdr bound))))
1084           bound)
1085         (t
1086          (error "Bound is not ~S, a ~S or a list of a ~S: ~S"
1087                 '*
1088                 type
1089                 type
1090                 bound))))
1091
1092 (def-type-translator integer (&optional (low '*) (high '*))
1093   (let* ((l (canonicalized-bound low 'integer))
1094          (lb (if (consp l) (1+ (car l)) l))
1095          (h (canonicalized-bound high 'integer))
1096          (hb (if (consp h) (1- (car h)) h)))
1097     (when (and hb lb (< hb lb))
1098       (error "Lower bound ~S is greater than upper bound ~S." l h))
1099     (make-numeric-type :class 'integer
1100                        :complexp :real
1101                        :enumerable (not (null (and l h)))
1102                        :low lb
1103                        :high hb)))
1104
1105 (defmacro def-bounded-type (type class format)
1106   `(def-type-translator ,type (&optional (low '*) (high '*))
1107      (let ((lb (canonicalized-bound low ',type))
1108            (hb (canonicalized-bound high ',type)))
1109        (unless (numeric-bound-test* lb hb <= <)
1110          (error "Lower bound ~S is not less than upper bound ~S." low high))
1111        (make-numeric-type :class ',class :format ',format :low lb :high hb))))
1112
1113 (def-bounded-type rational rational nil)
1114 (def-bounded-type float float nil)
1115 (def-bounded-type real nil nil)
1116
1117 (defmacro define-float-format (f)
1118   `(def-bounded-type ,f float ,f))
1119
1120 (define-float-format short-float)
1121 (define-float-format single-float)
1122 (define-float-format double-float)
1123 (define-float-format long-float)
1124
1125 (defun numeric-types-intersect (type1 type2)
1126   (declare (type numeric-type type1 type2))
1127   (let* ((class1 (numeric-type-class type1))
1128          (class2 (numeric-type-class type2))
1129          (complexp1 (numeric-type-complexp type1))
1130          (complexp2 (numeric-type-complexp type2))
1131          (format1 (numeric-type-format type1))
1132          (format2 (numeric-type-format type2))
1133          (low1 (numeric-type-low type1))
1134          (high1 (numeric-type-high type1))
1135          (low2 (numeric-type-low type2))
1136          (high2 (numeric-type-high type2)))
1137     ;; If one is complex and the other isn't, then they are disjoint.
1138     (cond ((not (or (eq complexp1 complexp2)
1139                     (null complexp1) (null complexp2)))
1140            nil)
1141           ;; If either type is a float, then the other must either be
1142           ;; specified to be a float or unspecified. Otherwise, they
1143           ;; are disjoint.
1144           ((and (eq class1 'float)
1145                 (not (member class2 '(float nil)))) nil)
1146           ((and (eq class2 'float)
1147                 (not (member class1 '(float nil)))) nil)
1148           ;; If the float formats are specified and different, the
1149           ;; types are disjoint.
1150           ((not (or (eq format1 format2) (null format1) (null format2)))
1151            nil)
1152           (t
1153            ;; Check the bounds. This is a bit odd because we must
1154            ;; always have the outer bound of the interval as the
1155            ;; second arg.
1156            (if (numeric-bound-test high1 high2 <= <)
1157                (or (and (numeric-bound-test low1 low2 >= >)
1158                         (numeric-bound-test* low1 high2 <= <))
1159                    (and (numeric-bound-test low2 low1 >= >)
1160                         (numeric-bound-test* low2 high1 <= <)))
1161                (or (and (numeric-bound-test* low2 high1 <= <)
1162                         (numeric-bound-test low2 low1 >= >))
1163                    (and (numeric-bound-test high2 high1 <= <)
1164                         (numeric-bound-test* high2 low1 >= >))))))))
1165
1166 ;;; Take the numeric bound X and convert it into something that can be
1167 ;;; used as a bound in a numeric type with the specified CLASS and
1168 ;;; FORMAT. If UP-P is true, then we round up as needed, otherwise we
1169 ;;; round down. UP-P true implies that X is a lower bound, i.e. (N) > N.
1170 ;;;
1171 ;;; This is used by NUMERIC-TYPE-INTERSECTION to mash the bound into
1172 ;;; the appropriate type number. X may only be a float when CLASS is
1173 ;;; FLOAT.
1174 ;;;
1175 ;;; ### Note: it is possible for the coercion to a float to overflow
1176 ;;; or underflow. This happens when the bound doesn't fit in the
1177 ;;; specified format. In this case, we should really return the
1178 ;;; appropriate {Most | Least}-{Positive | Negative}-XXX-Float float
1179 ;;; of desired format. But these conditions aren't currently signalled
1180 ;;; in any useful way.
1181 ;;;
1182 ;;; Also, when converting an open rational bound into a float we
1183 ;;; should probably convert it to a closed bound of the closest float
1184 ;;; in the specified format. KLUDGE: In general, open float bounds are
1185 ;;; screwed up. -- (comment from original CMU CL)
1186 (defun round-numeric-bound (x class format up-p)
1187   (if x
1188       (let ((cx (if (consp x) (car x) x)))
1189         (ecase class
1190           ((nil rational) x)
1191           (integer
1192            (if (and (consp x) (integerp cx))
1193                (if up-p (1+ cx) (1- cx))
1194                (if up-p (ceiling cx) (floor cx))))
1195           (float
1196            (let ((res (if format (coerce cx format) (float cx))))
1197              (if (consp x) (list res) res)))))
1198       nil))
1199
1200 ;;; Handle the case of TYPE-INTERSECTION on two numeric types. We use
1201 ;;; TYPES-INTERSECT to throw out the case of types with no
1202 ;;; intersection. If an attribute in TYPE1 is unspecified, then we use
1203 ;;; TYPE2's attribute, which must be at least as restrictive. If the
1204 ;;; types intersect, then the only attributes that can be specified
1205 ;;; and different are the class and the bounds.
1206 ;;;
1207 ;;; When the class differs, we use the more restrictive class. The
1208 ;;; only interesting case is RATIONAL/INTEGER, since RATIONAL includes
1209 ;;; INTEGER.
1210 ;;;
1211 ;;; We make the result lower (upper) bound the maximum (minimum) of
1212 ;;; the argument lower (upper) bounds. We convert the bounds into the
1213 ;;; appropriate numeric type before maximizing. This avoids possible
1214 ;;; confusion due to mixed-type comparisons (but I think the result is
1215 ;;; the same).
1216 (define-type-method (number :simple-intersection) (type1 type2)
1217   (declare (type numeric-type type1 type2))
1218   (if (numeric-types-intersect type1 type2)
1219       (let* ((class1 (numeric-type-class type1))
1220              (class2 (numeric-type-class type2))
1221              (class (ecase class1
1222                       ((nil) class2)
1223                       ((integer float) class1)
1224                       (rational (if (eq class2 'integer)
1225                                        'integer
1226                                        'rational))))
1227              (format (or (numeric-type-format type1)
1228                          (numeric-type-format type2))))
1229         (values
1230          (make-numeric-type
1231           :class class
1232           :format format
1233           :complexp (or (numeric-type-complexp type1)
1234                         (numeric-type-complexp type2))
1235           :low (numeric-bound-max
1236                 (round-numeric-bound (numeric-type-low type1)
1237                                      class format t)
1238                 (round-numeric-bound (numeric-type-low type2)
1239                                      class format t)
1240                 > >= nil)
1241           :high (numeric-bound-max
1242                  (round-numeric-bound (numeric-type-high type1)
1243                                       class format nil)
1244                  (round-numeric-bound (numeric-type-high type2)
1245                                       class format nil)
1246                  < <= nil))
1247          t))
1248       (values *empty-type* t)))
1249
1250 ;;; Given two float formats, return the one with more precision. If
1251 ;;; either one is null, return NIL.
1252 (defun float-format-max (f1 f2)
1253   (when (and f1 f2)
1254     (dolist (f float-formats (error "Bad float format: ~S." f1))
1255       (when (or (eq f f1) (eq f f2))
1256         (return f)))))
1257
1258 ;;; Return the result of an operation on Type1 and Type2 according to
1259 ;;; the rules of numeric contagion. This is always NUMBER, some float
1260 ;;; format (possibly complex) or RATIONAL. Due to rational
1261 ;;; canonicalization, there isn't much we can do here with integers or
1262 ;;; rational complex numbers.
1263 ;;;
1264 ;;; If either argument is not a Numeric-Type, then return NUMBER. This
1265 ;;; is useful mainly for allowing types that are technically numbers,
1266 ;;; but not a Numeric-Type.
1267 (defun numeric-contagion (type1 type2)
1268   (if (and (numeric-type-p type1) (numeric-type-p type2))
1269       (let ((class1 (numeric-type-class type1))
1270             (class2 (numeric-type-class type2))
1271             (format1 (numeric-type-format type1))
1272             (format2 (numeric-type-format type2))
1273             (complexp1 (numeric-type-complexp type1))
1274             (complexp2 (numeric-type-complexp type2)))
1275         (cond ((or (null complexp1)
1276                    (null complexp2))
1277                (specifier-type 'number))
1278               ((eq class1 'float)
1279                (make-numeric-type
1280                 :class 'float
1281                 :format (ecase class2
1282                           (float (float-format-max format1 format2))
1283                           ((integer rational) format1)
1284                           ((nil)
1285                            ;; A double-float with any real number is a
1286                            ;; double-float.
1287                            #!-long-float
1288                            (if (eq format1 'double-float)
1289                              'double-float
1290                              nil)
1291                            ;; A long-float with any real number is a
1292                            ;; long-float.
1293                            #!+long-float
1294                            (if (eq format1 'long-float)
1295                              'long-float
1296                              nil)))
1297                 :complexp (if (or (eq complexp1 :complex)
1298                                   (eq complexp2 :complex))
1299                               :complex
1300                               :real)))
1301               ((eq class2 'float) (numeric-contagion type2 type1))
1302               ((and (eq complexp1 :real) (eq complexp2 :real))
1303                (make-numeric-type
1304                 :class (and class1 class2 'rational)
1305                 :complexp :real))
1306               (t
1307                (specifier-type 'number))))
1308       (specifier-type 'number)))
1309 \f
1310 ;;;; array types
1311
1312 (define-type-class array)
1313
1314 ;;; What this does depends on the setting of the
1315 ;;; *USE-IMPLEMENTATION-TYPES* switch. If true, return the specialized
1316 ;;; element type, otherwise return the original element type.
1317 (defun specialized-element-type-maybe (type)
1318   (declare (type array-type type))
1319   (if *use-implementation-types*
1320       (array-type-specialized-element-type type)
1321       (array-type-element-type type)))
1322
1323 (define-type-method (array :simple-=) (type1 type2)
1324   (values (and (equal (array-type-dimensions type1)
1325                       (array-type-dimensions type2))
1326                (eq (array-type-complexp type1)
1327                    (array-type-complexp type2))
1328                (type= (specialized-element-type-maybe type1)
1329                       (specialized-element-type-maybe type2)))
1330           t))
1331
1332 (define-type-method (array :unparse) (type)
1333   (let ((dims (array-type-dimensions type))
1334         (eltype (type-specifier (array-type-element-type type)))
1335         (complexp (array-type-complexp type)))
1336     (cond ((eq dims '*)
1337            (if (eq eltype '*)
1338                (if complexp 'array 'simple-array)
1339                (if complexp `(array ,eltype) `(simple-array ,eltype))))
1340           ((= (length dims) 1)
1341            (if complexp
1342                (if (eq (car dims) '*)
1343                    (case eltype
1344                      (bit 'bit-vector)
1345                      (base-char 'base-string)
1346                      (character 'string)
1347                      (* 'vector)
1348                      (t `(vector ,eltype)))
1349                    (case eltype
1350                      (bit `(bit-vector ,(car dims)))
1351                      (base-char `(base-string ,(car dims)))
1352                      (character `(string ,(car dims)))
1353                      (t `(vector ,eltype ,(car dims)))))
1354                (if (eq (car dims) '*)
1355                    (case eltype
1356                      (bit 'simple-bit-vector)
1357                      (base-char 'simple-base-string)
1358                      (character 'simple-string)
1359                      ((t) 'simple-vector)
1360                      (t `(simple-array ,eltype (*))))
1361                    (case eltype
1362                      (bit `(simple-bit-vector ,(car dims)))
1363                      (base-char `(simple-base-string ,(car dims)))
1364                      (character `(simple-string ,(car dims)))
1365                      ((t) `(simple-vector ,(car dims)))
1366                      (t `(simple-array ,eltype ,dims))))))
1367           (t
1368            (if complexp
1369                `(array ,eltype ,dims)
1370                `(simple-array ,eltype ,dims))))))
1371
1372 (define-type-method (array :simple-subtypep) (type1 type2)
1373   (let ((dims1 (array-type-dimensions type1))
1374         (dims2 (array-type-dimensions type2))
1375         (complexp2 (array-type-complexp type2)))
1376     ;; See whether dimensions are compatible.
1377     (cond ((not (or (eq dims2 '*)
1378                     (and (not (eq dims1 '*))
1379                          ;; (sbcl-0.6.4 has trouble figuring out that
1380                          ;; DIMS1 and DIMS2 must be lists at this
1381                          ;; point, and knowing that is important to
1382                          ;; compiling EVERY efficiently.)
1383                          (= (length (the list dims1))
1384                             (length (the list dims2)))
1385                          (every (lambda (x y)
1386                                   (or (eq y '*) (eql x y)))
1387                                 (the list dims1)
1388                                 (the list dims2)))))
1389            (values nil t))
1390           ;; See whether complexpness is compatible.
1391           ((not (or (eq complexp2 :maybe)
1392                     (eq (array-type-complexp type1) complexp2)))
1393            (values nil t))
1394           ;; If the TYPE2 eltype is wild, we win. Otherwise, the types
1395           ;; must be identical.
1396           ((or (eq (array-type-element-type type2) *wild-type*)
1397                (type= (specialized-element-type-maybe type1)
1398                       (specialized-element-type-maybe type2)))
1399            (values t t))
1400           (t
1401            (values nil t)))))
1402
1403 (define-superclasses array
1404   ((string string)
1405    (vector vector)
1406    (array))
1407   !cold-init-forms)
1408
1409 (defun array-types-intersect (type1 type2)
1410   (declare (type array-type type1 type2))
1411   (let ((dims1 (array-type-dimensions type1))
1412         (dims2 (array-type-dimensions type2))
1413         (complexp1 (array-type-complexp type1))
1414         (complexp2 (array-type-complexp type2)))
1415     ;; See whether dimensions are compatible.
1416     (cond ((not (or (eq dims1 '*) (eq dims2 '*)
1417                     (and (= (length dims1) (length dims2))
1418                          (every #'(lambda (x y)
1419                                     (or (eq x '*) (eq y '*) (= x y)))
1420                                 dims1 dims2))))
1421            (values nil t))
1422           ;; See whether complexpness is compatible.
1423           ((not (or (eq complexp1 :maybe)
1424                     (eq complexp2 :maybe)
1425                     (eq complexp1 complexp2)))
1426            (values nil t))
1427           ;; If either element type is wild, then they intersect.
1428           ;; Otherwise, the types must be identical.
1429           ((or (eq (array-type-element-type type1) *wild-type*)
1430                (eq (array-type-element-type type2) *wild-type*)
1431                (type= (specialized-element-type-maybe type1)
1432                       (specialized-element-type-maybe type2)))
1433
1434            (values t t))
1435           (t
1436            (values nil t)))))
1437
1438 (define-type-method (array :simple-intersection) (type1 type2)
1439   (declare (type array-type type1 type2))
1440   (if (array-types-intersect type1 type2)
1441       (let ((dims1 (array-type-dimensions type1))
1442             (dims2 (array-type-dimensions type2))
1443             (complexp1 (array-type-complexp type1))
1444             (complexp2 (array-type-complexp type2))
1445             (eltype1 (array-type-element-type type1))
1446             (eltype2 (array-type-element-type type2)))
1447         (values
1448          (specialize-array-type
1449           (make-array-type
1450            :dimensions (cond ((eq dims1 '*) dims2)
1451                              ((eq dims2 '*) dims1)
1452                              (t
1453                               (mapcar (lambda (x y) (if (eq x '*) y x))
1454                                       dims1 dims2)))
1455            :complexp (if (eq complexp1 :maybe) complexp2 complexp1)
1456            :element-type (if (eq eltype1 *wild-type*) eltype2 eltype1)))
1457          t))
1458       (values *empty-type* t)))
1459
1460 ;;; Check a supplied dimension list to determine whether it is legal,
1461 ;;; and return it in canonical form (as either '* or a list).
1462 (defun canonical-array-dimensions (dims)
1463   (typecase dims
1464     ((member *) dims)
1465     (integer
1466      (when (minusp dims)
1467        (error "Arrays can't have a negative number of dimensions: ~S" dims))
1468      (when (>= dims sb!xc:array-rank-limit)
1469        (error "array type with too many dimensions: ~S" dims))
1470      (make-list dims :initial-element '*))
1471     (list
1472      (when (>= (length dims) sb!xc:array-rank-limit)
1473        (error "array type with too many dimensions: ~S" dims))
1474      (dolist (dim dims)
1475        (unless (eq dim '*)
1476          (unless (and (integerp dim)
1477                       (>= dim 0)
1478                       (< dim sb!xc:array-dimension-limit))
1479            (error "bad dimension in array type: ~S" dim))))
1480      dims)
1481     (t
1482      (error "Array dimensions is not a list, integer or *:~%  ~S" dims))))
1483 \f
1484 ;;;; MEMBER types
1485
1486 (define-type-class member)
1487
1488 (define-type-method (member :unparse) (type)
1489   (let ((members (member-type-members type)))
1490     (if (equal members '(nil))
1491         'null
1492         `(member ,@members))))
1493
1494 (define-type-method (member :simple-subtypep) (type1 type2)
1495   (values (subsetp (member-type-members type1) (member-type-members type2))
1496           t))
1497
1498 (define-type-method (member :complex-subtypep-arg1) (type1 type2)
1499   (block PUNT
1500     (values (every-type-op ctypep type2 (member-type-members type1)
1501                            :list-first t)
1502             t)))
1503
1504 ;;; We punt if the odd type is enumerable and intersects with the
1505 ;;; MEMBER type. If not enumerable, then it is definitely not a
1506 ;;; subtype of the MEMBER type.
1507 (define-type-method (member :complex-subtypep-arg2) (type1 type2)
1508   (cond ((not (type-enumerable type1)) (values nil t))
1509         ((types-intersect type1 type2) (values nil nil))
1510         (t
1511          (values nil t))))
1512
1513 (define-type-method (member :simple-intersection) (type1 type2)
1514   (let ((mem1 (member-type-members type1))
1515         (mem2 (member-type-members type2)))
1516     (values (cond ((subsetp mem1 mem2) type1)
1517                   ((subsetp mem2 mem1) type2)
1518                   (t
1519                    (let ((res (intersection mem1 mem2)))
1520                      (if res
1521                          (make-member-type :members res)
1522                          *empty-type*))))
1523             t)))
1524
1525 (define-type-method (member :complex-intersection) (type1 type2)
1526   (block PUNT
1527     (collect ((members))
1528       (let ((mem2 (member-type-members type2)))
1529         (dolist (member mem2)
1530           (multiple-value-bind (val win) (ctypep member type1)
1531             (unless win
1532               (return-from PUNT (values type2 nil)))
1533             (when val (members member))))
1534
1535         (values (cond ((subsetp mem2 (members)) type2)
1536                       ((null (members)) *empty-type*)
1537                       (t
1538                        (make-member-type :members (members))))
1539                 t)))))
1540
1541 ;;; We don't need a :COMPLEX-UNION, since the only interesting case is a union
1542 ;;; type, and the member/union interaction is handled by the union type
1543 ;;; method.
1544 (define-type-method (member :simple-union) (type1 type2)
1545   (let ((mem1 (member-type-members type1))
1546         (mem2 (member-type-members type2)))
1547     (cond ((subsetp mem1 mem2) type2)
1548           ((subsetp mem2 mem1) type1)
1549           (t
1550            (make-member-type :members (union mem1 mem2))))))
1551
1552 (define-type-method (member :simple-=) (type1 type2)
1553   (let ((mem1 (member-type-members type1))
1554         (mem2 (member-type-members type2)))
1555     (values (and (subsetp mem1 mem2) (subsetp mem2 mem1))
1556             t)))
1557
1558 (define-type-method (member :complex-=) (type1 type2)
1559   (if (type-enumerable type1)
1560       (multiple-value-bind (val win) (csubtypep type2 type1)
1561         (if (or val (not win))
1562             (values nil nil)
1563             (values nil t)))
1564       (values nil t)))
1565
1566 (def-type-translator member (&rest members)
1567   (if members
1568     (make-member-type :members (remove-duplicates members))
1569     *empty-type*))
1570 \f
1571 ;;;; union types
1572
1573 ;;; Make a union type from the specifier types, setting ENUMERABLE in
1574 ;;; the result if all are enumerable.
1575 (defun make-union-type (types)
1576   (declare (list types))
1577   (%make-union-type (every #'type-enumerable types) types))
1578
1579 (define-type-class union)
1580
1581 ;;; If LIST, then return that, otherwise the OR of the component types.
1582 (define-type-method (union :unparse) (type)
1583   (declare (type ctype type))
1584   (if (type= type (specifier-type 'list))
1585       'list
1586       `(or ,@(mapcar #'type-specifier (union-type-types type)))))
1587
1588 ;;; Two union types are equal if every type in one is equal to some
1589 ;;; type in the other.
1590 (define-type-method (union :simple-=) (type1 type2)
1591   (block PUNT
1592     (let ((types1 (union-type-types type1))
1593           (types2 (union-type-types type2)))
1594       (values (and (dolist (type1 types1 t)
1595                      (unless (any-type-op type= type1 types2)
1596                        (return nil)))
1597                    (dolist (type2 types2 t)
1598                      (unless (any-type-op type= type2 types1)
1599                        (return nil))))
1600               t))))
1601
1602 ;;; Similarly, a union type is a subtype of another if every element
1603 ;;; of TYPE1 is a subtype of some element of TYPE2.
1604 (define-type-method (union :simple-subtypep) (type1 type2)
1605   (block PUNT
1606     (let ((types2 (union-type-types type2)))
1607       (values (dolist (type1 (union-type-types type1) t)
1608                 (unless (any-type-op csubtypep type1 types2)
1609                   (return nil)))
1610               t))))
1611
1612 (define-type-method (union :complex-subtypep-arg1) (type1 type2)
1613   (block PUNT
1614     (values (every-type-op csubtypep type2 (union-type-types type1)
1615                            :list-first t)
1616             t)))
1617
1618 (define-type-method (union :complex-subtypep-arg2) (type1 type2)
1619   (block PUNT
1620     (values (any-type-op csubtypep type1 (union-type-types type2)) t)))
1621
1622 (define-type-method (union :complex-union) (type1 type2)
1623   (let* ((class1 (type-class-info type1)))
1624     (collect ((res))
1625       (let ((this-type type1))
1626         (dolist (type (union-type-types type2)
1627                       (if (res)
1628                           (make-union-type (cons this-type (res)))
1629                           this-type))
1630           (cond ((eq (type-class-info type) class1)
1631                  (let ((union (funcall (type-class-simple-union class1)
1632                                        this-type type)))
1633                    (if union
1634                        (setq this-type union)
1635                        (res type))))
1636                 ((csubtypep type this-type))
1637                 ((csubtypep type1 type) (return type2))
1638                 (t
1639                  (res type))))))))
1640
1641 ;;; For the union of union types, we let the :COMPLEX-UNION method do
1642 ;;; the work.
1643 (define-type-method (union :simple-union) (type1 type2)
1644   (let ((res type1))
1645     (dolist (t2 (union-type-types type2) res)
1646       (setq res (type-union res t2)))))
1647
1648 (define-type-method (union :simple-intersection :complex-intersection)
1649                     (type1 type2)
1650   (let ((res *empty-type*)
1651         (win t))
1652     (dolist (type (union-type-types type2) (values res win))
1653       (multiple-value-bind (int w) (type-intersection type1 type)
1654         (setq res (type-union res int))
1655         (unless w (setq win nil))))))
1656
1657 (def-type-translator or (&rest types)
1658   (reduce #'type-union
1659           (mapcar #'specifier-type types)
1660           :initial-value *empty-type*))
1661
1662 ;;; We don't actually have intersection types, since the result of
1663 ;;; reasonable type intersections is always describable as a union of
1664 ;;; simple types. If something is too hairy to fit this mold, then we
1665 ;;; make a hairy type.
1666 (def-type-translator and (&whole spec &rest types)
1667   (let ((res *wild-type*))
1668     (dolist (type types res)
1669       (let ((ctype (specifier-type type)))
1670         (multiple-value-bind (int win) (type-intersection res ctype)
1671           (unless win
1672             (return (make-hairy-type :specifier spec)))
1673           (setq res int))))))
1674 \f
1675 ;;; Return the type that describes all objects that are in X but not
1676 ;;; in Y. If we can't determine this type, then return NIL.
1677 ;;;
1678 ;;; For now, we only are clever dealing with union and member types.
1679 ;;; If either type is not a union type, then we pretend that it is a
1680 ;;; union of just one type. What we do is remove from X all the types
1681 ;;; that are a subtype any type in Y. If any type in X intersects with
1682 ;;; a type in Y but is not a subtype, then we give up.
1683 ;;;
1684 ;;; We must also special-case any member type that appears in the
1685 ;;; union. We remove from X's members all objects that are TYPEP to Y.
1686 ;;; If Y has any members, we must be careful that none of those
1687 ;;; members are CTYPEP to any of Y's non-member types. We give up in
1688 ;;; this case, since to compute that difference we would have to break
1689 ;;; the type from X into some collection of types that represents the
1690 ;;; type without that particular element. This seems too hairy to be
1691 ;;; worthwhile, given its low utility.
1692 (defun type-difference (x y)
1693   (let ((x-types (if (union-type-p x) (union-type-types x) (list x)))
1694         (y-types (if (union-type-p y) (union-type-types y) (list y))))
1695     (collect ((res))
1696       (dolist (x-type x-types)
1697         (if (member-type-p x-type)
1698             (collect ((members))
1699               (dolist (mem (member-type-members x-type))
1700                 (multiple-value-bind (val win) (ctypep mem y)
1701                   (unless win (return-from type-difference nil))
1702                   (unless val
1703                     (members mem))))
1704               (when (members)
1705                 (res (make-member-type :members (members)))))
1706             (dolist (y-type y-types (res x-type))
1707               (multiple-value-bind (val win) (csubtypep x-type y-type)
1708                 (unless win (return-from type-difference nil))
1709                 (when val (return))
1710                 (when (types-intersect x-type y-type)
1711                   (return-from type-difference nil))))))
1712
1713       (let ((y-mem (find-if #'member-type-p y-types)))
1714         (when y-mem
1715           (let ((members (member-type-members y-mem)))
1716             (dolist (x-type x-types)
1717               (unless (member-type-p x-type)
1718                 (dolist (member members)
1719                   (multiple-value-bind (val win) (ctypep member x-type)
1720                     (when (or (not win) val)
1721                       (return-from type-difference nil)))))))))
1722
1723       (cond ((null (res)) *empty-type*)
1724             ((null (rest (res))) (first (res)))
1725             (t
1726              (make-union-type (res)))))))
1727 \f
1728 (def-type-translator array (&optional (element-type '*)
1729                                       (dimensions '*))
1730   (specialize-array-type
1731    (make-array-type :dimensions (canonical-array-dimensions dimensions)
1732                     :element-type (specifier-type element-type))))
1733
1734 (def-type-translator simple-array (&optional (element-type '*)
1735                                              (dimensions '*))
1736   (specialize-array-type
1737    (make-array-type :dimensions (canonical-array-dimensions dimensions)
1738                     :element-type (specifier-type element-type)
1739                     :complexp nil)))
1740 \f
1741 (!defun-from-collected-cold-init-forms !late-type-cold-init)