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