0.6.11.13:
[sbcl.git] / src / code / late-type.lisp
1 ;;;; This file contains the definition of non-CLASS types (e.g.
2 ;;;; subtypes of interesting BUILT-IN-CLASSes) and the interfaces to
3 ;;;; the type system. Common Lisp type specifiers are parsed into a
4 ;;;; somewhat canonical internal type representation that supports
5 ;;;; type union, intersection, etc. (Except that ALIEN types have
6 ;;;; moved out..)
7
8 ;;;; This software is part of the SBCL system. See the README file for
9 ;;;; more information.
10 ;;;;
11 ;;;; This software is derived from the CMU CL system, which was
12 ;;;; written at Carnegie Mellon University and released into the
13 ;;;; public domain. The software is in the public domain and is
14 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
15 ;;;; files for more information.
16
17 (in-package "SB!KERNEL")
18
19 (/show0 "late-type.lisp 19")
20
21 (!begin-collecting-cold-init-forms)
22
23 ;;; ### Remaining incorrectnesses:
24 ;;;
25 ;;; TYPE-UNION (and the OR type) doesn't properly canonicalize an
26 ;;; exhaustive partition or coalesce contiguous ranges of numeric
27 ;;; types.
28 ;;;
29 ;;; There are all sorts of nasty problems with open bounds on FLOAT
30 ;;; types (and probably FLOAT types in general.)
31 ;;;
32 ;;; RATIO and BIGNUM are not recognized as numeric types.
33
34 ;;; FIXME: It seems to me that this should be set to NIL by default,
35 ;;; and perhaps not even optionally set to T.
36 (defvar *use-implementation-types* t
37   #!+sb-doc
38   "*USE-IMPLEMENTATION-TYPES* is a semi-public flag which determines how
39    restrictive we are in determining type membership. If two types are the
40    same in the implementation, then we will consider them them the same when
41    this switch is on. When it is off, we try to be as restrictive as the
42    language allows, allowing us to detect more errors. Currently, this only
43    affects array types.")
44
45 (!cold-init-forms (setq *use-implementation-types* t))
46
47 ;;; These functions are used as method for types which need a complex
48 ;;; subtypep method to handle some superclasses, but cover a subtree
49 ;;; of the type graph (i.e. there is no simple way for any other type
50 ;;; class to be a subtype.) There are always still complex ways,
51 ;;; namely UNION and MEMBER types, so we must give TYPE1's method a
52 ;;; chance to run, instead of immediately returning NIL, T.
53 (defun delegate-complex-subtypep-arg2 (type1 type2)
54   (let ((subtypep-arg1
55          (type-class-complex-subtypep-arg1
56           (type-class-info type1))))
57     (if subtypep-arg1
58         (funcall subtypep-arg1 type1 type2)
59         (values nil t))))
60 (defun delegate-complex-intersection2 (type1 type2)
61   (let ((method (type-class-complex-intersection2 (type-class-info type1))))
62     (if (and method (not (eq method #'delegate-complex-intersection2)))
63         (funcall method type2 type1)
64         (hierarchical-intersection2 type1 type2))))
65
66 ;;; This is used by !DEFINE-SUPERCLASSES to define the SUBTYPE-ARG1
67 ;;; method. INFO is a list of conses
68 ;;;   (SUPERCLASS-CLASS . {GUARD-TYPE-SPECIFIER | NIL}).
69 ;;; This will never be called with a hairy type as TYPE2, since the
70 ;;; hairy type TYPE2 method gets first crack.
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-intersection2 ,type-class)
114                #'delegate-complex-intersection2)))))
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 &KEY argument
133 (defstruct (key-info #-sb-xc-host (:pure t)
134                      (:copier nil))
135   ;; the key (not necessarily a keyword in ANSI)
136   (name (required-argument) :type symbol)
137   ;; the type of the argument value
138   (type (required-argument) :type ctype))
139
140 (!define-type-method (values :simple-subtypep :complex-subtypep-arg1)
141                      (type1 type2)
142   (declare (ignore type2))
143   ;; FIXME: should be TYPE-ERROR, here and in next method
144   (error "SUBTYPEP is illegal on this type:~%  ~S" (type-specifier type1)))
145
146 (!define-type-method (values :complex-subtypep-arg2)
147                      (type1 type2)
148   (declare (ignore type1))
149   (error "SUBTYPEP is illegal on this type:~%  ~S" (type-specifier type2)))
150
151 (!define-type-method (values :unparse) (type)
152   (cons 'values (unparse-args-types type)))
153
154 ;;; Return true if LIST1 and LIST2 have the same elements in the same
155 ;;; positions according to TYPE=. We return NIL, NIL if there is an
156 ;;; uncertain comparison.
157 (defun type=-list (list1 list2)
158   (declare (list list1 list2))
159   (do ((types1 list1 (cdr types1))
160        (types2 list2 (cdr types2)))
161       ((or (null types1) (null types2))
162        (if (or types1 types2)
163            (values nil t)
164            (values t t)))
165     (multiple-value-bind (val win)
166         (type= (first types1) (first types2))
167       (unless win
168         (return (values nil nil)))
169       (unless val
170         (return (values nil t))))))
171
172 (!define-type-method (values :simple-=) (type1 type2)
173   (let ((rest1 (args-type-rest type1))
174         (rest2 (args-type-rest type2)))
175     (cond ((or (args-type-keyp type1) (args-type-keyp type2)
176                (args-type-allowp type1) (args-type-allowp type2))
177            (values nil nil))
178           ((and rest1 rest2 (type/= rest1 rest2))
179            (type= rest1 rest2))
180           ((or rest1 rest2)
181            (values nil t))
182           (t
183            (multiple-value-bind (req-val req-win)
184                (type=-list (values-type-required type1)
185                            (values-type-required type2))
186              (multiple-value-bind (opt-val opt-win)
187                  (type=-list (values-type-optional type1)
188                              (values-type-optional type2))
189                (values (and req-val opt-val) (and req-win opt-win))))))))
190
191 (!define-type-class function)
192
193 ;;; a flag that we can bind to cause complex function types to be
194 ;;; unparsed as FUNCTION. This is useful when we want a type that we
195 ;;; can pass to TYPEP.
196 (defvar *unparse-function-type-simplify*)
197 (!cold-init-forms (setq *unparse-function-type-simplify* nil))
198
199 (!define-type-method (function :unparse) (type)
200   (if *unparse-function-type-simplify*
201       'function
202       (list 'function
203             (if (function-type-wild-args type)
204                 '*
205                 (unparse-args-types type))
206             (type-specifier
207              (function-type-returns type)))))
208
209 ;;; Since all function types are equivalent to FUNCTION, they are all
210 ;;; subtypes of each other.
211 (!define-type-method (function :simple-subtypep) (type1 type2)
212   (declare (ignore type1 type2))
213   (values t t))
214
215 (!define-superclasses function ((function)) !cold-init-forms)
216
217 ;;; The union or intersection of two FUNCTION types is FUNCTION.
218 (!define-type-method (function :simple-union) (type1 type2)
219   (declare (ignore type1 type2))
220   (specifier-type 'function))
221 (!define-type-method (function :simple-intersection2) (type1 type2)
222   (declare (ignore type1 type2))
223   (specifier-type 'function))
224
225 ;;; ### Not very real, but good enough for redefining transforms
226 ;;; according to type:
227 (!define-type-method (function :simple-=) (type1 type2)
228   (values (equalp type1 type2) t))
229
230 (!define-type-class constant :inherits values)
231
232 (!define-type-method (constant :unparse) (type)
233   `(constant-argument ,(type-specifier (constant-type-type type))))
234
235 (!define-type-method (constant :simple-=) (type1 type2)
236   (type= (constant-type-type type1) (constant-type-type type2)))
237
238 (!def-type-translator constant-argument (type)
239   (make-constant-type :type (specifier-type type)))
240
241 ;;; Given a LAMBDA-LIST-like values type specification and an ARGS-TYPE
242 ;;; structure, fill in the slots in the structure accordingly. This is
243 ;;; used for both FUNCTION and VALUES types.
244 (declaim (ftype (function (list args-type) (values)) parse-args-types))
245 (defun parse-args-types (lambda-list result)
246   (multiple-value-bind (required optional restp rest keyp keys allowp aux)
247       (parse-lambda-list lambda-list)
248     (when aux
249       (error "&AUX in a FUNCTION or VALUES type: ~S." lambda-list))
250     (setf (args-type-required result) (mapcar #'specifier-type required))
251     (setf (args-type-optional result) (mapcar #'specifier-type optional))
252     (setf (args-type-rest result) (if restp (specifier-type rest) nil))
253     (setf (args-type-keyp result) keyp)
254     (collect ((key-info))
255       (dolist (key keys)
256         (unless (proper-list-of-length-p key 2)
257           (error "Keyword type description is not a two-list: ~S." key))
258         (let ((kwd (first key)))
259           (when (find kwd (key-info) :key #'key-info-name)
260             (error "~@<repeated keyword ~S in lambda list: ~2I~_~S~:>"
261                    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))
318 ; (inline single-value-type))
319 (defun single-value-type (type)
320   (declare (type ctype type))
321   (cond ((values-type-p type)
322          (or (car (args-type-required type))
323              (if (args-type-optional type)
324                  (type-union (car (args-type-optional type))
325                              (specifier-type 'null)))
326              (args-type-rest type)
327              (specifier-type 'null)))
328         ((eq type *wild-type*)
329          *universal-type*)
330         (t
331          type)))
332
333 ;;; Return the minmum number of arguments that a function can be
334 ;;; called with, and the maximum number or NIL. If not a function
335 ;;; type, return NIL, NIL.
336 (defun function-type-nargs (type)
337   (declare (type ctype type))
338   (if (function-type-p type)
339       (let ((fixed (length (args-type-required type))))
340         (if (or (args-type-rest type)
341                 (args-type-keyp type)
342                 (args-type-allowp type))
343             (values fixed nil)
344             (values fixed (+ fixed (length (args-type-optional type))))))
345       (values nil nil)))
346
347 ;;; Determine whether TYPE corresponds to a definite number of values.
348 ;;; The first value is a list of the types for each value, and the
349 ;;; second value is the number of values. If the number of values is
350 ;;; not fixed, then return NIL and :UNKNOWN.
351 (defun values-types (type)
352   (declare (type ctype type))
353   (cond ((eq type *wild-type*)
354          (values nil :unknown))
355         ((not (values-type-p type))
356          (values (list type) 1))
357         ((or (args-type-optional type)
358              (args-type-rest type)
359              (args-type-keyp type)
360              (args-type-allowp type))
361          (values nil :unknown))
362         (t
363          (let ((req (args-type-required type)))
364            (values (mapcar #'single-value-type req) (length req))))))
365
366 ;;; Return two values:
367 ;;; 1. A list of all the positional (fixed and optional) types.
368 ;;; 2. The &REST type (if any). If keywords allowed, *UNIVERSAL-TYPE*.
369 ;;;    If no keywords or &REST, then the DEFAULT-TYPE.
370 (defun values-type-types (type &optional (default-type *empty-type*))
371   (declare (type values-type type))
372   (values (append (args-type-required type)
373                   (args-type-optional type))
374           (cond ((args-type-keyp type) *universal-type*)
375                 ((args-type-rest type))
376                 (t
377                  default-type))))
378
379 ;;; Return a list of OPERATION applied to the types in TYPES1 and
380 ;;; TYPES2, padding with REST2 as needed. TYPES1 must not be shorter
381 ;;; than TYPES2. The second value is T if OPERATION always returned a
382 ;;; true second value.
383 (defun fixed-values-op (types1 types2 rest2 operation)
384   (declare (list types1 types2) (type ctype rest2) (type function operation))
385   (let ((exact t))
386     (values (mapcar #'(lambda (t1 t2)
387                         (multiple-value-bind (res win)
388                             (funcall operation t1 t2)
389                           (unless win
390                             (setq exact nil))
391                           res))
392                     types1
393                     (append types2
394                             (make-list (- (length types1) (length types2))
395                                        :initial-element rest2)))
396             exact)))
397
398 ;;; If Type isn't a values type, then make it into one:
399 ;;;    <type>  ==>  (values type &rest t)
400 (defun coerce-to-values (type)
401   (declare (type ctype type))
402   (if (values-type-p type)
403       type
404       (make-values-type :required (list type) :rest *universal-type*)))
405
406 ;;; Do the specified OPERATION on TYPE1 and TYPE2, which may be any
407 ;;; type, including VALUES types. With VALUES types such as:
408 ;;;    (VALUES a0 a1)
409 ;;;    (VALUES b0 b1)
410 ;;; we compute the more useful result
411 ;;;    (VALUES (<operation> a0 b0) (<operation> a1 b1))
412 ;;; rather than the precise result
413 ;;;    (<operation> (values a0 a1) (values b0 b1))
414 ;;; This has the virtue of always keeping the VALUES type specifier
415 ;;; outermost, and retains all of the information that is really
416 ;;; useful for static type analysis. We want to know what is always
417 ;;; true of each value independently. It is worthless to know that IF
418 ;;; the first value is B0 then the second will be B1.
419 ;;;
420 ;;; If the VALUES count signatures differ, then we produce a result with
421 ;;; the required VALUE count chosen by NREQ when applied to the number
422 ;;; of required values in TYPE1 and TYPE2. Any &KEY values become
423 ;;; &REST T (anyone who uses keyword values deserves to lose.)
424 ;;;
425 ;;; The second value is true if the result is definitely empty or if
426 ;;; OPERATION returned true as its second value each time we called
427 ;;; it. Since we approximate the intersection of VALUES types, the
428 ;;; second value being true doesn't mean the result is exact.
429 (defun args-type-op (type1 type2 operation nreq default-type)
430   (declare (type ctype type1 type2 default-type)
431            (type function operation nreq))
432   (if (or (values-type-p type1) (values-type-p type2))
433       (let ((type1 (coerce-to-values type1))
434             (type2 (coerce-to-values type2)))
435         (multiple-value-bind (types1 rest1)
436             (values-type-types type1 default-type)
437           (multiple-value-bind (types2 rest2)
438               (values-type-types type2 default-type)
439             (multiple-value-bind (rest rest-exact)
440                 (funcall operation rest1 rest2)
441               (multiple-value-bind (res res-exact)
442                   (if (< (length types1) (length types2))
443                       (fixed-values-op types2 types1 rest1 operation)
444                       (fixed-values-op types1 types2 rest2 operation))
445                 (let* ((req (funcall nreq
446                                      (length (args-type-required type1))
447                                      (length (args-type-required type2))))
448                        (required (subseq res 0 req))
449                        (opt (subseq res req))
450                        (opt-last (position rest opt :test-not #'type=
451                                            :from-end t)))
452                   (if (find *empty-type* required :test #'type=)
453                       (values *empty-type* t)
454                       (values (make-values-type
455                                :required required
456                                :optional (if opt-last
457                                              (subseq opt 0 (1+ opt-last))
458                                              ())
459                                :rest (if (eq rest default-type) nil rest))
460                               (and rest-exact res-exact)))))))))
461       (funcall operation type1 type2)))
462
463 ;;; Do a union or intersection operation on types that might be values
464 ;;; types. The result is optimized for utility rather than exactness,
465 ;;; but it is guaranteed that it will be no smaller (more restrictive)
466 ;;; than the precise result.
467 ;;;
468 ;;; The return convention seems to be analogous to
469 ;;; TYPES-INTERSECT. -- WHN 19990910.
470 (defun-cached (values-type-union :hash-function type-cache-hash
471                                  :hash-bits 8
472                                  :default nil
473                                  :init-wrapper !cold-init-forms)
474               ((type1 eq) (type2 eq))
475   (declare (type ctype type1 type2))
476   (cond ((or (eq type1 *wild-type*) (eq type2 *wild-type*)) *wild-type*)
477         ((eq type1 *empty-type*) type2)
478         ((eq type2 *empty-type*) type1)
479         (t
480          (values (args-type-op type1 type2 #'type-union #'min *empty-type*)))))
481 (defun-cached (values-type-intersection :hash-function type-cache-hash
482                                         :hash-bits 8
483                                         :values 2
484                                         :default (values nil :empty)
485                                         :init-wrapper !cold-init-forms)
486               ((type1 eq) (type2 eq))
487   (declare (type ctype type1 type2))
488   (cond ((eq type1 *wild-type*) (values type2 t))
489         ((eq type2 *wild-type*) (values type1 t))
490         (t
491          (args-type-op type1 type2
492                        #'type-intersection
493                        #'max
494                        (specifier-type 'null)))))
495
496 ;;; This is like TYPES-INTERSECT, except that it sort of works on
497 ;;; VALUES types. Note that due to the semantics of
498 ;;; VALUES-TYPE-INTERSECTION, this might return (VALUES T T) when
499 ;;; there isn't really any intersection (?).
500 ;;;
501 ;;; The return convention seems to be analogous to
502 ;;; TYPES-INTERSECT. -- WHN 19990910.
503 (defun values-types-intersect (type1 type2)
504   (cond ((or (eq type1 *empty-type*) (eq type2 *empty-type*))
505          (values 't t))
506         ((or (values-type-p type1) (values-type-p type2))
507          (multiple-value-bind (res win) (values-type-intersection type1 type2)
508            (values (not (eq res *empty-type*))
509                    win)))
510         (t
511          (types-intersect type1 type2))))
512
513 ;;; a SUBTYPEP-like operation that can be used on any types, including
514 ;;; VALUES types
515 (defun-cached (values-subtypep :hash-function type-cache-hash
516                                :hash-bits 8
517                                :values 2
518                                :default (values nil :empty)
519                                :init-wrapper !cold-init-forms)
520               ((type1 eq) (type2 eq))
521   (declare (type ctype type1 type2))
522   (cond ((eq type2 *wild-type*) (values t t))
523         ((eq type1 *wild-type*)
524          (values (eq type2 *universal-type*) t))
525         ((not (values-types-intersect type1 type2))
526          (values nil t))
527         (t
528          (if (or (values-type-p type1) (values-type-p type2))
529              (let ((type1 (coerce-to-values type1))
530                    (type2 (coerce-to-values type2)))
531                (multiple-value-bind (types1 rest1) (values-type-types type1)
532                  (multiple-value-bind (types2 rest2) (values-type-types type2)
533                    (cond ((< (length (values-type-required type1))
534                              (length (values-type-required type2)))
535                           (values nil t))
536                          ((< (length types1) (length types2))
537                           (values nil nil))
538                          ((or (values-type-keyp type1)
539                               (values-type-keyp type2))
540                           (values nil nil))
541                          (t
542                           (do ((t1 types1 (rest t1))
543                                (t2 types2 (rest t2)))
544                               ((null t2)
545                                (csubtypep rest1 rest2))
546                             (multiple-value-bind (res win-p)
547                                 (csubtypep (first t1) (first t2))
548                               (unless win-p
549                                 (return (values nil nil)))
550                               (unless res
551                                 (return (values nil t))))))))))
552              (csubtypep type1 type2)))))
553 \f
554 ;;;; type method interfaces
555
556 ;;; like SUBTYPEP, only works on CTYPE structures
557 (defun-cached (csubtypep :hash-function type-cache-hash
558                          :hash-bits 8
559                          :values 2
560                          :default (values nil :empty)
561                          :init-wrapper !cold-init-forms)
562               ((type1 eq) (type2 eq))
563   (declare (type ctype type1 type2))
564   (cond ((or (eq type1 type2)
565              (eq type1 *empty-type*)
566              (eq type2 *wild-type*))
567          (values t t))
568         ((or (eq type1 *wild-type*)
569              (eq type2 *empty-type*))
570          (values nil t))
571         (t
572          (!invoke-type-method :simple-subtypep :complex-subtypep-arg2
573                               type1 type2
574                               :complex-arg1 :complex-subtypep-arg1))))
575
576 ;;; Just parse the type specifiers and call CSUBTYPE.
577 (defun sb!xc:subtypep (type1 type2)
578   #!+sb-doc
579   "Return two values indicating the relationship between type1 and type2.
580   If values are T and T, type1 definitely is a subtype of type2.
581   If values are NIL and T, type1 definitely is not a subtype of type2.
582   If values are NIL and NIL, it couldn't be determined."
583   (csubtypep (specifier-type type1) (specifier-type type2)))
584
585 ;;; If two types are definitely equivalent, return true. The second
586 ;;; value indicates whether the first value is definitely correct.
587 ;;; This should only fail in the presence of HAIRY types.
588 (defun-cached (type= :hash-function type-cache-hash
589                      :hash-bits 8
590                      :values 2
591                      :default (values nil :empty)
592                      :init-wrapper !cold-init-forms)
593               ((type1 eq) (type2 eq))
594   (declare (type ctype type1 type2))
595   (if (eq type1 type2)
596       (values t t)
597       (!invoke-type-method :simple-= :complex-= type1 type2)))
598
599 ;;; Not exactly the negation of TYPE=, since when the relationship is
600 ;;; uncertain, we still return NIL, NIL. This is useful in cases where
601 ;;; the conservative assumption is =.
602 (defun type/= (type1 type2)
603   (declare (type ctype type1 type2))
604   (multiple-value-bind (res win) (type= type1 type2)
605     (if win
606         (values (not res) t)
607         (values nil nil))))
608
609 ;;; Find a type which includes both types. Any inexactness is
610 ;;; represented by the fuzzy element types; we return a single value
611 ;;; that is precise to the best of our knowledge. This result is
612 ;;; simplified into the canonical form, thus is not a UNION type
613 ;;; unless there is no other way to represent the result.
614 (defun-cached (type-union :hash-function type-cache-hash
615                           :hash-bits 8
616                           :init-wrapper !cold-init-forms)
617               ((type1 eq) (type2 eq))
618   (declare (type ctype type1 type2))
619   (if (eq type1 type2)
620       type1
621       (let ((res (!invoke-type-method :simple-union :complex-union
622                                       type1 type2
623                                       :default :vanilla)))
624         (cond ((eq res :vanilla)
625                (or (vanilla-union type1 type2)
626                    (make-union-type-or-something (list type1 type2))))
627               (res)
628               (t
629                (make-union-type-or-something (list type1 type2)))))))
630
631 ;;; the type method dispatch case of TYPE-INTERSECTION2
632 (defun %type-intersection2 (type1 type2)
633   ;; We want to give both argument orders a chance at
634   ;; COMPLEX-INTERSECTION2. Without that, the old CMU CL type
635   ;; methods could give noncommutative results, e.g.
636   ;;   (TYPE-INTERSECTION2 *EMPTY-TYPE* SOME-HAIRY-TYPE)
637   ;;     => NIL, NIL
638   ;;   (TYPE-INTERSECTION2 SOME-HAIRY-TYPE *EMPTY-TYPE*)
639   ;;     => #<NAMED-TYPE NIL>, T
640   ;; We also need to distinguish between the case where we found a
641   ;; type method, and it returned NIL, and the case where we fell
642   ;; through without finding any type method. An example of the first
643   ;; case is the intersection of a HAIRY-TYPE with some ordinary type.
644   ;; An example of the second case is the intersection of two
645   ;; completely-unrelated types, e.g. CONS and NUMBER, or SYMBOL and
646   ;; ARRAY.
647   ;;
648   ;; (Why yes, CLOS probably *would* be nicer..)
649   (flet ((1way (x y)
650            (!invoke-type-method :simple-intersection2 :complex-intersection2
651                                 x y
652                                 :default :no-type-method-found)))
653     (declare (inline 1way))
654     (let ((xy (1way type1 type2)))
655       (or (and (not (eql xy :no-type-method-found)) xy)
656           (let ((yx (1way type2 type1)))
657             (or (and (not (eql yx :no-type-method-found)) yx)
658                 (cond ((and (eql xy :no-type-method-found)
659                             (eql yx :no-type-method-found))
660                        *empty-type*)
661                       (t
662                        (assert (and (not xy) (not yx))) ; else handled above
663                        nil))))))))
664
665 (defun-cached (type-intersection2 :hash-function type-cache-hash
666                                   :hash-bits 8
667                                   :values 1
668                                   :default nil
669                                   :init-wrapper !cold-init-forms)
670               ((type1 eq) (type2 eq))
671   (declare (type ctype type1 type2))
672   (cond ((eq type1 type2)
673          type1)
674         ((or (intersection-type-p type1)
675              (intersection-type-p type2))
676          ;; Intersections of INTERSECTION-TYPE should have the
677          ;; INTERSECTION-TYPE-TYPES objects broken out and intersected
678          ;; separately. The full TYPE-INTERSECTION function knows how
679          ;; to do that, so let it handle it.
680          (type-intersection type1 type2))
681         (t
682          ;; the ordinary case: we dispatch to type methods
683          (%type-intersection2 type1 type2))))
684
685 ;;; Return as restrictive and simple a type as we can discover that is
686 ;;; no more restrictive than the intersection of TYPE1 and TYPE2. At
687 ;;; worst, we arbitrarily return one of the arguments as the first
688 ;;; value (trying not to return a hairy type).
689 (defun type-approx-intersection2 (type1 type2)
690   (cond ((type-intersection2 type1 type2))
691         ((hairy-type-p type1) type2)
692         (t type1)))
693
694 ;;; The first value is true unless the types don't intersect. The
695 ;;; second value is true if the first value is definitely correct. NIL
696 ;;; is considered to intersect with any type. If T is a subtype of
697 ;;; either type, then we also return T, T. This way we recognize
698 ;;; that hairy types might intersect with T.
699 ;;;
700 ;;; FIXME: It would be more accurate to call this TYPES-MIGHT-INTERSECT,
701 ;;; and rename VALUES-TYPES-INTERSECT the same way.
702 (defun types-intersect (type1 type2)
703   (declare (type ctype type1 type2))
704   (if (or (eq type1 *empty-type*) (eq type2 *empty-type*))
705       (values t t)
706       (let ((intersection2 (type-intersection2 type1 type2)))
707         (cond ((not intersection2)
708                (if (or (csubtypep *universal-type* type1)
709                        (csubtypep *universal-type* type2))
710                    (values t t)
711                    (values t nil)))
712               ((eq intersection2 *empty-type*) (values nil t))
713               (t (values t t))))))
714
715 ;;; Return a Common Lisp type specifier corresponding to the TYPE
716 ;;; object.
717 (defun type-specifier (type)
718   (declare (type ctype type))
719   (funcall (type-class-unparse (type-class-info type)) type))
720
721 ;;; (VALUES-SPECIFIER-TYPE and SPECIFIER-TYPE moved from here to
722 ;;; early-type.lisp by WHN ca. 19990201.)
723
724 ;;; Take a list of type specifiers, computing the translation of each
725 ;;; specifier and defining it as a builtin type.
726 (declaim (ftype (function (list) (values)) precompute-types))
727 (defun precompute-types (specs)
728   (dolist (spec specs)
729     (let ((res (specifier-type spec)))
730       (unless (unknown-type-p res)
731         (setf (info :type :builtin spec) res)
732         (setf (info :type :kind spec) :primitive))))
733   (values))
734 \f
735 ;;;; general TYPE-UNION and TYPE-INTERSECTION operations
736 ;;;;
737 ;;;; These are fully general operations on CTYPEs: they'll always
738 ;;;; return a CTYPE representing the result.
739
740 ;;; shared logic for unions and intersections: Stuff TYPE into the
741 ;;; vector TYPES, finding pairs of types which can be simplified by
742 ;;; SIMPLIFY2 and replacing them by their simplified forms.
743 (defun accumulate-compound-type (type types simplify2)
744   (declare (type ctype type))
745   (declare (type (vector t) types))
746   (declare (type function simplify2))
747   (dotimes (i (length types) (vector-push-extend type types))
748     (let ((simplified2 (funcall simplify2 type (aref types i))))
749       (when simplified2
750         ;; Discard the old (AREF TYPES I).
751         (setf (aref types i) (vector-pop types))
752         ;; Add the new SIMPLIFIED2 to TYPES, by tail recursing.
753         (return (accumulate-compound-type simplified2
754                                           types
755                                           simplify2)))))
756   (values))
757
758 ;;; shared logic for unions and intersections: Make a COMPOUND-TYPE
759 ;;; object whose components are the types in TYPES, or skip to
760 ;;; special cases when TYPES-VECTOR is short.
761 (defun make-compound-type-or-something (constructor types enumerable identity)
762   (declare (type function constructor))
763   (declare (type (vector t) types))
764   (declare (type ctype identity))
765   (case (length types)
766     (0 identity)
767     (1 (the ctype (aref types 0)))
768     (t (funcall constructor enumerable (coerce types 'list)))))
769
770 (defun type-intersection (&rest input-types)
771   (let (;; components of our result, accumulated as a vector
772         (simplified-types (make-array (length input-types) :fill-pointer 0)))
773     (flet ((accumulate (type)
774              (accumulate-compound-type type
775                                        simplified-types
776                                        #'type-intersection2)))
777       (declare (inline accumulate))
778       (dolist (type input-types)
779         (if (intersection-type-p type)
780             (map nil #'accumulate (intersection-type-types type))
781             (accumulate type)))
782       ;; We want to have a canonical representation of types (or failing
783       ;; that, punt to HAIRY-TYPE). Canonical representation would have
784       ;; intersections inside unions but not vice versa, since you can
785       ;; always achieve that by the distributive rule. But we don't want
786       ;; to just apply the distributive rule, since it would be too easy
787       ;; to end up with unreasonably huge type expressions. So instead
788       ;; we punt to HAIRY-TYPE when this comes up.
789       (if (and (> (length simplified-types) 1)
790                (some #'union-type-p simplified-types))
791           (make-hairy-type
792            :specifier `(and ,@(map 'list #'type-specifier simplified-types)))
793           (make-compound-type-or-something #'%make-intersection-type
794                                            simplified-types
795                                            (some #'type-enumerable
796                                                  simplified-types)
797                                            *universal-type*)))))
798
799 ;;; FIXME: Define TYPE-UNION similar to TYPE-INTERSECTION.
800 \f
801 ;;;; built-in types
802
803 (!define-type-class named)
804
805 (defvar *wild-type*)
806 (defvar *empty-type*)
807 (defvar *universal-type*)
808
809 (!cold-init-forms
810  (macrolet ((frob (name var)
811               `(progn
812                  (setq ,var (make-named-type :name ',name))
813                  (setf (info :type :kind ',name) :primitive)
814                  (setf (info :type :builtin ',name) ,var))))
815    ;; KLUDGE: In ANSI, * isn't really the name of a type, it's just a
816    ;; special symbol which can be stuck in some places where an
817    ;; ordinary type can go, e.g. (ARRAY * 1) instead of (ARRAY T 1).
818    ;; At some point, in order to become more standard, we should
819    ;; convert all the classic CMU CL legacy *s and *WILD-TYPE*s into
820    ;; Ts and *UNIVERSAL-TYPE*s.
821    (frob * *wild-type*)
822    (frob nil *empty-type*)
823    (frob t *universal-type*)))
824
825 (!define-type-method (named :simple-=) (type1 type2)
826   ;; FIXME: BUG 85: This assertion failed when I added it in
827   ;; sbcl-0.6.11.13. It probably shouldn't fail; but for now it's
828   ;; just commented out.
829   ;;(assert (not (eq type1 *wild-type*))) ; * isn't really a type.
830   (values (eq type1 type2) t))
831
832 (!define-type-method (named :simple-subtypep) (type1 type2)
833   (assert (not (eq type1 *wild-type*))) ; * isn't really a type.
834   (values (or (eq type1 *empty-type*) (eq type2 *wild-type*)) t))
835
836 (!define-type-method (named :complex-subtypep-arg1) (type1 type2)
837   (assert (not (eq type1 *wild-type*))) ; * isn't really a type.
838   ;; FIXME: Why does this (old CMU CL) assertion hold? Perhaps 'cause
839   ;; the HAIRY-TYPE COMPLEX-SUBTYPEP-ARG2 method takes precedence over
840   ;; this COMPLEX-SUBTYPE-ARG1 method? (I miss CLOS..)
841   (assert (not (hairy-type-p type2))) 
842   ;; Besides the old CMU CL assertion above, we also need to avoid
843   ;; compound types, else we could get into trouble with
844   ;;   (SUBTYPEP 'T '(OR (SATISFIES FOO) (SATISFIES BAR)))
845   ;; or
846   ;;   (SUBTYPEP 'T '(AND (SATISFIES FOO) (SATISFIES BAR))).
847   (assert (not (compound-type-p type2))) 
848   ;; Then, since TYPE2 is reasonably tractable, we're good to go.
849   (values (eq type1 *empty-type*) t))
850
851 (!define-type-method (named :complex-subtypep-arg2) (type1 type2)
852   (assert (not (eq type2 *wild-type*))) ; * isn't really a type.
853   (cond ((eq type2 *universal-type*)
854          (values t t))
855         ((hairy-type-p type1)
856          (values nil nil))
857         (t
858          ;; FIXME: This seems to rely on there only being 2 or 3
859          ;; HAIRY-TYPE values, and the exclusion of various
860          ;; possibilities above. It would be good to explain it and/or
861          ;; rewrite it so that it's clearer.
862          (values (not (eq type2 *empty-type*)) t))))
863
864 (!define-type-method (named :complex-intersection2) (type1 type2)
865   ;; FIXME: This assertion failed when I added it in sbcl-0.6.11.13.
866   ;; Perhaps when bug 85 is fixed it can be reenabled.
867   ;;(assert (not (eq type2 *wild-type*))) ; * isn't really a type.
868   (hierarchical-intersection2 type1 type2))
869
870 (!define-type-method (named :unparse) (x)
871   (named-type-name x))
872 \f
873 ;;;; hairy and unknown types
874
875 (!define-type-method (hairy :unparse) (x) (hairy-type-specifier x))
876
877 (!define-type-method (hairy :simple-subtypep) (type1 type2)
878   (let ((hairy-spec1 (hairy-type-specifier type1))
879         (hairy-spec2 (hairy-type-specifier type2)))
880     (cond ((and (consp hairy-spec1) (eq (car hairy-spec1) 'not)
881                 (consp hairy-spec2) (eq (car hairy-spec2) 'not))
882            (csubtypep (specifier-type (cadr hairy-spec2))
883                       (specifier-type (cadr hairy-spec1))))
884           ((equal hairy-spec1 hairy-spec2)
885            (values t t))
886           (t
887            (values nil nil)))))
888
889 (!define-type-method (hairy :complex-subtypep-arg2) (type1 type2)
890   (let ((hairy-spec (hairy-type-specifier type2)))
891     (cond ((and (consp hairy-spec) (eq (car hairy-spec) 'not))
892            (let* ((complement-type2 (specifier-type (cadr hairy-spec)))
893                   (intersection2 (type-intersection2 type1
894                                                      complement-type2)))
895              (if intersection2
896                  (values (eq intersection2 *empty-type*) t)
897                  (values nil nil))))
898           (t
899            (values nil nil)))))
900
901 (!define-type-method (hairy :complex-subtypep-arg1 :complex-=) (type1 type2)
902   (declare (ignore type1 type2))
903   (values nil nil))
904
905 (!define-type-method (hairy :simple-intersection2 :complex-intersection2)
906                      (type1 type2)
907   (declare (ignore type1 type2))
908   nil)
909
910 (!define-type-method (hairy :complex-union) (type1 type2)
911   (make-union-type-or-something (list type1 type2)))
912
913 (!define-type-method (hairy :simple-=) (type1 type2)
914   (if (equal (hairy-type-specifier type1)
915              (hairy-type-specifier type2))
916       (values t t)
917       (values nil nil)))
918
919 (!def-type-translator not (&whole whole type)
920   (declare (ignore type))
921   ;; Check legality of arguments.
922   (destructuring-bind (not typespec) whole
923     (declare (ignore not))
924     (specifier-type typespec)) ; must be legal typespec
925   ;; Create object.
926   (make-hairy-type :specifier whole))
927
928 (!def-type-translator satisfies (&whole whole fun)
929   (declare (ignore fun))
930   ;; Check legality of arguments of arguments.
931   (destructuring-bind (satisfies predicate-name) whole
932     (declare (ignore satisfies))
933     (unless (symbolp predicate-name)
934       (error 'simple-type-error
935              :datum predicate-name
936              :expected-type symbol
937              :format-control "~S is not a symbol."
938              :format-arguments (list predicate-name))))
939   (make-hairy-type :specifier whole))
940 \f
941 ;;;; numeric types
942
943 #!+negative-zero-is-not-zero
944 (defun make-numeric-type (&key class format (complexp :real) low high
945                                enumerable)
946   (flet ((canonicalise-low-bound (x)
947            ;; Canonicalise a low bound of (-0.0) to 0.0.
948            (if (and (consp x) (floatp (car x)) (zerop (car x))
949                     (minusp (float-sign (car x))))
950                (float 0.0 (car x))
951                x))
952          (canonicalise-high-bound (x)
953            ;; Canonicalise a high bound of (+0.0) to -0.0.
954            (if (and (consp x) (floatp (car x)) (zerop (car x))
955                     (plusp (float-sign (car x))))
956                (float -0.0 (car x))
957                x)))
958     (%make-numeric-type :class class
959                         :format format
960                         :complexp complexp
961                         :low (canonicalise-low-bound low)
962                         :high (canonicalise-high-bound high)
963                         :enumerable enumerable)))
964
965 (!define-type-class number)
966
967 (!define-type-method (number :simple-=) (type1 type2)
968   (values
969    (and (eq (numeric-type-class type1) (numeric-type-class type2))
970         (eq (numeric-type-format type1) (numeric-type-format type2))
971         (eq (numeric-type-complexp type1) (numeric-type-complexp type2))
972         (equal (numeric-type-low type1) (numeric-type-low type2))
973         (equal (numeric-type-high type1) (numeric-type-high type2)))
974    t))
975
976 (!define-type-method (number :unparse) (type)
977   (let* ((complexp (numeric-type-complexp type))
978          (low (numeric-type-low type))
979          (high (numeric-type-high type))
980          (base (case (numeric-type-class type)
981                  (integer 'integer)
982                  (rational 'rational)
983                  (float (or (numeric-type-format type) 'float))
984                  (t 'real))))
985     (let ((base+bounds
986            (cond ((and (eq base 'integer) high low)
987                   (let ((high-count (logcount high))
988                         (high-length (integer-length high)))
989                     (cond ((= low 0)
990                            (cond ((= high 0) '(integer 0 0))
991                                  ((= high 1) 'bit)
992                                  ((and (= high-count high-length)
993                                        (plusp high-length))
994                                   `(unsigned-byte ,high-length))
995                                  (t
996                                   `(mod ,(1+ high)))))
997                           ((and (= low sb!vm:*target-most-negative-fixnum*)
998                                 (= high sb!vm:*target-most-positive-fixnum*))
999                            'fixnum)
1000                           ((and (= low (lognot high))
1001                                 (= high-count high-length)
1002                                 (> high-count 0))
1003                            `(signed-byte ,(1+ high-length)))
1004                           (t
1005                            `(integer ,low ,high)))))
1006                  (high `(,base ,(or low '*) ,high))
1007                  (low
1008                   (if (and (eq base 'integer) (= low 0))
1009                       'unsigned-byte
1010                       `(,base ,low)))
1011                  (t base))))
1012       (ecase complexp
1013         (:real
1014          base+bounds)
1015         (:complex
1016          (if (eq base+bounds 'real)
1017              'complex
1018              `(complex ,base+bounds)))
1019         ((nil)
1020          (assert (eq base+bounds 'real))
1021          'number)))))
1022
1023 ;;; Return true if X is "less than or equal" to Y, taking open bounds
1024 ;;; into consideration. CLOSED is the predicate used to test the bound
1025 ;;; on a closed interval (e.g. <=), and OPEN is the predicate used on
1026 ;;; open bounds (e.g. <). Y is considered to be the outside bound, in
1027 ;;; the sense that if it is infinite (NIL), then the test succeeds,
1028 ;;; whereas if X is infinite, then the test fails (unless Y is also
1029 ;;; infinite).
1030 ;;;
1031 ;;; This is for comparing bounds of the same kind, e.g. upper and
1032 ;;; upper. Use NUMERIC-BOUND-TEST* for different kinds of bounds.
1033 #!-negative-zero-is-not-zero
1034 (defmacro numeric-bound-test (x y closed open)
1035   `(cond ((not ,y) t)
1036          ((not ,x) nil)
1037          ((consp ,x)
1038           (if (consp ,y)
1039               (,closed (car ,x) (car ,y))
1040               (,closed (car ,x) ,y)))
1041          (t
1042           (if (consp ,y)
1043               (,open ,x (car ,y))
1044               (,closed ,x ,y)))))
1045
1046 #!+negative-zero-is-not-zero
1047 (defmacro numeric-bound-test-zero (op x y)
1048   `(if (and (zerop ,x) (zerop ,y) (floatp ,x) (floatp ,y))
1049        (,op (float-sign ,x) (float-sign ,y))
1050        (,op ,x ,y)))
1051
1052 #!+negative-zero-is-not-zero
1053 (defmacro numeric-bound-test (x y closed open)
1054   `(cond ((not ,y) t)
1055          ((not ,x) nil)
1056          ((consp ,x)
1057           (if (consp ,y)
1058               (numeric-bound-test-zero ,closed (car ,x) (car ,y))
1059               (numeric-bound-test-zero ,closed (car ,x) ,y)))
1060          (t
1061           (if (consp ,y)
1062               (numeric-bound-test-zero ,open ,x (car ,y))
1063               (numeric-bound-test-zero ,closed ,x ,y)))))
1064
1065 ;;; This is used to compare upper and lower bounds. This is different
1066 ;;; from the same-bound case:
1067 ;;; -- Since X = NIL is -infinity, whereas y = NIL is +infinity, we
1068 ;;;    return true if *either* arg is NIL.
1069 ;;; -- an open inner bound is "greater" and also squeezes the interval,
1070 ;;;    causing us to use the OPEN test for those cases as well.
1071 #!-negative-zero-is-not-zero
1072 (defmacro numeric-bound-test* (x y closed open)
1073   `(cond ((not ,y) t)
1074          ((not ,x) t)
1075          ((consp ,x)
1076           (if (consp ,y)
1077               (,open (car ,x) (car ,y))
1078               (,open (car ,x) ,y)))
1079          (t
1080           (if (consp ,y)
1081               (,open ,x (car ,y))
1082               (,closed ,x ,y)))))
1083
1084 #!+negative-zero-is-not-zero
1085 (defmacro numeric-bound-test* (x y closed open)
1086   `(cond ((not ,y) t)
1087          ((not ,x) t)
1088          ((consp ,x)
1089           (if (consp ,y)
1090               (numeric-bound-test-zero ,open (car ,x) (car ,y))
1091               (numeric-bound-test-zero ,open (car ,x) ,y)))
1092          (t
1093           (if (consp ,y)
1094               (numeric-bound-test-zero ,open ,x (car ,y))
1095               (numeric-bound-test-zero ,closed ,x ,y)))))
1096
1097 ;;; Return whichever of the numeric bounds X and Y is "maximal"
1098 ;;; according to the predicates CLOSED (e.g. >=) and OPEN (e.g. >).
1099 ;;; This is only meaningful for maximizing like bounds, i.e. upper and
1100 ;;; upper. If MAX-P is true, then we return NIL if X or Y is NIL,
1101 ;;; otherwise we return the other arg.
1102 (defmacro numeric-bound-max (x y closed open max-p)
1103   (once-only ((n-x x)
1104               (n-y y))
1105     `(cond ((not ,n-x) ,(if max-p nil n-y))
1106            ((not ,n-y) ,(if max-p nil n-x))
1107            ((consp ,n-x)
1108             (if (consp ,n-y)
1109                 (if (,closed (car ,n-x) (car ,n-y)) ,n-x ,n-y)
1110                 (if (,open (car ,n-x) ,n-y) ,n-x ,n-y)))
1111            (t
1112             (if (consp ,n-y)
1113                 (if (,open (car ,n-y) ,n-x) ,n-y ,n-x)
1114                 (if (,closed ,n-y ,n-x) ,n-y ,n-x))))))
1115
1116 (!define-type-method (number :simple-subtypep) (type1 type2)
1117   (let ((class1 (numeric-type-class type1))
1118         (class2 (numeric-type-class type2))
1119         (complexp2 (numeric-type-complexp type2))
1120         (format2 (numeric-type-format type2))
1121         (low1 (numeric-type-low type1))
1122         (high1 (numeric-type-high type1))
1123         (low2 (numeric-type-low type2))
1124         (high2 (numeric-type-high type2)))
1125     ;; If one is complex and the other isn't, they are disjoint.
1126     (cond ((not (or (eq (numeric-type-complexp type1) complexp2)
1127                     (null complexp2)))
1128            (values nil t))
1129           ;; If the classes are specified and different, the types are
1130           ;; disjoint unless type2 is rational and type1 is integer.
1131           ((not (or (eq class1 class2)
1132                     (null class2)
1133                     (and (eq class1 'integer)
1134                          (eq class2 'rational))))
1135            (values nil t))
1136           ;; If the float formats are specified and different, the types
1137           ;; are disjoint.
1138           ((not (or (eq (numeric-type-format type1) format2)
1139                     (null format2)))
1140            (values nil t))
1141           ;; Check the bounds.
1142           ((and (numeric-bound-test low1 low2 >= >)
1143                 (numeric-bound-test high1 high2 <= <))
1144            (values t t))
1145           (t
1146            (values nil t)))))
1147
1148 (!define-superclasses number ((generic-number)) !cold-init-forms)
1149
1150 ;;; If the high bound of LOW is adjacent to the low bound of HIGH,
1151 ;;; then return true, otherwise NIL.
1152 (defun numeric-types-adjacent (low high)
1153   (let ((low-bound (numeric-type-high low))
1154         (high-bound (numeric-type-low high)))
1155     (cond ((not (and low-bound high-bound)) nil)
1156           ((and (consp low-bound) (consp high-bound)) nil)
1157           ((consp low-bound)
1158            #!-negative-zero-is-not-zero
1159            (let ((low-value (car low-bound)))
1160              (or (eql low-value high-bound)
1161                  (and (eql low-value -0f0) (eql high-bound 0f0))
1162                  (and (eql low-value 0f0) (eql high-bound -0f0))
1163                  (and (eql low-value -0d0) (eql high-bound 0d0))
1164                  (and (eql low-value 0d0) (eql high-bound -0d0))))
1165            #!+negative-zero-is-not-zero
1166            (eql (car low-bound) high-bound))
1167           ((consp high-bound)
1168            #!-negative-zero-is-not-zero
1169            (let ((high-value (car high-bound)))
1170              (or (eql high-value low-bound)
1171                  (and (eql high-value -0f0) (eql low-bound 0f0))
1172                  (and (eql high-value 0f0) (eql low-bound -0f0))
1173                  (and (eql high-value -0d0) (eql low-bound 0d0))
1174                  (and (eql high-value 0d0) (eql low-bound -0d0))))
1175            #!+negative-zero-is-not-zero
1176            (eql (car high-bound) low-bound))
1177           #!+negative-zero-is-not-zero
1178           ((or (and (eql low-bound -0f0) (eql high-bound 0f0))
1179                (and (eql low-bound -0d0) (eql high-bound 0d0))))
1180           ((and (eq (numeric-type-class low) 'integer)
1181                 (eq (numeric-type-class high) 'integer))
1182            (eql (1+ low-bound) high-bound))
1183           (t
1184            nil))))
1185
1186 ;;; Return a numeric type that is a supertype for both TYPE1 and TYPE2.
1187 ;;;
1188 ;;; ### Note: we give up early to keep from dropping lots of information on
1189 ;;; the floor by returning overly general types.
1190 (!define-type-method (number :simple-union) (type1 type2)
1191   (declare (type numeric-type type1 type2))
1192   (cond ((csubtypep type1 type2) type2)
1193         ((csubtypep type2 type1) type1)
1194         (t
1195          (let ((class1 (numeric-type-class type1))
1196                (format1 (numeric-type-format type1))
1197                (complexp1 (numeric-type-complexp type1))
1198                (class2 (numeric-type-class type2))
1199                (format2 (numeric-type-format type2))
1200                (complexp2 (numeric-type-complexp type2)))
1201            (when (and (eq class1 class2)
1202                       (eq format1 format2)
1203                       (eq complexp1 complexp2)
1204                       (or (numeric-types-intersect type1 type2)
1205                           (numeric-types-adjacent type1 type2)
1206                           (numeric-types-adjacent type2 type1)))
1207              (make-numeric-type
1208               :class class1
1209               :format format1
1210               :complexp complexp1
1211               :low (numeric-bound-max (numeric-type-low type1)
1212                                       (numeric-type-low type2)
1213                                       <= < t)
1214               :high (numeric-bound-max (numeric-type-high type1)
1215                                        (numeric-type-high type2)
1216                                        >= > t)))))))
1217
1218 (!cold-init-forms
1219   (setf (info :type :kind 'number) :primitive)
1220   (setf (info :type :builtin 'number)
1221         (make-numeric-type :complexp nil)))
1222
1223 (!def-type-translator complex (&optional (spec '*))
1224   (if (eq spec '*)
1225       (make-numeric-type :complexp :complex)
1226       (let ((type (specifier-type spec)))
1227         (unless (numeric-type-p type)
1228           (error "Component type for Complex is not numeric: ~S." spec))
1229         (when (eq (numeric-type-complexp type) :complex)
1230           (error "Component type for Complex is complex: ~S." spec))
1231         (let ((res (copy-numeric-type type)))
1232           (setf (numeric-type-complexp res) :complex)
1233           res))))
1234
1235 ;;; If X is *, return NIL, otherwise return the bound, which must be a
1236 ;;; member of TYPE or a one-element list of a member of TYPE.
1237 #!-sb-fluid (declaim (inline canonicalized-bound))
1238 (defun canonicalized-bound (bound type)
1239   (cond ((eq bound '*) nil)
1240         ((or (sb!xc:typep bound type)
1241              (and (consp bound)
1242                   (sb!xc:typep (car bound) type)
1243                   (null (cdr bound))))
1244           bound)
1245         (t
1246          (error "Bound is not ~S, a ~S or a list of a ~S: ~S"
1247                 '*
1248                 type
1249                 type
1250                 bound))))
1251
1252 (!def-type-translator integer (&optional (low '*) (high '*))
1253   (let* ((l (canonicalized-bound low 'integer))
1254          (lb (if (consp l) (1+ (car l)) l))
1255          (h (canonicalized-bound high 'integer))
1256          (hb (if (consp h) (1- (car h)) h)))
1257     (when (and hb lb (< hb lb))
1258       (error "Lower bound ~S is greater than upper bound ~S." l h))
1259     (make-numeric-type :class 'integer
1260                        :complexp :real
1261                        :enumerable (not (null (and l h)))
1262                        :low lb
1263                        :high hb)))
1264
1265 (defmacro !def-bounded-type (type class format)
1266   `(!def-type-translator ,type (&optional (low '*) (high '*))
1267      (let ((lb (canonicalized-bound low ',type))
1268            (hb (canonicalized-bound high ',type)))
1269        (unless (numeric-bound-test* lb hb <= <)
1270          (error "Lower bound ~S is not less than upper bound ~S." low high))
1271        (make-numeric-type :class ',class :format ',format :low lb :high hb))))
1272
1273 (!def-bounded-type rational rational nil)
1274 (!def-bounded-type float float nil)
1275 (!def-bounded-type real nil nil)
1276
1277 (defmacro !define-float-format (f)
1278   `(!def-bounded-type ,f float ,f))
1279
1280 (!define-float-format short-float)
1281 (!define-float-format single-float)
1282 (!define-float-format double-float)
1283 (!define-float-format long-float)
1284
1285 (defun numeric-types-intersect (type1 type2)
1286   (declare (type numeric-type type1 type2))
1287   (let* ((class1 (numeric-type-class type1))
1288          (class2 (numeric-type-class type2))
1289          (complexp1 (numeric-type-complexp type1))
1290          (complexp2 (numeric-type-complexp type2))
1291          (format1 (numeric-type-format type1))
1292          (format2 (numeric-type-format type2))
1293          (low1 (numeric-type-low type1))
1294          (high1 (numeric-type-high type1))
1295          (low2 (numeric-type-low type2))
1296          (high2 (numeric-type-high type2)))
1297     ;; If one is complex and the other isn't, then they are disjoint.
1298     (cond ((not (or (eq complexp1 complexp2)
1299                     (null complexp1) (null complexp2)))
1300            nil)
1301           ;; If either type is a float, then the other must either be
1302           ;; specified to be a float or unspecified. Otherwise, they
1303           ;; are disjoint.
1304           ((and (eq class1 'float)
1305                 (not (member class2 '(float nil)))) nil)
1306           ((and (eq class2 'float)
1307                 (not (member class1 '(float nil)))) nil)
1308           ;; If the float formats are specified and different, the
1309           ;; types are disjoint.
1310           ((not (or (eq format1 format2) (null format1) (null format2)))
1311            nil)
1312           (t
1313            ;; Check the bounds. This is a bit odd because we must
1314            ;; always have the outer bound of the interval as the
1315            ;; second arg.
1316            (if (numeric-bound-test high1 high2 <= <)
1317                (or (and (numeric-bound-test low1 low2 >= >)
1318                         (numeric-bound-test* low1 high2 <= <))
1319                    (and (numeric-bound-test low2 low1 >= >)
1320                         (numeric-bound-test* low2 high1 <= <)))
1321                (or (and (numeric-bound-test* low2 high1 <= <)
1322                         (numeric-bound-test low2 low1 >= >))
1323                    (and (numeric-bound-test high2 high1 <= <)
1324                         (numeric-bound-test* high2 low1 >= >))))))))
1325
1326 ;;; Take the numeric bound X and convert it into something that can be
1327 ;;; used as a bound in a numeric type with the specified CLASS and
1328 ;;; FORMAT. If UP-P is true, then we round up as needed, otherwise we
1329 ;;; round down. UP-P true implies that X is a lower bound, i.e. (N) > N.
1330 ;;;
1331 ;;; This is used by NUMERIC-TYPE-INTERSECTION to mash the bound into
1332 ;;; the appropriate type number. X may only be a float when CLASS is
1333 ;;; FLOAT.
1334 ;;;
1335 ;;; ### Note: it is possible for the coercion to a float to overflow
1336 ;;; or underflow. This happens when the bound doesn't fit in the
1337 ;;; specified format. In this case, we should really return the
1338 ;;; appropriate {Most | Least}-{Positive | Negative}-XXX-Float float
1339 ;;; of desired format. But these conditions aren't currently signalled
1340 ;;; in any useful way.
1341 ;;;
1342 ;;; Also, when converting an open rational bound into a float we
1343 ;;; should probably convert it to a closed bound of the closest float
1344 ;;; in the specified format. KLUDGE: In general, open float bounds are
1345 ;;; screwed up. -- (comment from original CMU CL)
1346 (defun round-numeric-bound (x class format up-p)
1347   (if x
1348       (let ((cx (if (consp x) (car x) x)))
1349         (ecase class
1350           ((nil rational) x)
1351           (integer
1352            (if (and (consp x) (integerp cx))
1353                (if up-p (1+ cx) (1- cx))
1354                (if up-p (ceiling cx) (floor cx))))
1355           (float
1356            (let ((res (if format (coerce cx format) (float cx))))
1357              (if (consp x) (list res) res)))))
1358       nil))
1359
1360 ;;; Handle the case of type intersection on two numeric types. We use
1361 ;;; TYPES-INTERSECT to throw out the case of types with no
1362 ;;; intersection. If an attribute in TYPE1 is unspecified, then we use
1363 ;;; TYPE2's attribute, which must be at least as restrictive. If the
1364 ;;; types intersect, then the only attributes that can be specified
1365 ;;; and different are the class and the bounds.
1366 ;;;
1367 ;;; When the class differs, we use the more restrictive class. The
1368 ;;; only interesting case is RATIONAL/INTEGER, since RATIONAL includes
1369 ;;; INTEGER.
1370 ;;;
1371 ;;; We make the result lower (upper) bound the maximum (minimum) of
1372 ;;; the argument lower (upper) bounds. We convert the bounds into the
1373 ;;; appropriate numeric type before maximizing. This avoids possible
1374 ;;; confusion due to mixed-type comparisons (but I think the result is
1375 ;;; the same).
1376 (!define-type-method (number :simple-intersection2) (type1 type2)
1377   (declare (type numeric-type type1 type2))
1378   (if (numeric-types-intersect type1 type2)
1379       (let* ((class1 (numeric-type-class type1))
1380              (class2 (numeric-type-class type2))
1381              (class (ecase class1
1382                       ((nil) class2)
1383                       ((integer float) class1)
1384                       (rational (if (eq class2 'integer)
1385                                        'integer
1386                                        'rational))))
1387              (format (or (numeric-type-format type1)
1388                          (numeric-type-format type2))))
1389         (make-numeric-type
1390          :class class
1391          :format format
1392          :complexp (or (numeric-type-complexp type1)
1393                        (numeric-type-complexp type2))
1394          :low (numeric-bound-max
1395                (round-numeric-bound (numeric-type-low type1)
1396                                     class format t)
1397                (round-numeric-bound (numeric-type-low type2)
1398                                     class format t)
1399                > >= nil)
1400          :high (numeric-bound-max
1401                 (round-numeric-bound (numeric-type-high type1)
1402                                      class format nil)
1403                 (round-numeric-bound (numeric-type-high type2)
1404                                      class format nil)
1405                 < <= nil)))
1406       *empty-type*))
1407
1408 ;;; Given two float formats, return the one with more precision. If
1409 ;;; either one is null, return NIL.
1410 (defun float-format-max (f1 f2)
1411   (when (and f1 f2)
1412     (dolist (f *float-formats* (error "bad float format: ~S" f1))
1413       (when (or (eq f f1) (eq f f2))
1414         (return f)))))
1415
1416 ;;; Return the result of an operation on TYPE1 and TYPE2 according to
1417 ;;; the rules of numeric contagion. This is always NUMBER, some float
1418 ;;; format (possibly complex) or RATIONAL. Due to rational
1419 ;;; canonicalization, there isn't much we can do here with integers or
1420 ;;; rational complex numbers.
1421 ;;;
1422 ;;; If either argument is not a NUMERIC-TYPE, then return NUMBER. This
1423 ;;; is useful mainly for allowing types that are technically numbers,
1424 ;;; but not a NUMERIC-TYPE.
1425 (defun numeric-contagion (type1 type2)
1426   (if (and (numeric-type-p type1) (numeric-type-p type2))
1427       (let ((class1 (numeric-type-class type1))
1428             (class2 (numeric-type-class type2))
1429             (format1 (numeric-type-format type1))
1430             (format2 (numeric-type-format type2))
1431             (complexp1 (numeric-type-complexp type1))
1432             (complexp2 (numeric-type-complexp type2)))
1433         (cond ((or (null complexp1)
1434                    (null complexp2))
1435                (specifier-type 'number))
1436               ((eq class1 'float)
1437                (make-numeric-type
1438                 :class 'float
1439                 :format (ecase class2
1440                           (float (float-format-max format1 format2))
1441                           ((integer rational) format1)
1442                           ((nil)
1443                            ;; A double-float with any real number is a
1444                            ;; double-float.
1445                            #!-long-float
1446                            (if (eq format1 'double-float)
1447                              'double-float
1448                              nil)
1449                            ;; A long-float with any real number is a
1450                            ;; long-float.
1451                            #!+long-float
1452                            (if (eq format1 'long-float)
1453                              'long-float
1454                              nil)))
1455                 :complexp (if (or (eq complexp1 :complex)
1456                                   (eq complexp2 :complex))
1457                               :complex
1458                               :real)))
1459               ((eq class2 'float) (numeric-contagion type2 type1))
1460               ((and (eq complexp1 :real) (eq complexp2 :real))
1461                (make-numeric-type
1462                 :class (and class1 class2 'rational)
1463                 :complexp :real))
1464               (t
1465                (specifier-type 'number))))
1466       (specifier-type 'number)))
1467 \f
1468 ;;;; array types
1469
1470 (!define-type-class array)
1471
1472 ;;; What this does depends on the setting of the
1473 ;;; *USE-IMPLEMENTATION-TYPES* switch. If true, return the specialized
1474 ;;; element type, otherwise return the original element type.
1475 (defun specialized-element-type-maybe (type)
1476   (declare (type array-type type))
1477   (if *use-implementation-types*
1478       (array-type-specialized-element-type type)
1479       (array-type-element-type type)))
1480
1481 (!define-type-method (array :simple-=) (type1 type2)
1482   (values (and (equal (array-type-dimensions type1)
1483                       (array-type-dimensions type2))
1484                (eq (array-type-complexp type1)
1485                    (array-type-complexp type2))
1486                (type= (specialized-element-type-maybe type1)
1487                       (specialized-element-type-maybe type2)))
1488           t))
1489
1490 (!define-type-method (array :unparse) (type)
1491   (let ((dims (array-type-dimensions type))
1492         (eltype (type-specifier (array-type-element-type type)))
1493         (complexp (array-type-complexp type)))
1494     (cond ((eq dims '*)
1495            (if (eq eltype '*)
1496                (if complexp 'array 'simple-array)
1497                (if complexp `(array ,eltype) `(simple-array ,eltype))))
1498           ((= (length dims) 1)
1499            (if complexp
1500                (if (eq (car dims) '*)
1501                    (case eltype
1502                      (bit 'bit-vector)
1503                      (base-char 'base-string)
1504                      (character 'string)
1505                      (* 'vector)
1506                      (t `(vector ,eltype)))
1507                    (case eltype
1508                      (bit `(bit-vector ,(car dims)))
1509                      (base-char `(base-string ,(car dims)))
1510                      (character `(string ,(car dims)))
1511                      (t `(vector ,eltype ,(car dims)))))
1512                (if (eq (car dims) '*)
1513                    (case eltype
1514                      (bit 'simple-bit-vector)
1515                      (base-char 'simple-base-string)
1516                      (character 'simple-string)
1517                      ((t) 'simple-vector)
1518                      (t `(simple-array ,eltype (*))))
1519                    (case eltype
1520                      (bit `(simple-bit-vector ,(car dims)))
1521                      (base-char `(simple-base-string ,(car dims)))
1522                      (character `(simple-string ,(car dims)))
1523                      ((t) `(simple-vector ,(car dims)))
1524                      (t `(simple-array ,eltype ,dims))))))
1525           (t
1526            (if complexp
1527                `(array ,eltype ,dims)
1528                `(simple-array ,eltype ,dims))))))
1529
1530 (!define-type-method (array :simple-subtypep) (type1 type2)
1531   (let ((dims1 (array-type-dimensions type1))
1532         (dims2 (array-type-dimensions type2))
1533         (complexp2 (array-type-complexp type2)))
1534     (cond (;; not subtypep unless dimensions are compatible
1535            (not (or (eq dims2 '*)
1536                     (and (not (eq dims1 '*))
1537                          ;; (sbcl-0.6.4 has trouble figuring out that
1538                          ;; DIMS1 and DIMS2 must be lists at this
1539                          ;; point, and knowing that is important to
1540                          ;; compiling EVERY efficiently.)
1541                          (= (length (the list dims1))
1542                             (length (the list dims2)))
1543                          (every (lambda (x y)
1544                                   (or (eq y '*) (eql x y)))
1545                                 (the list dims1)
1546                                 (the list dims2)))))
1547            (values nil t))
1548           ;; not subtypep unless complexness is compatible
1549           ((not (or (eq complexp2 :maybe)
1550                     (eq (array-type-complexp type1) complexp2)))
1551            (values nil t))
1552           ;; Since we didn't fail any of the tests above, we win
1553           ;; if the TYPE2 element type is wild.
1554           ((eq (array-type-element-type type2) *wild-type*)
1555            (values t t))
1556           (;; Since we didn't match any of the special cases above, we
1557            ;; can't give a good answer unless both the element types
1558            ;; have been defined.
1559            (or (unknown-type-p (array-type-element-type type1))
1560                (unknown-type-p (array-type-element-type type2)))
1561            (values nil nil))
1562           (;; Otherwise, the subtype relationship holds iff the
1563            ;; types are equal, and they're equal iff the specialized
1564            ;; element types are identical.
1565            t
1566            (values (type= (specialized-element-type-maybe type1)
1567                           (specialized-element-type-maybe type2))
1568                    t)))))
1569
1570 (!define-superclasses array
1571   ((string string)
1572    (vector vector)
1573    (array))
1574   !cold-init-forms)
1575
1576 (defun array-types-intersect (type1 type2)
1577   (declare (type array-type type1 type2))
1578   (let ((dims1 (array-type-dimensions type1))
1579         (dims2 (array-type-dimensions type2))
1580         (complexp1 (array-type-complexp type1))
1581         (complexp2 (array-type-complexp type2)))
1582     ;; See whether dimensions are compatible.
1583     (cond ((not (or (eq dims1 '*) (eq dims2 '*)
1584                     (and (= (length dims1) (length dims2))
1585                          (every #'(lambda (x y)
1586                                     (or (eq x '*) (eq y '*) (= x y)))
1587                                 dims1 dims2))))
1588            (values nil t))
1589           ;; See whether complexpness is compatible.
1590           ((not (or (eq complexp1 :maybe)
1591                     (eq complexp2 :maybe)
1592                     (eq complexp1 complexp2)))
1593            (values nil t))
1594           ;; If either element type is wild, then they intersect.
1595           ;; Otherwise, the types must be identical.
1596           ((or (eq (array-type-element-type type1) *wild-type*)
1597                (eq (array-type-element-type type2) *wild-type*)
1598                (type= (specialized-element-type-maybe type1)
1599                       (specialized-element-type-maybe type2)))
1600
1601            (values t t))
1602           (t
1603            (values nil t)))))
1604
1605 (!define-type-method (array :simple-intersection2) (type1 type2)
1606   (declare (type array-type type1 type2))
1607   (if (array-types-intersect type1 type2)
1608       (let ((dims1 (array-type-dimensions type1))
1609             (dims2 (array-type-dimensions type2))
1610             (complexp1 (array-type-complexp type1))
1611             (complexp2 (array-type-complexp type2))
1612             (eltype1 (array-type-element-type type1))
1613             (eltype2 (array-type-element-type type2)))
1614         (specialize-array-type
1615          (make-array-type
1616           :dimensions (cond ((eq dims1 '*) dims2)
1617                             ((eq dims2 '*) dims1)
1618                             (t
1619                              (mapcar (lambda (x y) (if (eq x '*) y x))
1620                                      dims1 dims2)))
1621           :complexp (if (eq complexp1 :maybe) complexp2 complexp1)
1622           :element-type (if (eq eltype1 *wild-type*) eltype2 eltype1))))
1623       *empty-type*))
1624
1625 ;;; Check a supplied dimension list to determine whether it is legal,
1626 ;;; and return it in canonical form (as either '* or a list).
1627 (defun canonical-array-dimensions (dims)
1628   (typecase dims
1629     ((member *) dims)
1630     (integer
1631      (when (minusp dims)
1632        (error "Arrays can't have a negative number of dimensions: ~S" dims))
1633      (when (>= dims sb!xc:array-rank-limit)
1634        (error "array type with too many dimensions: ~S" dims))
1635      (make-list dims :initial-element '*))
1636     (list
1637      (when (>= (length dims) sb!xc:array-rank-limit)
1638        (error "array type with too many dimensions: ~S" dims))
1639      (dolist (dim dims)
1640        (unless (eq dim '*)
1641          (unless (and (integerp dim)
1642                       (>= dim 0)
1643                       (< dim sb!xc:array-dimension-limit))
1644            (error "bad dimension in array type: ~S" dim))))
1645      dims)
1646     (t
1647      (error "Array dimensions is not a list, integer or *:~%  ~S" dims))))
1648 \f
1649 ;;;; MEMBER types
1650
1651 (!define-type-class member)
1652
1653 (!define-type-method (member :unparse) (type)
1654   (let ((members (member-type-members type)))
1655     (if (equal members '(nil))
1656         'null
1657         `(member ,@members))))
1658
1659 (!define-type-method (member :simple-subtypep) (type1 type2)
1660   (values (subsetp (member-type-members type1) (member-type-members type2))
1661           t))
1662
1663 (!define-type-method (member :complex-subtypep-arg1) (type1 type2)
1664   (every/type (swapped-args-fun #'ctypep)
1665               type2
1666               (member-type-members type1)))
1667
1668 ;;; We punt if the odd type is enumerable and intersects with the
1669 ;;; MEMBER type. If not enumerable, then it is definitely not a
1670 ;;; subtype of the MEMBER type.
1671 (!define-type-method (member :complex-subtypep-arg2) (type1 type2)
1672   (cond ((not (type-enumerable type1)) (values nil t))
1673         ((types-intersect type1 type2) (values nil nil))
1674         (t (values nil t))))
1675
1676 (!define-type-method (member :simple-intersection2) (type1 type2)
1677   (let ((mem1 (member-type-members type1))
1678         (mem2 (member-type-members type2)))
1679     (cond ((subsetp mem1 mem2) type1)
1680           ((subsetp mem2 mem1) type2)
1681           (t
1682            (let ((res (intersection mem1 mem2)))
1683              (if res
1684                  (make-member-type :members res)
1685                  *empty-type*))))))
1686
1687 (!define-type-method (member :complex-intersection2) (type1 type2)
1688   (block punt                
1689     (collect ((members))
1690       (let ((mem2 (member-type-members type2)))
1691         (dolist (member mem2)
1692           (multiple-value-bind (val win) (ctypep member type1)
1693             (unless win
1694               (return-from punt nil))
1695             (when val (members member))))
1696         (cond ((subsetp mem2 (members)) type2)
1697               ((null (members)) *empty-type*)
1698               (t
1699                (make-member-type :members (members))))))))
1700
1701 ;;; We don't need a :COMPLEX-UNION, since the only interesting case is
1702 ;;; a union type, and the member/union interaction is handled by the
1703 ;;; union type method.
1704 (!define-type-method (member :simple-union) (type1 type2)
1705   (let ((mem1 (member-type-members type1))
1706         (mem2 (member-type-members type2)))
1707     (cond ((subsetp mem1 mem2) type2)
1708           ((subsetp mem2 mem1) type1)
1709           (t
1710            (make-member-type :members (union mem1 mem2))))))
1711
1712 (!define-type-method (member :simple-=) (type1 type2)
1713   (let ((mem1 (member-type-members type1))
1714         (mem2 (member-type-members type2)))
1715     (values (and (subsetp mem1 mem2)
1716                  (subsetp mem2 mem1))
1717             t)))
1718
1719 (!define-type-method (member :complex-=) (type1 type2)
1720   (if (type-enumerable type1)
1721       (multiple-value-bind (val win) (csubtypep type2 type1)
1722         (if (or val (not win))
1723             (values nil nil)
1724             (values nil t)))
1725       (values nil t)))
1726
1727 (!def-type-translator member (&rest members)
1728   (if members
1729     (make-member-type :members (remove-duplicates members))
1730     *empty-type*))
1731 \f
1732 ;;;; intersection types
1733 ;;;;
1734 ;;;; Until version 0.6.10.6, SBCL followed the original CMU CL approach
1735 ;;;; of punting on all AND types, not just the unreasonably complicated
1736 ;;;; ones. The change was motivated by trying to get the KEYWORD type
1737 ;;;; to behave sensibly:
1738 ;;;;    ;; reasonable definition
1739 ;;;;    (DEFTYPE KEYWORD () '(AND SYMBOL (SATISFIES KEYWORDP)))
1740 ;;;;    ;; reasonable behavior
1741 ;;;;    (ASSERT (SUBTYPEP 'KEYWORD 'SYMBOL))
1742 ;;;; Without understanding a little about the semantics of AND, we'd
1743 ;;;; get (SUBTYPEP 'KEYWORD 'SYMBOL)=>NIL,NIL and, for entirely
1744 ;;;; parallel reasons, (SUBTYPEP 'RATIO 'NUMBER)=>NIL,NIL. That's
1745 ;;;; not so good..)
1746 ;;;;
1747 ;;;; We still follow the example of CMU CL to some extent, by punting
1748 ;;;; (to the opaque HAIRY-TYPE) on sufficiently complicated types
1749 ;;;; involving AND.
1750
1751 (!define-type-class intersection)
1752
1753 ;;; A few intersection types have special names. The others just get
1754 ;;; mechanically unparsed.
1755 (!define-type-method (intersection :unparse) (type)
1756   (declare (type ctype type))
1757   (or (find type '(ratio bignum keyword) :key #'specifier-type :test #'type=)
1758       `(and ,@(mapcar #'type-specifier (intersection-type-types type)))))
1759
1760 ;;; shared machinery for type equality: true if every type in the set
1761 ;;; TYPES1 matches a type in the set TYPES2 and vice versa
1762 (defun type=-set (types1 types2)
1763   (flet (;; true if every type in the set X matches a type in the set Y
1764          (type<=-set (x y)
1765            (declare (type list x y))
1766            (every (lambda (xelement)
1767                     (position xelement y :test #'type=))
1768                   x)))
1769     (values (and (type<=-set types1 types2)
1770                  (type<=-set types2 types1))
1771             t)))
1772
1773 ;;; Two intersection types are equal if their subtypes are equal sets.
1774 ;;;
1775 ;;; FIXME: Might it be better to use
1776 ;;;   (AND (SUBTYPEP X Y) (SUBTYPEP Y X))
1777 ;;; instead, since SUBTYPEP is the usual relationship that we care
1778 ;;; most about, so it would be good to leverage any ingenuity there
1779 ;;; in this more obscure method?
1780 (!define-type-method (intersection :simple-=) (type1 type2)
1781   (type=-set (intersection-type-types type1)
1782              (intersection-type-types type2)))
1783
1784 (!define-type-method (intersection :simple-subtypep) (type1 type2)
1785   (let ((certain? t))
1786     (dolist (t1 (intersection-type-types type1) (values nil certain?))
1787       (multiple-value-bind (subtypep validp)
1788           (intersection-complex-subtypep-arg2 t1 type2)
1789         (cond ((not validp)
1790                (setf certain? nil))
1791               (subtypep
1792                (return (values t t))))))))
1793
1794 (!define-type-method (intersection :complex-subtypep-arg1) (type1 type2)
1795   (any/type (swapped-args-fun #'csubtypep)
1796             type2
1797             (intersection-type-types type1)))
1798
1799 (defun intersection-complex-subtypep-arg2 (type1 type2)
1800   (every/type #'csubtypep type1 (intersection-type-types type2)))
1801 (!define-type-method (intersection :complex-subtypep-arg2) (type1 type2)
1802   (intersection-complex-subtypep-arg2 type1 type2))
1803
1804 (!def-type-translator and (&whole whole &rest type-specifiers)
1805   (apply #'type-intersection
1806          (mapcar #'specifier-type
1807                  type-specifiers)))
1808 \f
1809 ;;;; union types
1810
1811 ;;; Make a union type from the specifier types, setting ENUMERABLE in
1812 ;;; the result if all are enumerable; or take the easy way out if we
1813 ;;; recognize a special case which can be represented more simply.
1814 (defun make-union-type-or-something (types)
1815   (declare (list types))
1816   (cond ((null types)
1817          *empty-type*)
1818         ((null (cdr types))
1819          (first types))
1820         (t
1821          (%make-union-type (every #'type-enumerable types) types))))
1822
1823 (!define-type-class union)
1824
1825 ;;; The LIST type has a special name. Other union types just get
1826 ;;; mechanically unparsed.
1827 (!define-type-method (union :unparse) (type)
1828   (declare (type ctype type))
1829   (if (type= type (specifier-type 'list))
1830       'list
1831       `(or ,@(mapcar #'type-specifier (union-type-types type)))))
1832
1833 ;;; Two union types are equal if their subtypes are equal sets.
1834 (!define-type-method (union :simple-=) (type1 type2)
1835   (type=-set (union-type-types type1)
1836              (union-type-types type2)))
1837
1838 ;;; Similarly, a union type is a subtype of another if every element
1839 ;;; of TYPE1 is a subtype of some element of TYPE2.
1840 ;;;
1841 ;;; KLUDGE: This definition seems redundant, here in UNION-TYPE and
1842 ;;; similarly in INTERSECTION-TYPE, with the logic in the
1843 ;;; corresponding :COMPLEX-SUBTYPEP-ARG1 and :COMPLEX-SUBTYPEP-ARG2
1844 ;;; methods. Ideally there's probably some way to make the
1845 ;;; :SIMPLE-SUBTYPEP method default to the :COMPLEX-SUBTYPEP-FOO
1846 ;;; methods in such a way that this definition could go away, but I
1847 ;;; don't grok the system well enough to tell whether it's simple to
1848 ;;; arrange this. -- WHN 2000-02-03
1849 (!define-type-method (union :simple-subtypep) (type1 type2)
1850   (dolist (t1 (union-type-types type1) (values t t))
1851     (multiple-value-bind (subtypep validp)
1852         (union-complex-subtypep-arg2 t1 type2)
1853       (cond ((not validp)
1854              (return (values nil nil)))
1855             ((not subtypep)
1856              (return (values nil t)))))))
1857
1858 (defun union-complex-subtypep-arg1 (type1 type2)
1859   (every/type (swapped-args-fun #'csubtypep)
1860               type2
1861               (union-type-types type1)))
1862 (!define-type-method (union :complex-subtypep-arg1) (type1 type2)
1863   (union-complex-subtypep-arg1 type1 type2))
1864
1865 (defun union-complex-subtypep-arg2 (type1 type2)
1866   (any/type #'csubtypep type1 (union-type-types type2)))
1867 (!define-type-method (union :complex-subtypep-arg2) (type1 type2)
1868   (union-complex-subtypep-arg2 type1 type2))
1869
1870 (!define-type-method (union :complex-union) (type1 type2)
1871   (let ((class1 (type-class-info type1)))
1872     (collect ((res))
1873       (let ((this-type type1))
1874         (dolist (type (union-type-types type2)
1875                       (if (res)
1876                           (make-union-type-or-something (cons this-type (res)))
1877                           this-type))
1878           (cond ((eq (type-class-info type) class1)
1879                  (let ((union (funcall (type-class-simple-union class1)
1880                                        this-type type)))
1881                    (if union
1882                        (setq this-type union)
1883                        (res type))))
1884                 ((csubtypep type this-type))
1885                 ((csubtypep type1 type) (return type2))
1886                 (t
1887                  (res type))))))))
1888
1889 ;;; For the union of union types, we let the :COMPLEX-UNION method do
1890 ;;; the work.
1891 (!define-type-method (union :simple-union) (type1 type2)
1892   (let ((res type1))
1893     (dolist (t2 (union-type-types type2) res)
1894       (setq res (type-union res t2)))))
1895
1896 (!define-type-method (union :simple-intersection2 :complex-intersection2)
1897                      (type1 type2)
1898   ;; The CSUBTYPEP clauses here let us simplify e.g.
1899   ;;   (TYPE-INTERSECTION2 (SPECIFIER-TYPE 'LIST)
1900   ;;                       (SPECIFIER-TYPE '(OR LIST VECTOR)))
1901   ;; (where LIST is (OR CONS NULL)).
1902   ;;
1903   ;; The tests are more or less (CSUBTYPEP TYPE1 TYPE2) and vice
1904   ;; versa, but it's important that we pre-expand them into
1905   ;; specialized operations on individual elements of
1906   ;; UNION-TYPE-TYPES, instead of using the ordinary call to
1907   ;; CSUBTYPEP, in order to avoid possibly invoking any methods which
1908   ;; might in turn invoke (TYPE-INTERSECTION2 TYPE1 TYPE2) and thus
1909   ;; cause infinite recursion.
1910   (cond ((union-complex-subtypep-arg2 type1 type2)
1911          type1)
1912         ((union-complex-subtypep-arg1 type2 type1)
1913          type2)
1914         (t 
1915          (let (;; a component of TYPE2 whose intersection with TYPE1
1916                ;; is nonempty
1917                (nontriv-t2 nil))
1918            (dolist (t2 (union-type-types type2) (or nontriv-t2 *empty-type*))
1919              (unless (eq *empty-type* (type-intersection type1 t2))
1920                (if nontriv-t2 ; if this is second nonempty intersection
1921                    (return nil) ; too many: can't find nice result
1922                    (setf nontriv-t2 t2))))))))
1923
1924 (!def-type-translator or (&rest type-specifiers)
1925   (reduce #'type-union
1926           (mapcar #'specifier-type type-specifiers)
1927           :initial-value *empty-type*))
1928 \f
1929 ;;;; CONS types
1930
1931 (!define-type-class cons)
1932
1933 (!def-type-translator cons (&optional (car-type-spec '*) (cdr-type-spec '*))
1934   (make-cons-type (specifier-type car-type-spec)
1935                   (specifier-type cdr-type-spec)))
1936  
1937 (!define-type-method (cons :unparse) (type)
1938   (let ((car-eltype (type-specifier (cons-type-car-type type)))
1939         (cdr-eltype (type-specifier (cons-type-cdr-type type))))
1940     (if (and (member car-eltype '(t *))
1941              (member cdr-eltype '(t *)))
1942         'cons
1943         `(cons ,car-eltype ,cdr-eltype))))
1944  
1945 (!define-type-method (cons :simple-=) (type1 type2)
1946   (declare (type cons-type type1 type2))
1947   (and (type= (cons-type-car-type type1) (cons-type-car-type type2))
1948        (type= (cons-type-cdr-type type1) (cons-type-cdr-type type2))))
1949  
1950 (!define-type-method (cons :simple-subtypep) (type1 type2)
1951   (declare (type cons-type type1 type2))
1952   (multiple-value-bind (val-car win-car)
1953       (csubtypep (cons-type-car-type type1) (cons-type-car-type type2))
1954     (multiple-value-bind (val-cdr win-cdr)
1955         (csubtypep (cons-type-cdr-type type1) (cons-type-cdr-type type2))
1956       (if (and val-car val-cdr)
1957           (values t (and win-car win-cdr))
1958           (values nil (or win-car win-cdr))))))
1959  
1960 ;;; Give up if a precise type is not possible, to avoid returning
1961 ;;; overly general types.
1962 (!define-type-method (cons :simple-union) (type1 type2)
1963   (declare (type cons-type type1 type2))
1964   (let ((car-type1 (cons-type-car-type type1))
1965         (car-type2 (cons-type-car-type type2))
1966         (cdr-type1 (cons-type-cdr-type type1))
1967         (cdr-type2 (cons-type-cdr-type type2)))
1968     (cond ((type= car-type1 car-type2)
1969            (make-cons-type car-type1
1970                            (type-union cdr-type1 cdr-type2)))
1971           ((type= cdr-type1 cdr-type2)
1972            (make-cons-type (type-union cdr-type1 cdr-type2)
1973                            cdr-type1)))))
1974
1975 (!define-type-method (cons :simple-intersection2) (type1 type2)
1976   (declare (type cons-type type1 type2))
1977   (let (car-int2
1978         cdr-int2)
1979     (and (setf car-int2 (type-intersection2 (cons-type-car-type type1)
1980                                             (cons-type-car-type type2)))
1981          (setf cdr-int2 (type-intersection2 (cons-type-cdr-type type1)
1982                                             (cons-type-cdr-type type2)))
1983          (make-cons-type car-int2 cdr-int2))))
1984 \f
1985 ;;; Return the type that describes all objects that are in X but not
1986 ;;; in Y. If we can't determine this type, then return NIL.
1987 ;;;
1988 ;;; For now, we only are clever dealing with union and member types.
1989 ;;; If either type is not a union type, then we pretend that it is a
1990 ;;; union of just one type. What we do is remove from X all the types
1991 ;;; that are a subtype any type in Y. If any type in X intersects with
1992 ;;; a type in Y but is not a subtype, then we give up.
1993 ;;;
1994 ;;; We must also special-case any member type that appears in the
1995 ;;; union. We remove from X's members all objects that are TYPEP to Y.
1996 ;;; If Y has any members, we must be careful that none of those
1997 ;;; members are CTYPEP to any of Y's non-member types. We give up in
1998 ;;; this case, since to compute that difference we would have to break
1999 ;;; the type from X into some collection of types that represents the
2000 ;;; type without that particular element. This seems too hairy to be
2001 ;;; worthwhile, given its low utility.
2002 (defun type-difference (x y)
2003   (let ((x-types (if (union-type-p x) (union-type-types x) (list x)))
2004         (y-types (if (union-type-p y) (union-type-types y) (list y))))
2005     (collect ((res))
2006       (dolist (x-type x-types)
2007         (if (member-type-p x-type)
2008             (collect ((members))
2009               (dolist (mem (member-type-members x-type))
2010                 (multiple-value-bind (val win) (ctypep mem y)
2011                   (unless win (return-from type-difference nil))
2012                   (unless val
2013                     (members mem))))
2014               (when (members)
2015                 (res (make-member-type :members (members)))))
2016             (dolist (y-type y-types (res x-type))
2017               (multiple-value-bind (val win) (csubtypep x-type y-type)
2018                 (unless win (return-from type-difference nil))
2019                 (when val (return))
2020                 (when (types-intersect x-type y-type)
2021                   (return-from type-difference nil))))))
2022
2023       (let ((y-mem (find-if #'member-type-p y-types)))
2024         (when y-mem
2025           (let ((members (member-type-members y-mem)))
2026             (dolist (x-type x-types)
2027               (unless (member-type-p x-type)
2028                 (dolist (member members)
2029                   (multiple-value-bind (val win) (ctypep member x-type)
2030                     (when (or (not win) val)
2031                       (return-from type-difference nil)))))))))
2032
2033       (cond ((null (res)) *empty-type*)
2034             ((null (rest (res))) (first (res)))
2035             (t
2036              (make-union-type-or-something (res)))))))
2037 \f
2038 (!def-type-translator array (&optional (element-type '*)
2039                                        (dimensions '*))
2040   (specialize-array-type
2041    (make-array-type :dimensions (canonical-array-dimensions dimensions)
2042                     :element-type (specifier-type element-type))))
2043
2044 (!def-type-translator simple-array (&optional (element-type '*)
2045                                               (dimensions '*))
2046   (specialize-array-type
2047    (make-array-type :dimensions (canonical-array-dimensions dimensions)
2048                     :element-type (specifier-type element-type)
2049                     :complexp nil)))
2050 \f
2051 (!defun-from-collected-cold-init-forms !late-type-cold-init)
2052
2053 (/show0 "late-type.lisp end of file")