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