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