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