0.7.12.31:
[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 ((and (consp hairy-spec1) (eq (car hairy-spec1) 'not)
1088                 (consp hairy-spec2) (eq (car hairy-spec2) 'not))
1089            (csubtypep (specifier-type (cadr hairy-spec2))
1090                       (specifier-type (cadr hairy-spec1))))
1091           ((equal hairy-spec1 hairy-spec2)
1092            (values t t))
1093           (t
1094            (values nil nil)))))
1095
1096 (!define-type-method (hairy :complex-subtypep-arg2) (type1 type2)
1097   (let ((hairy-spec (hairy-type-specifier type2)))
1098     (cond ((and (consp hairy-spec) (eq (car hairy-spec) 'not))
1099            (let* ((complement-type2 (specifier-type (cadr hairy-spec)))
1100                   (intersection2 (type-intersection2 type1
1101                                                      complement-type2)))
1102              (if intersection2
1103                  (values (eq intersection2 *empty-type*) t)
1104                  (invoke-complex-subtypep-arg1-method type1 type2))))
1105           (t
1106            (invoke-complex-subtypep-arg1-method type1 type2)))))
1107
1108 (!define-type-method (hairy :complex-subtypep-arg1) (type1 type2)
1109   ;; "Incrementally extended heuristic algorithms tend inexorably toward the
1110   ;; incomprehensible." -- http://www.unlambda.com/~james/lambda/lambda.txt
1111   (let ((hairy-spec (hairy-type-specifier type1)))
1112      (cond ((and (consp hairy-spec) (eq (car hairy-spec) 'not))
1113             ;; You may not believe this. I couldn't either. But then I
1114             ;; sat down and drew lots of Venn diagrams. Comments
1115             ;; involving a and b refer to the call (subtypep '(not a)
1116             ;; 'b) -- CSR, 2002-02-27.
1117             (block nil
1118               ;; (Several logical truths in this block are true as
1119               ;; long as b/=T. As of sbcl-0.7.1.28, it seems
1120               ;; impossible to construct a case with b=T where we
1121               ;; actually reach this type method, but we'll test for
1122               ;; and exclude this case anyway, since future
1123               ;; maintenance might make it possible for it to end up
1124               ;; in this code.)
1125               (multiple-value-bind (equal certain)
1126                   (type= type2 (specifier-type t))
1127                 (unless certain
1128                   (return (values nil nil)))
1129                 (when equal
1130                   (return (values t t))))
1131               (let ((complement-type1 (specifier-type (cadr hairy-spec))))
1132                 ;; Do the special cases first, in order to give us a
1133                 ;; chance if subtype/supertype relationships are hairy.
1134                 (multiple-value-bind (equal certain) 
1135                     (type= complement-type1 type2)
1136                   ;; If a = b, ~a is not a subtype of b (unless b=T,
1137                   ;; which was excluded above).
1138                   (unless certain
1139                     (return (values nil nil)))
1140                   (when equal
1141                     (return (values nil t))))
1142                 ;; KLUDGE: ANSI requires that the SUBTYPEP result
1143                 ;; between any two built-in atomic type specifiers
1144                 ;; never be uncertain. This is hard to do cleanly for
1145                 ;; the built-in types whose definitions include
1146                 ;; (NOT FOO), i.e. CONS and RATIO. However, we can do
1147                 ;; it with this hack, which uses our global knowledge
1148                 ;; that our implementation of the type system uses
1149                 ;; disjoint implementation types to represent disjoint
1150                 ;; sets (except when types are contained in other types).
1151                 ;; (This is a KLUDGE because it's fragile. Various
1152                 ;; changes in internal representation in the type
1153                 ;; system could make it start confidently returning
1154                 ;; incorrect results.) -- WHN 2002-03-08
1155                 (unless (or (type-might-contain-other-types-p complement-type1)
1156                             (type-might-contain-other-types-p type2))
1157                   ;; Because of the way our types which don't contain
1158                   ;; other types are disjoint subsets of the space of
1159                   ;; possible values, (SUBTYPEP '(NOT AA) 'B)=NIL when
1160                   ;; AA and B are simple (and B is not T, as checked above).
1161                   (return (values nil t)))
1162                 ;; The old (TYPE= TYPE1 TYPE2) branch would never be
1163                 ;; taken, as TYPE1 and TYPE2 will only be equal if
1164                 ;; they're both NOT types, and then the
1165                 ;; :SIMPLE-SUBTYPEP method would be used instead.
1166                 ;; But a CSUBTYPEP relationship might still hold:
1167                 (multiple-value-bind (equal certain)
1168                     (csubtypep complement-type1 type2)
1169                   ;; If a is a subtype of b, ~a is not a subtype of b
1170                   ;; (unless b=T, which was excluded above).
1171                   (unless certain
1172                     (return (values nil nil)))
1173                   (when equal
1174                     (return (values nil t))))
1175                 (multiple-value-bind (equal certain)
1176                     (csubtypep type2 complement-type1)
1177                   ;; If b is a subtype of a, ~a is not a subtype of b.
1178                   ;; (FIXME: That's not true if a=T. Do we know at
1179                   ;; this point that a is not T?)
1180                   (unless certain
1181                     (return (values nil nil)))
1182                   (when equal
1183                     (return (values nil t))))
1184                 ;; old CSR comment ca. 0.7.2, now obsoleted by the
1185                 ;; SIMPLE-CTYPE? KLUDGE case above:
1186                 ;;   Other cases here would rely on being able to catch
1187                 ;;   all possible cases, which the fragility of this
1188                 ;;   type system doesn't inspire me; for instance, if a
1189                 ;;   is type= to ~b, then we want T, T; if this is not
1190                 ;;   the case and the types are disjoint (have an
1191                 ;;   intersection of *empty-type*) then we want NIL, T;
1192                 ;;   else if the union of a and b is the
1193                 ;;   *universal-type* then we want T, T. So currently we
1194                 ;;   still claim to be unsure about e.g. (subtypep '(not
1195                 ;;   fixnum) 'single-float).
1196                 )))
1197            (t
1198             (values nil nil)))))
1199
1200 (!define-type-method (hairy :complex-=) (type1 type2)
1201   (declare (ignore type1 type2))
1202   (values nil nil))
1203
1204 (!define-type-method (hairy :simple-intersection2) 
1205                      (type1 type2)
1206   (if (type= type1 type2)
1207       type1
1208       nil))
1209
1210 (!define-type-method (hairy :complex-intersection2)
1211                      (type1 type2)
1212   (aver (hairy-type-p type2))
1213   (let ((hairy-type-spec (type-specifier type2)))
1214     (if (and (consp hairy-type-spec)
1215              (eq (car hairy-type-spec) 'not))
1216         (if (csubtypep type1 (specifier-type (cadr hairy-type-spec)))
1217             *empty-type*
1218             nil)
1219         nil)))
1220         
1221 (!define-type-method (hairy :simple-union2) 
1222                      (type1 type2)
1223   (if (type= type1 type2)
1224       type1
1225       nil))
1226
1227 (!define-type-method (hairy :complex-union2)
1228                      (type1 type2)
1229   (aver (hairy-type-p type2))
1230   (let ((hairy-type-spec (type-specifier type2)))
1231     (if (and (consp hairy-type-spec)
1232              (eq (car hairy-type-spec) 'not))
1233         (if (csubtypep (specifier-type (cadr hairy-type-spec)) type1)
1234             *universal-type*
1235             nil)
1236         nil)))
1237
1238 (!define-type-method (hairy :simple-=) (type1 type2)
1239   (if (equal (hairy-type-specifier type1)
1240              (hairy-type-specifier type2))
1241       (values t t)
1242       (values nil nil)))
1243
1244 (!def-type-translator not (&whole whole type)
1245   (declare (ignore type))
1246   ;; Check legality of arguments.
1247   (destructuring-bind (not typespec) whole
1248     (declare (ignore not))
1249     ;; must be legal typespec
1250     (let* ((not-type (specifier-type typespec))
1251            (spec (type-specifier not-type)))
1252       (cond
1253         ;; canonicalize (not (not foo))
1254         ((and (listp spec) (eq (car spec) 'not))
1255          (specifier-type (cadr spec)))
1256         ((eq not-type *empty-type*) *universal-type*)
1257         ((eq not-type *universal-type*) *empty-type*)
1258         ((and (numeric-type-p not-type)
1259               (null (numeric-type-low not-type))
1260               (null (numeric-type-high not-type)))
1261          (make-hairy-type :specifier whole))
1262         ;; FIXME: this is insufficiently general.  We need to
1263         ;; canonicalize over intersections and unions, too.  However,
1264         ;; this will probably suffice to get BIGNUM right, and more
1265         ;; code will be written when someone (probably Paul Dietz)
1266         ;; comes up with a test case that demonstrates a failure,
1267         ;; because right now I can't construct one.
1268         ((numeric-type-p not-type)
1269          (type-union
1270           ;; FIXME: so much effort for parsing?  This seems overly
1271           ;; compute-heavy.
1272           (specifier-type `(not ,(type-specifier
1273                                   (modified-numeric-type not-type
1274                                                          :low nil
1275                                                          :high nil))))
1276           (cond
1277             ((null (numeric-type-low not-type))
1278              (modified-numeric-type
1279               not-type
1280               :low (let ((h (numeric-type-high not-type)))
1281                      (if (consp h) h (list h)))
1282               :high nil))
1283             ((null (numeric-type-high not-type))
1284              (modified-numeric-type
1285               not-type
1286               :low nil
1287               :high (let ((l (numeric-type-low not-type)))
1288                       (if (consp l) l (list l)))))
1289             (t (type-union
1290                 (modified-numeric-type
1291                  not-type
1292                  :low nil
1293                  :high (let ((l (numeric-type-low not-type)))
1294                          (if (consp l) l (list l))))
1295                 (modified-numeric-type
1296                  not-type
1297                  :low (let ((h (numeric-type-high not-type)))
1298                         (if (consp h) h (list h)))
1299                  :high nil))))))
1300         (t (make-hairy-type :specifier whole))))))
1301
1302 (!def-type-translator satisfies (&whole whole fun)
1303   (declare (ignore fun))
1304   ;; Check legality of arguments.
1305   (destructuring-bind (satisfies predicate-name) whole
1306     (declare (ignore satisfies))
1307     (unless (symbolp predicate-name)
1308       (error 'simple-type-error
1309              :datum predicate-name
1310              :expected-type 'symbol
1311              :format-control "The SATISFIES predicate name is not a symbol: ~S"
1312              :format-arguments (list predicate-name))))
1313   ;; Create object.
1314   (make-hairy-type :specifier whole))
1315 \f
1316 ;;;; numeric types
1317
1318 (!define-type-class number)
1319
1320 (!define-type-method (number :simple-=) (type1 type2)
1321   (values
1322    (and (eq (numeric-type-class type1) (numeric-type-class type2))
1323         (eq (numeric-type-format type1) (numeric-type-format type2))
1324         (eq (numeric-type-complexp type1) (numeric-type-complexp type2))
1325         (equal (numeric-type-low type1) (numeric-type-low type2))
1326         (equal (numeric-type-high type1) (numeric-type-high type2)))
1327    t))
1328
1329 (!define-type-method (number :unparse) (type)
1330   (let* ((complexp (numeric-type-complexp type))
1331          (low (numeric-type-low type))
1332          (high (numeric-type-high type))
1333          (base (case (numeric-type-class type)
1334                  (integer 'integer)
1335                  (rational 'rational)
1336                  (float (or (numeric-type-format type) 'float))
1337                  (t 'real))))
1338     (let ((base+bounds
1339            (cond ((and (eq base 'integer) high low)
1340                   (let ((high-count (logcount high))
1341                         (high-length (integer-length high)))
1342                     (cond ((= low 0)
1343                            (cond ((= high 0) '(integer 0 0))
1344                                  ((= high 1) 'bit)
1345                                  ((and (= high-count high-length)
1346                                        (plusp high-length))
1347                                   `(unsigned-byte ,high-length))
1348                                  (t
1349                                   `(mod ,(1+ high)))))
1350                           ((and (= low sb!xc:most-negative-fixnum)
1351                                 (= high sb!xc:most-positive-fixnum))
1352                            'fixnum)
1353                           ((and (= low (lognot high))
1354                                 (= high-count high-length)
1355                                 (> high-count 0))
1356                            `(signed-byte ,(1+ high-length)))
1357                           (t
1358                            `(integer ,low ,high)))))
1359                  (high `(,base ,(or low '*) ,high))
1360                  (low
1361                   (if (and (eq base 'integer) (= low 0))
1362                       'unsigned-byte
1363                       `(,base ,low)))
1364                  (t base))))
1365       (ecase complexp
1366         (:real
1367          base+bounds)
1368         (:complex
1369          (if (eq base+bounds 'real)
1370              'complex
1371              `(complex ,base+bounds)))
1372         ((nil)
1373          (aver (eq base+bounds 'real))
1374          'number)))))
1375
1376 ;;; Return true if X is "less than or equal" to Y, taking open bounds
1377 ;;; into consideration. CLOSED is the predicate used to test the bound
1378 ;;; on a closed interval (e.g. <=), and OPEN is the predicate used on
1379 ;;; open bounds (e.g. <). Y is considered to be the outside bound, in
1380 ;;; the sense that if it is infinite (NIL), then the test succeeds,
1381 ;;; whereas if X is infinite, then the test fails (unless Y is also
1382 ;;; infinite).
1383 ;;;
1384 ;;; This is for comparing bounds of the same kind, e.g. upper and
1385 ;;; upper. Use NUMERIC-BOUND-TEST* for different kinds of bounds.
1386 #!-negative-zero-is-not-zero
1387 (defmacro numeric-bound-test (x y closed open)
1388   `(cond ((not ,y) t)
1389          ((not ,x) nil)
1390          ((consp ,x)
1391           (if (consp ,y)
1392               (,closed (car ,x) (car ,y))
1393               (,closed (car ,x) ,y)))
1394          (t
1395           (if (consp ,y)
1396               (,open ,x (car ,y))
1397               (,closed ,x ,y)))))
1398
1399 #!+negative-zero-is-not-zero
1400 (defmacro numeric-bound-test-zero (op x y)
1401   `(if (and (zerop ,x) (zerop ,y) (floatp ,x) (floatp ,y))
1402        (,op (float-sign ,x) (float-sign ,y))
1403        (,op ,x ,y)))
1404
1405 #!+negative-zero-is-not-zero
1406 (defmacro numeric-bound-test (x y closed open)
1407   `(cond ((not ,y) t)
1408          ((not ,x) nil)
1409          ((consp ,x)
1410           (if (consp ,y)
1411               (numeric-bound-test-zero ,closed (car ,x) (car ,y))
1412               (numeric-bound-test-zero ,closed (car ,x) ,y)))
1413          (t
1414           (if (consp ,y)
1415               (numeric-bound-test-zero ,open ,x (car ,y))
1416               (numeric-bound-test-zero ,closed ,x ,y)))))
1417
1418 ;;; This is used to compare upper and lower bounds. This is different
1419 ;;; from the same-bound case:
1420 ;;; -- Since X = NIL is -infinity, whereas y = NIL is +infinity, we
1421 ;;;    return true if *either* arg is NIL.
1422 ;;; -- an open inner bound is "greater" and also squeezes the interval,
1423 ;;;    causing us to use the OPEN test for those cases as well.
1424 #!-negative-zero-is-not-zero
1425 (defmacro numeric-bound-test* (x y closed open)
1426   `(cond ((not ,y) t)
1427          ((not ,x) t)
1428          ((consp ,x)
1429           (if (consp ,y)
1430               (,open (car ,x) (car ,y))
1431               (,open (car ,x) ,y)))
1432          (t
1433           (if (consp ,y)
1434               (,open ,x (car ,y))
1435               (,closed ,x ,y)))))
1436
1437 #!+negative-zero-is-not-zero
1438 (defmacro numeric-bound-test* (x y closed open)
1439   `(cond ((not ,y) t)
1440          ((not ,x) t)
1441          ((consp ,x)
1442           (if (consp ,y)
1443               (numeric-bound-test-zero ,open (car ,x) (car ,y))
1444               (numeric-bound-test-zero ,open (car ,x) ,y)))
1445          (t
1446           (if (consp ,y)
1447               (numeric-bound-test-zero ,open ,x (car ,y))
1448               (numeric-bound-test-zero ,closed ,x ,y)))))
1449
1450 ;;; Return whichever of the numeric bounds X and Y is "maximal"
1451 ;;; according to the predicates CLOSED (e.g. >=) and OPEN (e.g. >).
1452 ;;; This is only meaningful for maximizing like bounds, i.e. upper and
1453 ;;; upper. If MAX-P is true, then we return NIL if X or Y is NIL,
1454 ;;; otherwise we return the other arg.
1455 (defmacro numeric-bound-max (x y closed open max-p)
1456   (once-only ((n-x x)
1457               (n-y y))
1458     `(cond ((not ,n-x) ,(if max-p nil n-y))
1459            ((not ,n-y) ,(if max-p nil n-x))
1460            ((consp ,n-x)
1461             (if (consp ,n-y)
1462                 (if (,closed (car ,n-x) (car ,n-y)) ,n-x ,n-y)
1463                 (if (,open (car ,n-x) ,n-y) ,n-x ,n-y)))
1464            (t
1465             (if (consp ,n-y)
1466                 (if (,open (car ,n-y) ,n-x) ,n-y ,n-x)
1467                 (if (,closed ,n-y ,n-x) ,n-y ,n-x))))))
1468
1469 (!define-type-method (number :simple-subtypep) (type1 type2)
1470   (let ((class1 (numeric-type-class type1))
1471         (class2 (numeric-type-class type2))
1472         (complexp2 (numeric-type-complexp type2))
1473         (format2 (numeric-type-format type2))
1474         (low1 (numeric-type-low type1))
1475         (high1 (numeric-type-high type1))
1476         (low2 (numeric-type-low type2))
1477         (high2 (numeric-type-high type2)))
1478     ;; If one is complex and the other isn't, they are disjoint.
1479     (cond ((not (or (eq (numeric-type-complexp type1) complexp2)
1480                     (null complexp2)))
1481            (values nil t))
1482           ;; If the classes are specified and different, the types are
1483           ;; disjoint unless type2 is rational and type1 is integer.
1484           ((not (or (eq class1 class2)
1485                     (null class2)
1486                     (and (eq class1 'integer)
1487                          (eq class2 'rational))))
1488            (values nil t))
1489           ;; If the float formats are specified and different, the types
1490           ;; are disjoint.
1491           ((not (or (eq (numeric-type-format type1) format2)
1492                     (null format2)))
1493            (values nil t))
1494           ;; Check the bounds.
1495           ((and (numeric-bound-test low1 low2 >= >)
1496                 (numeric-bound-test high1 high2 <= <))
1497            (values t t))
1498           (t
1499            (values nil t)))))
1500
1501 (!define-superclasses number ((number)) !cold-init-forms)
1502
1503 ;;; If the high bound of LOW is adjacent to the low bound of HIGH,
1504 ;;; then return true, otherwise NIL.
1505 (defun numeric-types-adjacent (low high)
1506   (let ((low-bound (numeric-type-high low))
1507         (high-bound (numeric-type-low high)))
1508     (cond ((not (and low-bound high-bound)) nil)
1509           ((and (consp low-bound) (consp high-bound)) nil)
1510           ((consp low-bound)
1511            #!-negative-zero-is-not-zero
1512            (let ((low-value (car low-bound)))
1513              (or (eql low-value high-bound)
1514                  (and (eql low-value -0f0) (eql high-bound 0f0))
1515                  (and (eql low-value 0f0) (eql high-bound -0f0))
1516                  (and (eql low-value -0d0) (eql high-bound 0d0))
1517                  (and (eql low-value 0d0) (eql high-bound -0d0))))
1518            #!+negative-zero-is-not-zero
1519            (eql (car low-bound) high-bound))
1520           ((consp high-bound)
1521            #!-negative-zero-is-not-zero
1522            (let ((high-value (car high-bound)))
1523              (or (eql high-value low-bound)
1524                  (and (eql high-value -0f0) (eql low-bound 0f0))
1525                  (and (eql high-value 0f0) (eql low-bound -0f0))
1526                  (and (eql high-value -0d0) (eql low-bound 0d0))
1527                  (and (eql high-value 0d0) (eql low-bound -0d0))))
1528            #!+negative-zero-is-not-zero
1529            (eql (car high-bound) low-bound))
1530           #!+negative-zero-is-not-zero
1531           ((or (and (eql low-bound -0f0) (eql high-bound 0f0))
1532                (and (eql low-bound -0d0) (eql high-bound 0d0))))
1533           ((and (eq (numeric-type-class low) 'integer)
1534                 (eq (numeric-type-class high) 'integer))
1535            (eql (1+ low-bound) high-bound))
1536           (t
1537            nil))))
1538
1539 ;;; Return a numeric type that is a supertype for both TYPE1 and TYPE2.
1540 ;;;
1541 ;;; ### Note: we give up early to keep from dropping lots of information on
1542 ;;; the floor by returning overly general types.
1543 (!define-type-method (number :simple-union2) (type1 type2)
1544   (declare (type numeric-type type1 type2))
1545   (cond ((csubtypep type1 type2) type2)
1546         ((csubtypep type2 type1) type1)
1547         (t
1548          (let ((class1 (numeric-type-class type1))
1549                (format1 (numeric-type-format type1))
1550                (complexp1 (numeric-type-complexp type1))
1551                (class2 (numeric-type-class type2))
1552                (format2 (numeric-type-format type2))
1553                (complexp2 (numeric-type-complexp type2)))
1554            (when (and (eq class1 class2)
1555                       (eq format1 format2)
1556                       (eq complexp1 complexp2)
1557                       (or (numeric-types-intersect type1 type2)
1558                           (numeric-types-adjacent type1 type2)
1559                           (numeric-types-adjacent type2 type1)))
1560              (make-numeric-type
1561               :class class1
1562               :format format1
1563               :complexp complexp1
1564               :low (numeric-bound-max (numeric-type-low type1)
1565                                       (numeric-type-low type2)
1566                                       <= < t)
1567               :high (numeric-bound-max (numeric-type-high type1)
1568                                        (numeric-type-high type2)
1569                                        >= > t)))))))
1570
1571 (!cold-init-forms
1572   (setf (info :type :kind 'number)
1573         #+sb-xc-host :defined #-sb-xc-host :primitive)
1574   (setf (info :type :builtin 'number)
1575         (make-numeric-type :complexp nil)))
1576
1577 (!def-type-translator complex (&optional (typespec '*))
1578   (if (eq typespec '*)
1579       (make-numeric-type :complexp :complex)
1580       (labels ((not-numeric ()
1581                  (error "The component type for COMPLEX is not numeric: ~S"
1582                         typespec))
1583                (not-real ()
1584                  (error "The component type for COMPLEX is not real: ~S"
1585                         typespec))
1586                (complex1 (component-type)
1587                  (unless (numeric-type-p component-type)
1588                    (not-numeric))
1589                  (when (eq (numeric-type-complexp component-type) :complex)
1590                    (not-real))
1591                  (modified-numeric-type component-type :complexp :complex))
1592                (complex-union (component)
1593                  (unless (numberp component)
1594                    (not-numeric))
1595                  ;; KLUDGE: This TYPECASE more or less does
1596                  ;; (UPGRADED-COMPLEX-PART-TYPE (TYPE-OF COMPONENT)),
1597                  ;; (plus a small hack to treat (EQL COMPONENT 0) specially)
1598                  ;; but uses logic cut and pasted from the DEFUN of
1599                  ;; UPGRADED-COMPLEX-PART-TYPE. That's fragile, because
1600                  ;; changing the definition of UPGRADED-COMPLEX-PART-TYPE
1601                  ;; would tend to break the code here. Unfortunately,
1602                  ;; though, reusing UPGRADED-COMPLEX-PART-TYPE here
1603                  ;; would cause another kind of fragility, because
1604                  ;; ANSI's definition of TYPE-OF is so weak that e.g.
1605                  ;; (UPGRADED-COMPLEX-PART-TYPE (TYPE-OF 1/2)) could
1606                  ;; end up being (UPGRADED-COMPLEX-PART-TYPE 'REAL)
1607                  ;; instead of (UPGRADED-COMPLEX-PART-TYPE 'RATIONAL).
1608                  ;; So using TYPE-OF would mean that ANSI-conforming
1609                  ;; maintenance changes in TYPE-OF could break the code here.
1610                  ;; It's not clear how best to fix this. -- WHN 2002-01-21,
1611                  ;; trying to summarize CSR's concerns in his patch
1612                  (typecase component
1613                    (complex (error "The component type for COMPLEX (EQL X) ~
1614                                     is complex: ~S"
1615                                    component))
1616                    ((eql 0) (specifier-type nil)) ; as required by ANSI
1617                    (single-float (specifier-type '(complex single-float)))
1618                    (double-float (specifier-type '(complex double-float)))
1619                    #!+long-float
1620                    (long-float (specifier-type '(complex long-float)))
1621                    (rational (specifier-type '(complex rational)))
1622                    (t (specifier-type '(complex real))))))
1623         (let ((ctype (specifier-type typespec)))
1624           (typecase ctype
1625             (numeric-type (complex1 ctype))
1626             (union-type (apply #'type-union
1627                                ;; FIXME: This code could suffer from
1628                                ;; (admittedly very obscure) cases of
1629                                ;; bug 145 e.g. when TYPE is
1630                                ;;   (OR (AND INTEGER (SATISFIES ODDP))
1631                                ;;       (AND FLOAT (SATISFIES FOO))
1632                                ;; and not even report the problem very well.
1633                                (mapcar #'complex1
1634                                        (union-type-types ctype))))
1635             ;; MEMBER-TYPE is almost the same as UNION-TYPE, but
1636             ;; there's a gotcha: (COMPLEX (EQL 0)) is, according to
1637             ;; ANSI, equal to type NIL, the empty set.
1638             (member-type (apply #'type-union
1639                                 (mapcar #'complex-union
1640                                         (member-type-members ctype))))
1641             (t
1642              (multiple-value-bind (subtypep certainly)
1643                  (csubtypep ctype (specifier-type 'real))
1644                (if (and (not subtypep) certainly)
1645                    (not-real)
1646                    ;; ANSI just says that TYPESPEC is any subtype of
1647                    ;; type REAL, not necessarily a NUMERIC-TYPE. In
1648                    ;; particular, at this point TYPESPEC could legally be
1649                    ;; an intersection type like (AND REAL (SATISFIES ODDP)),
1650                    ;; in which case we fall through the logic above and
1651                    ;; end up here, stumped.
1652                    (bug "~@<(known bug #145): The type ~S is too hairy to be 
1653                          used for a COMPLEX component.~:@>"
1654                         typespec)))))))))
1655
1656 ;;; If X is *, return NIL, otherwise return the bound, which must be a
1657 ;;; member of TYPE or a one-element list of a member of TYPE.
1658 #!-sb-fluid (declaim (inline canonicalized-bound))
1659 (defun canonicalized-bound (bound type)
1660   (cond ((eq bound '*) nil)
1661         ((or (sb!xc:typep bound type)
1662              (and (consp bound)
1663                   (sb!xc:typep (car bound) type)
1664                   (null (cdr bound))))
1665           bound)
1666         (t
1667          (error "Bound is not ~S, a ~S or a list of a ~S: ~S"
1668                 '*
1669                 type
1670                 type
1671                 bound))))
1672
1673 (!def-type-translator integer (&optional (low '*) (high '*))
1674   (let* ((l (canonicalized-bound low 'integer))
1675          (lb (if (consp l) (1+ (car l)) l))
1676          (h (canonicalized-bound high 'integer))
1677          (hb (if (consp h) (1- (car h)) h)))
1678     (if (and hb lb (< hb lb))
1679         ;; previously we threw an error here:
1680         ;; (error "Lower bound ~S is greater than upper bound ~S." l h))
1681         ;; but ANSI doesn't say anything about that, so:
1682         *empty-type*
1683       (make-numeric-type :class 'integer
1684                          :complexp :real
1685                          :enumerable (not (null (and l h)))
1686                          :low lb
1687                          :high hb))))
1688
1689 (defmacro !def-bounded-type (type class format)
1690   `(!def-type-translator ,type (&optional (low '*) (high '*))
1691      (let ((lb (canonicalized-bound low ',type))
1692            (hb (canonicalized-bound high ',type)))
1693        (if (not (numeric-bound-test* lb hb <= <))
1694            ;; as above, previously we did
1695            ;; (error "Lower bound ~S is not less than upper bound ~S." low high))
1696            ;; but it is correct to do
1697            *empty-type*
1698          (make-numeric-type :class ',class
1699                             :format ',format
1700                             :low lb
1701                             :high hb)))))
1702
1703 (!def-bounded-type rational rational nil)
1704
1705 ;;; Unlike CMU CL, we represent the types FLOAT and REAL as
1706 ;;; UNION-TYPEs of more primitive types, in order to make
1707 ;;; type representation more unique, avoiding problems in the
1708 ;;; simplification of things like
1709 ;;;   (subtypep '(or (single-float -1.0 1.0) (single-float 0.1))
1710 ;;;             '(or (real -1 7) (single-float 0.1) (single-float -1.0 1.0)))
1711 ;;; When we allowed REAL to remain as a separate NUMERIC-TYPE,
1712 ;;; it was too easy for the first argument to be simplified to
1713 ;;; '(SINGLE-FLOAT -1.0), and for the second argument to be simplified
1714 ;;; to '(OR (REAL -1 7) (SINGLE-FLOAT 0.1)) and then for the
1715 ;;; SUBTYPEP to fail (returning NIL,T instead of T,T) because
1716 ;;; the first argument can't be seen to be a subtype of any of the
1717 ;;; terms in the second argument.
1718 ;;;
1719 ;;; The old CMU CL way was:
1720 ;;;   (!def-bounded-type float float nil)
1721 ;;;   (!def-bounded-type real nil nil)
1722 ;;;
1723 ;;; FIXME: If this new way works for a while with no weird new
1724 ;;; problems, we can go back and rip out support for separate FLOAT
1725 ;;; and REAL flavors of NUMERIC-TYPE. The new way was added in
1726 ;;; sbcl-0.6.11.22, 2001-03-21.
1727 ;;;
1728 ;;; FIXME: It's probably necessary to do something to fix the
1729 ;;; analogous problem with INTEGER and RATIONAL types. Perhaps
1730 ;;; bounded RATIONAL types should be represented as (OR RATIO INTEGER).
1731 (defun coerce-bound (bound type inner-coerce-bound-fun)
1732   (declare (type function inner-coerce-bound-fun))
1733   (cond ((eql bound '*)
1734          bound)
1735         ((consp bound)
1736          (destructuring-bind (inner-bound) bound
1737            (list (funcall inner-coerce-bound-fun inner-bound type))))
1738         (t
1739          (funcall inner-coerce-bound-fun bound type))))
1740 (defun inner-coerce-real-bound (bound type)
1741   (ecase type
1742     (rational (rationalize bound))
1743     (float (if (floatp bound)
1744                bound
1745                ;; Coerce to the widest float format available, to
1746                ;; avoid unnecessary loss of precision:
1747                (coerce bound 'long-float)))))
1748 (defun coerced-real-bound (bound type)
1749   (coerce-bound bound type #'inner-coerce-real-bound))
1750 (defun coerced-float-bound (bound type)
1751   (coerce-bound bound type #'coerce))
1752 (!def-type-translator real (&optional (low '*) (high '*))
1753   (specifier-type `(or (float ,(coerced-real-bound  low 'float)
1754                               ,(coerced-real-bound high 'float))
1755                        (rational ,(coerced-real-bound  low 'rational)
1756                                  ,(coerced-real-bound high 'rational)))))
1757 (!def-type-translator float (&optional (low '*) (high '*))
1758   (specifier-type 
1759    `(or (single-float ,(coerced-float-bound  low 'single-float)
1760                       ,(coerced-float-bound high 'single-float))
1761         (double-float ,(coerced-float-bound  low 'double-float)
1762                       ,(coerced-float-bound high 'double-float))
1763         #!+long-float ,(error "stub: no long float support yet"))))
1764
1765 (defmacro !define-float-format (f)
1766   `(!def-bounded-type ,f float ,f))
1767
1768 (!define-float-format short-float)
1769 (!define-float-format single-float)
1770 (!define-float-format double-float)
1771 (!define-float-format long-float)
1772
1773 (defun numeric-types-intersect (type1 type2)
1774   (declare (type numeric-type type1 type2))
1775   (let* ((class1 (numeric-type-class type1))
1776          (class2 (numeric-type-class type2))
1777          (complexp1 (numeric-type-complexp type1))
1778          (complexp2 (numeric-type-complexp type2))
1779          (format1 (numeric-type-format type1))
1780          (format2 (numeric-type-format type2))
1781          (low1 (numeric-type-low type1))
1782          (high1 (numeric-type-high type1))
1783          (low2 (numeric-type-low type2))
1784          (high2 (numeric-type-high type2)))
1785     ;; If one is complex and the other isn't, then they are disjoint.
1786     (cond ((not (or (eq complexp1 complexp2)
1787                     (null complexp1) (null complexp2)))
1788            nil)
1789           ;; If either type is a float, then the other must either be
1790           ;; specified to be a float or unspecified. Otherwise, they
1791           ;; are disjoint.
1792           ((and (eq class1 'float)
1793                 (not (member class2 '(float nil)))) nil)
1794           ((and (eq class2 'float)
1795                 (not (member class1 '(float nil)))) nil)
1796           ;; If the float formats are specified and different, the
1797           ;; types are disjoint.
1798           ((not (or (eq format1 format2) (null format1) (null format2)))
1799            nil)
1800           (t
1801            ;; Check the bounds. This is a bit odd because we must
1802            ;; always have the outer bound of the interval as the
1803            ;; second arg.
1804            (if (numeric-bound-test high1 high2 <= <)
1805                (or (and (numeric-bound-test low1 low2 >= >)
1806                         (numeric-bound-test* low1 high2 <= <))
1807                    (and (numeric-bound-test low2 low1 >= >)
1808                         (numeric-bound-test* low2 high1 <= <)))
1809                (or (and (numeric-bound-test* low2 high1 <= <)
1810                         (numeric-bound-test low2 low1 >= >))
1811                    (and (numeric-bound-test high2 high1 <= <)
1812                         (numeric-bound-test* high2 low1 >= >))))))))
1813
1814 ;;; Take the numeric bound X and convert it into something that can be
1815 ;;; used as a bound in a numeric type with the specified CLASS and
1816 ;;; FORMAT. If UP-P is true, then we round up as needed, otherwise we
1817 ;;; round down. UP-P true implies that X is a lower bound, i.e. (N) > N.
1818 ;;;
1819 ;;; This is used by NUMERIC-TYPE-INTERSECTION to mash the bound into
1820 ;;; the appropriate type number. X may only be a float when CLASS is
1821 ;;; FLOAT.
1822 ;;;
1823 ;;; ### Note: it is possible for the coercion to a float to overflow
1824 ;;; or underflow. This happens when the bound doesn't fit in the
1825 ;;; specified format. In this case, we should really return the
1826 ;;; appropriate {Most | Least}-{Positive | Negative}-XXX-Float float
1827 ;;; of desired format. But these conditions aren't currently signalled
1828 ;;; in any useful way.
1829 ;;;
1830 ;;; Also, when converting an open rational bound into a float we
1831 ;;; should probably convert it to a closed bound of the closest float
1832 ;;; in the specified format. KLUDGE: In general, open float bounds are
1833 ;;; screwed up. -- (comment from original CMU CL)
1834 (defun round-numeric-bound (x class format up-p)
1835   (if x
1836       (let ((cx (if (consp x) (car x) x)))
1837         (ecase class
1838           ((nil rational) x)
1839           (integer
1840            (if (and (consp x) (integerp cx))
1841                (if up-p (1+ cx) (1- cx))
1842                (if up-p (ceiling cx) (floor cx))))
1843           (float
1844            (let ((res (if format (coerce cx format) (float cx))))
1845              (if (consp x) (list res) res)))))
1846       nil))
1847
1848 ;;; Handle the case of type intersection on two numeric types. We use
1849 ;;; TYPES-EQUAL-OR-INTERSECT to throw out the case of types with no
1850 ;;; intersection. If an attribute in TYPE1 is unspecified, then we use
1851 ;;; TYPE2's attribute, which must be at least as restrictive. If the
1852 ;;; types intersect, then the only attributes that can be specified
1853 ;;; and different are the class and the bounds.
1854 ;;;
1855 ;;; When the class differs, we use the more restrictive class. The
1856 ;;; only interesting case is RATIONAL/INTEGER, since RATIONAL includes
1857 ;;; INTEGER.
1858 ;;;
1859 ;;; We make the result lower (upper) bound the maximum (minimum) of
1860 ;;; the argument lower (upper) bounds. We convert the bounds into the
1861 ;;; appropriate numeric type before maximizing. This avoids possible
1862 ;;; confusion due to mixed-type comparisons (but I think the result is
1863 ;;; the same).
1864 (!define-type-method (number :simple-intersection2) (type1 type2)
1865   (declare (type numeric-type type1 type2))
1866   (if (numeric-types-intersect type1 type2)
1867       (let* ((class1 (numeric-type-class type1))
1868              (class2 (numeric-type-class type2))
1869              (class (ecase class1
1870                       ((nil) class2)
1871                       ((integer float) class1)
1872                       (rational (if (eq class2 'integer)
1873                                        'integer
1874                                        'rational))))
1875              (format (or (numeric-type-format type1)
1876                          (numeric-type-format type2))))
1877         (make-numeric-type
1878          :class class
1879          :format format
1880          :complexp (or (numeric-type-complexp type1)
1881                        (numeric-type-complexp type2))
1882          :low (numeric-bound-max
1883                (round-numeric-bound (numeric-type-low type1)
1884                                     class format t)
1885                (round-numeric-bound (numeric-type-low type2)
1886                                     class format t)
1887                > >= nil)
1888          :high (numeric-bound-max
1889                 (round-numeric-bound (numeric-type-high type1)
1890                                      class format nil)
1891                 (round-numeric-bound (numeric-type-high type2)
1892                                      class format nil)
1893                 < <= nil)))
1894       *empty-type*))
1895
1896 ;;; Given two float formats, return the one with more precision. If
1897 ;;; either one is null, return NIL.
1898 (defun float-format-max (f1 f2)
1899   (when (and f1 f2)
1900     (dolist (f *float-formats* (error "bad float format: ~S" f1))
1901       (when (or (eq f f1) (eq f f2))
1902         (return f)))))
1903
1904 ;;; Return the result of an operation on TYPE1 and TYPE2 according to
1905 ;;; the rules of numeric contagion. This is always NUMBER, some float
1906 ;;; format (possibly complex) or RATIONAL. Due to rational
1907 ;;; canonicalization, there isn't much we can do here with integers or
1908 ;;; rational complex numbers.
1909 ;;;
1910 ;;; If either argument is not a NUMERIC-TYPE, then return NUMBER. This
1911 ;;; is useful mainly for allowing types that are technically numbers,
1912 ;;; but not a NUMERIC-TYPE.
1913 (defun numeric-contagion (type1 type2)
1914   (if (and (numeric-type-p type1) (numeric-type-p type2))
1915       (let ((class1 (numeric-type-class type1))
1916             (class2 (numeric-type-class type2))
1917             (format1 (numeric-type-format type1))
1918             (format2 (numeric-type-format type2))
1919             (complexp1 (numeric-type-complexp type1))
1920             (complexp2 (numeric-type-complexp type2)))
1921         (cond ((or (null complexp1)
1922                    (null complexp2))
1923                (specifier-type 'number))
1924               ((eq class1 'float)
1925                (make-numeric-type
1926                 :class 'float
1927                 :format (ecase class2
1928                           (float (float-format-max format1 format2))
1929                           ((integer rational) format1)
1930                           ((nil)
1931                            ;; A double-float with any real number is a
1932                            ;; double-float.
1933                            #!-long-float
1934                            (if (eq format1 'double-float)
1935                              'double-float
1936                              nil)
1937                            ;; A long-float with any real number is a
1938                            ;; long-float.
1939                            #!+long-float
1940                            (if (eq format1 'long-float)
1941                              'long-float
1942                              nil)))
1943                 :complexp (if (or (eq complexp1 :complex)
1944                                   (eq complexp2 :complex))
1945                               :complex
1946                               :real)))
1947               ((eq class2 'float) (numeric-contagion type2 type1))
1948               ((and (eq complexp1 :real) (eq complexp2 :real))
1949                (make-numeric-type
1950                 :class (and class1 class2 'rational)
1951                 :complexp :real))
1952               (t
1953                (specifier-type 'number))))
1954       (specifier-type 'number)))
1955 \f
1956 ;;;; array types
1957
1958 (!define-type-class array)
1959
1960 ;;; What this does depends on the setting of the
1961 ;;; *USE-IMPLEMENTATION-TYPES* switch. If true, return the specialized
1962 ;;; element type, otherwise return the original element type.
1963 (defun specialized-element-type-maybe (type)
1964   (declare (type array-type type))
1965   (if *use-implementation-types*
1966       (array-type-specialized-element-type type)
1967       (array-type-element-type type)))
1968
1969 (!define-type-method (array :simple-=) (type1 type2)
1970   (if (or (unknown-type-p (array-type-element-type type1))
1971           (unknown-type-p (array-type-element-type type2)))
1972       (multiple-value-bind (equalp certainp)
1973           (type= (array-type-element-type type1)
1974                  (array-type-element-type type2))
1975         ;; by its nature, the call to TYPE= should never return NIL,
1976         ;; T, as we don't know what the UNKNOWN-TYPE will grow up to
1977         ;; be.  -- CSR, 2002-08-19
1978         (aver (not (and (not equalp) certainp)))
1979         (values equalp certainp))
1980       (values (and (equal (array-type-dimensions type1)
1981                           (array-type-dimensions type2))
1982                    (eq (array-type-complexp type1)
1983                        (array-type-complexp type2))
1984                    (type= (specialized-element-type-maybe type1)
1985                           (specialized-element-type-maybe type2)))
1986               t)))
1987
1988 (!define-type-method (array :unparse) (type)
1989   (let ((dims (array-type-dimensions type))
1990         (eltype (type-specifier (array-type-element-type type)))
1991         (complexp (array-type-complexp type)))
1992     (cond ((eq dims '*)
1993            (if (eq eltype '*)
1994                (if complexp 'array 'simple-array)
1995                (if complexp `(array ,eltype) `(simple-array ,eltype))))
1996           ((= (length dims) 1)
1997            (if complexp
1998                (if (eq (car dims) '*)
1999                    (case eltype
2000                      (bit 'bit-vector)
2001                      (base-char 'base-string)
2002                      (character 'string)
2003                      (* 'vector)
2004                      (t `(vector ,eltype)))
2005                    (case eltype
2006                      (bit `(bit-vector ,(car dims)))
2007                      (base-char `(base-string ,(car dims)))
2008                      (character `(string ,(car dims)))
2009                      (t `(vector ,eltype ,(car dims)))))
2010                (if (eq (car dims) '*)
2011                    (case eltype
2012                      (bit 'simple-bit-vector)
2013                      (base-char 'simple-base-string)
2014                      (character 'simple-string)
2015                      ((t) 'simple-vector)
2016                      (t `(simple-array ,eltype (*))))
2017                    (case eltype
2018                      (bit `(simple-bit-vector ,(car dims)))
2019                      (base-char `(simple-base-string ,(car dims)))
2020                      (character `(simple-string ,(car dims)))
2021                      ((t) `(simple-vector ,(car dims)))
2022                      (t `(simple-array ,eltype ,dims))))))
2023           (t
2024            (if complexp
2025                `(array ,eltype ,dims)
2026                `(simple-array ,eltype ,dims))))))
2027
2028 (!define-type-method (array :simple-subtypep) (type1 type2)
2029   (let ((dims1 (array-type-dimensions type1))
2030         (dims2 (array-type-dimensions type2))
2031         (complexp2 (array-type-complexp type2)))
2032     (cond (;; not subtypep unless dimensions are compatible
2033            (not (or (eq dims2 '*)
2034                     (and (not (eq dims1 '*))
2035                          ;; (sbcl-0.6.4 has trouble figuring out that
2036                          ;; DIMS1 and DIMS2 must be lists at this
2037                          ;; point, and knowing that is important to
2038                          ;; compiling EVERY efficiently.)
2039                          (= (length (the list dims1))
2040                             (length (the list dims2)))
2041                          (every (lambda (x y)
2042                                   (or (eq y '*) (eql x y)))
2043                                 (the list dims1)
2044                                 (the list dims2)))))
2045            (values nil t))
2046           ;; not subtypep unless complexness is compatible
2047           ((not (or (eq complexp2 :maybe)
2048                     (eq (array-type-complexp type1) complexp2)))
2049            (values nil t))
2050           ;; Since we didn't fail any of the tests above, we win
2051           ;; if the TYPE2 element type is wild.
2052           ((eq (array-type-element-type type2) *wild-type*)
2053            (values t t))
2054           (;; Since we didn't match any of the special cases above, we
2055            ;; can't give a good answer unless both the element types
2056            ;; have been defined.
2057            (or (unknown-type-p (array-type-element-type type1))
2058                (unknown-type-p (array-type-element-type type2)))
2059            (values nil nil))
2060           (;; Otherwise, the subtype relationship holds iff the
2061            ;; types are equal, and they're equal iff the specialized
2062            ;; element types are identical.
2063            t
2064            (values (type= (specialized-element-type-maybe type1)
2065                           (specialized-element-type-maybe type2))
2066                    t)))))
2067
2068 (!define-superclasses array
2069   ((string string)
2070    (vector vector)
2071    (array))
2072   !cold-init-forms)
2073
2074 (defun array-types-intersect (type1 type2)
2075   (declare (type array-type type1 type2))
2076   (let ((dims1 (array-type-dimensions type1))
2077         (dims2 (array-type-dimensions type2))
2078         (complexp1 (array-type-complexp type1))
2079         (complexp2 (array-type-complexp type2)))
2080     ;; See whether dimensions are compatible.
2081     (cond ((not (or (eq dims1 '*) (eq dims2 '*)
2082                     (and (= (length dims1) (length dims2))
2083                          (every (lambda (x y)
2084                                   (or (eq x '*) (eq y '*) (= x y)))
2085                                 dims1 dims2))))
2086            (values nil t))
2087           ;; See whether complexpness is compatible.
2088           ((not (or (eq complexp1 :maybe)
2089                     (eq complexp2 :maybe)
2090                     (eq complexp1 complexp2)))
2091            (values nil t))
2092           ;; Old comment:
2093           ;;
2094           ;;   If either element type is wild, then they intersect.
2095           ;;   Otherwise, the types must be identical.
2096           ;;
2097           ;; FIXME: There seems to have been a fair amount of
2098           ;; confusion about the distinction between requested element
2099           ;; type and specialized element type; here is one of
2100           ;; them. If we request an array to hold objects of an
2101           ;; unknown type, we can do no better than represent that
2102           ;; type as an array specialized on wild-type.  We keep the
2103           ;; requested element-type in the -ELEMENT-TYPE slot, and
2104           ;; *WILD-TYPE* in the -SPECIALIZED-ELEMENT-TYPE.  So, here,
2105           ;; we must test for the SPECIALIZED slot being *WILD-TYPE*,
2106           ;; not just the ELEMENT-TYPE slot.  Maybe the return value
2107           ;; in that specific case should be T, NIL?  Or maybe this
2108           ;; function should really be called
2109           ;; ARRAY-TYPES-COULD-POSSIBLY-INTERSECT?  In any case, this
2110           ;; was responsible for bug #123, and this whole issue could
2111           ;; do with a rethink and/or a rewrite.  -- CSR, 2002-08-21
2112           ((or (eq (array-type-specialized-element-type type1) *wild-type*)
2113                (eq (array-type-specialized-element-type type2) *wild-type*)
2114                (type= (specialized-element-type-maybe type1)
2115                       (specialized-element-type-maybe type2)))
2116
2117            (values t t))
2118           (t
2119            (values nil t)))))
2120
2121 (!define-type-method (array :simple-intersection2) (type1 type2)
2122   (declare (type array-type type1 type2))
2123   (if (array-types-intersect type1 type2)
2124       (let ((dims1 (array-type-dimensions type1))
2125             (dims2 (array-type-dimensions type2))
2126             (complexp1 (array-type-complexp type1))
2127             (complexp2 (array-type-complexp type2))
2128             (eltype1 (array-type-element-type type1))
2129             (eltype2 (array-type-element-type type2)))
2130         (specialize-array-type
2131          (make-array-type
2132           :dimensions (cond ((eq dims1 '*) dims2)
2133                             ((eq dims2 '*) dims1)
2134                             (t
2135                              (mapcar (lambda (x y) (if (eq x '*) y x))
2136                                      dims1 dims2)))
2137           :complexp (if (eq complexp1 :maybe) complexp2 complexp1)
2138           :element-type (if (eq eltype1 *wild-type*) eltype2 eltype1))))
2139       *empty-type*))
2140
2141 ;;; Check a supplied dimension list to determine whether it is legal,
2142 ;;; and return it in canonical form (as either '* or a list).
2143 (defun canonical-array-dimensions (dims)
2144   (typecase dims
2145     ((member *) dims)
2146     (integer
2147      (when (minusp dims)
2148        (error "Arrays can't have a negative number of dimensions: ~S" dims))
2149      (when (>= dims sb!xc:array-rank-limit)
2150        (error "array type with too many dimensions: ~S" dims))
2151      (make-list dims :initial-element '*))
2152     (list
2153      (when (>= (length dims) sb!xc:array-rank-limit)
2154        (error "array type with too many dimensions: ~S" dims))
2155      (dolist (dim dims)
2156        (unless (eq dim '*)
2157          (unless (and (integerp dim)
2158                       (>= dim 0)
2159                       (< dim sb!xc:array-dimension-limit))
2160            (error "bad dimension in array type: ~S" dim))))
2161      dims)
2162     (t
2163      (error "Array dimensions is not a list, integer or *:~%  ~S" dims))))
2164 \f
2165 ;;;; MEMBER types
2166
2167 (!define-type-class member)
2168
2169 (!define-type-method (member :unparse) (type)
2170   (let ((members (member-type-members type)))
2171     (cond
2172       ((equal members '(nil)) 'null)
2173       ((type= type (specifier-type 'standard-char)) 'standard-char)
2174       (t `(member ,@members)))))
2175
2176 (!define-type-method (member :simple-subtypep) (type1 type2)
2177   (values (subsetp (member-type-members type1) (member-type-members type2))
2178           t))
2179
2180 (!define-type-method (member :complex-subtypep-arg1) (type1 type2)
2181   (every/type (swapped-args-fun #'ctypep)
2182               type2
2183               (member-type-members type1)))
2184
2185 ;;; We punt if the odd type is enumerable and intersects with the
2186 ;;; MEMBER type. If not enumerable, then it is definitely not a
2187 ;;; subtype of the MEMBER type.
2188 (!define-type-method (member :complex-subtypep-arg2) (type1 type2)
2189   (cond ((not (type-enumerable type1)) (values nil t))
2190         ((types-equal-or-intersect type1 type2)
2191          (invoke-complex-subtypep-arg1-method type1 type2))
2192         (t (values nil t))))
2193
2194 (!define-type-method (member :simple-intersection2) (type1 type2)
2195   (let ((mem1 (member-type-members type1))
2196         (mem2 (member-type-members type2)))
2197     (cond ((subsetp mem1 mem2) type1)
2198           ((subsetp mem2 mem1) type2)
2199           (t
2200            (let ((res (intersection mem1 mem2)))
2201              (if res
2202                  (make-member-type :members res)
2203                  *empty-type*))))))
2204
2205 (!define-type-method (member :complex-intersection2) (type1 type2)
2206   (block punt
2207     (collect ((members))
2208       (let ((mem2 (member-type-members type2)))
2209         (dolist (member mem2)
2210           (multiple-value-bind (val win) (ctypep member type1)
2211             (unless win
2212               (return-from punt nil))
2213             (when val (members member))))
2214         (cond ((subsetp mem2 (members)) type2)
2215               ((null (members)) *empty-type*)
2216               (t
2217                (make-member-type :members (members))))))))
2218
2219 ;;; We don't need a :COMPLEX-UNION2, since the only interesting case is
2220 ;;; a union type, and the member/union interaction is handled by the
2221 ;;; union type method.
2222 (!define-type-method (member :simple-union2) (type1 type2)
2223   (let ((mem1 (member-type-members type1))
2224         (mem2 (member-type-members type2)))
2225     (cond ((subsetp mem1 mem2) type2)
2226           ((subsetp mem2 mem1) type1)
2227           (t
2228            (make-member-type :members (union mem1 mem2))))))
2229
2230 (!define-type-method (member :simple-=) (type1 type2)
2231   (let ((mem1 (member-type-members type1))
2232         (mem2 (member-type-members type2)))
2233     (values (and (subsetp mem1 mem2)
2234                  (subsetp mem2 mem1))
2235             t)))
2236
2237 (!define-type-method (member :complex-=) (type1 type2)
2238   (if (type-enumerable type1)
2239       (multiple-value-bind (val win) (csubtypep type2 type1)
2240         (if (or val (not win))
2241             (values nil nil)
2242             (values nil t)))
2243       (values nil t)))
2244
2245 (!def-type-translator member (&rest members)
2246   (if members
2247       (let (ms numbers)
2248         (dolist (m (remove-duplicates members))
2249           (typecase m
2250             (number (push (ctype-of m) numbers))
2251             (t (push m ms))))
2252         (apply #'type-union
2253                (if ms
2254                    (make-member-type :members ms)
2255                    *empty-type*)
2256                (nreverse numbers)))
2257       *empty-type*))
2258 \f
2259 ;;;; intersection types
2260 ;;;;
2261 ;;;; Until version 0.6.10.6, SBCL followed the original CMU CL approach
2262 ;;;; of punting on all AND types, not just the unreasonably complicated
2263 ;;;; ones. The change was motivated by trying to get the KEYWORD type
2264 ;;;; to behave sensibly:
2265 ;;;;    ;; reasonable definition
2266 ;;;;    (DEFTYPE KEYWORD () '(AND SYMBOL (SATISFIES KEYWORDP)))
2267 ;;;;    ;; reasonable behavior
2268 ;;;;    (AVER (SUBTYPEP 'KEYWORD 'SYMBOL))
2269 ;;;; Without understanding a little about the semantics of AND, we'd
2270 ;;;; get (SUBTYPEP 'KEYWORD 'SYMBOL)=>NIL,NIL and, for entirely
2271 ;;;; parallel reasons, (SUBTYPEP 'RATIO 'NUMBER)=>NIL,NIL. That's
2272 ;;;; not so good..)
2273 ;;;;
2274 ;;;; We still follow the example of CMU CL to some extent, by punting
2275 ;;;; (to the opaque HAIRY-TYPE) on sufficiently complicated types
2276 ;;;; involving AND.
2277
2278 (!define-type-class intersection)
2279
2280 ;;; A few intersection types have special names. The others just get
2281 ;;; mechanically unparsed.
2282 (!define-type-method (intersection :unparse) (type)
2283   (declare (type ctype type))
2284   (or (find type '(ratio keyword) :key #'specifier-type :test #'type=)
2285       `(and ,@(mapcar #'type-specifier (intersection-type-types type)))))
2286
2287 ;;; shared machinery for type equality: true if every type in the set
2288 ;;; TYPES1 matches a type in the set TYPES2 and vice versa
2289 (defun type=-set (types1 types2)
2290   (flet (;; true if every type in the set X matches a type in the set Y
2291          (type<=-set (x y)
2292            (declare (type list x y))
2293            (every (lambda (xelement)
2294                     (position xelement y :test #'type=))
2295                   x)))
2296     (values (and (type<=-set types1 types2)
2297                  (type<=-set types2 types1))
2298             t)))
2299
2300 ;;; Two intersection types are equal if their subtypes are equal sets.
2301 ;;;
2302 ;;; FIXME: Might it be better to use
2303 ;;;   (AND (SUBTYPEP X Y) (SUBTYPEP Y X))
2304 ;;; instead, since SUBTYPEP is the usual relationship that we care
2305 ;;; most about, so it would be good to leverage any ingenuity there
2306 ;;; in this more obscure method?
2307 (!define-type-method (intersection :simple-=) (type1 type2)
2308   (type=-set (intersection-type-types type1)
2309              (intersection-type-types type2)))
2310
2311 (defun %intersection-complex-subtypep-arg1 (type1 type2)
2312   (any/type (swapped-args-fun #'csubtypep)
2313             type2
2314             (intersection-type-types type1)))
2315
2316 (defun %intersection-simple-subtypep (type1 type2)
2317   (every/type #'%intersection-complex-subtypep-arg1
2318               type1
2319               (intersection-type-types type2)))
2320
2321 (!define-type-method (intersection :simple-subtypep) (type1 type2)
2322   (%intersection-simple-subtypep type1 type2))
2323   
2324 (!define-type-method (intersection :complex-subtypep-arg1) (type1 type2)
2325   (%intersection-complex-subtypep-arg1 type1 type2))
2326
2327 (defun %intersection-complex-subtypep-arg2 (type1 type2)
2328   (every/type #'csubtypep type1 (intersection-type-types type2)))
2329
2330 (!define-type-method (intersection :complex-subtypep-arg2) (type1 type2)
2331   (%intersection-complex-subtypep-arg2 type1 type2))
2332
2333 ;;; FIXME: This will look eeriely familiar to readers of the UNION
2334 ;;; :SIMPLE-INTERSECTION2 :COMPLEX-INTERSECTION2 method.  That's
2335 ;;; because it was generated by cut'n'paste methods.  Given that
2336 ;;; intersections and unions have all sorts of symmetries known to
2337 ;;; mathematics, it shouldn't be beyond the ken of some programmers to
2338 ;;; reflect those symmetries in code in a way that ties them together
2339 ;;; more strongly than having two independent near-copies :-/
2340 (!define-type-method (intersection :simple-union2 :complex-union2)
2341                      (type1 type2)
2342   ;; Within this method, type2 is guaranteed to be an intersection
2343   ;; type:
2344   (aver (intersection-type-p type2))
2345   ;; Make sure to call only the applicable methods...
2346   (cond ((and (intersection-type-p type1)
2347               (%intersection-simple-subtypep type1 type2)) type2)
2348         ((and (intersection-type-p type1)
2349               (%intersection-simple-subtypep type2 type1)) type1)
2350         ((and (not (intersection-type-p type1))
2351               (%intersection-complex-subtypep-arg2 type1 type2))
2352          type2)
2353         ((and (not (intersection-type-p type1))
2354               (%intersection-complex-subtypep-arg1 type2 type1))
2355          type1)
2356         (t
2357          (let ((accumulator *universal-type*))
2358            (dolist (t2 (intersection-type-types type2) accumulator)
2359              (let ((union (type-union type1 t2)))
2360                (when (union-type-p union)
2361                  ;; we give up here -- there are all sorts of ordering
2362                  ;; worries, but it's better than before.  Doing
2363                  ;; exactly the same as in the UNION
2364                  ;; :SIMPLE/:COMPLEX-INTERSECTION2 method causes stack
2365                  ;; overflow with the mutual recursion never bottoming
2366                  ;; out.
2367                  (return nil))
2368                (setf accumulator
2369                      (type-intersection2 accumulator union))
2370                ;; When our result isn't simple any more (because
2371                ;; TYPE-INTERSECTION2 was unable to give us a simple
2372                ;; result)
2373                (unless accumulator
2374                  (return nil))))))))
2375          
2376 (!def-type-translator and (&whole whole &rest type-specifiers)
2377   (apply #'type-intersection
2378          (mapcar #'specifier-type
2379                  type-specifiers)))
2380 \f
2381 ;;;; union types
2382
2383 (!define-type-class union)
2384
2385 ;;; The LIST, FLOAT and REAL types have special names.  Other union
2386 ;;; types just get mechanically unparsed.
2387 (!define-type-method (union :unparse) (type)
2388   (declare (type ctype type))
2389   (cond
2390     ((type= type (specifier-type 'list)) 'list)
2391     ((type= type (specifier-type 'float)) 'float)
2392     ((type= type (specifier-type 'real)) 'real)
2393     ((type= type (specifier-type 'sequence)) 'sequence)
2394     ((type= type (specifier-type 'bignum)) 'bignum)
2395     (t `(or ,@(mapcar #'type-specifier (union-type-types type))))))
2396
2397 ;;; Two union types are equal if they are each subtypes of each
2398 ;;; other. We need to be this clever because our complex subtypep
2399 ;;; methods are now more accurate; we don't get infinite recursion
2400 ;;; because the simple-subtypep method delegates to complex-subtypep
2401 ;;; of the individual types of type1. - CSR, 2002-04-09
2402 ;;;
2403 ;;; Previous comment, now obsolete, but worth keeping around because
2404 ;;; it is true, though too strong a condition:
2405 ;;;
2406 ;;; Two union types are equal if their subtypes are equal sets.
2407 (!define-type-method (union :simple-=) (type1 type2)
2408   (multiple-value-bind (subtype certain?)
2409       (csubtypep type1 type2)
2410     (if subtype
2411         (csubtypep type2 type1)
2412         ;; we might as well become as certain as possible.
2413         (if certain?
2414             (values nil t)
2415             (multiple-value-bind (subtype certain?)
2416                 (csubtypep type2 type1)
2417               (declare (ignore subtype))
2418               (values nil certain?))))))
2419
2420 (!define-type-method (union :complex-=) (type1 type2)
2421   (declare (ignore type1))
2422   (if (some #'hairy-type-p (union-type-types type2))
2423       (values nil nil)
2424       (values nil t)))
2425
2426 ;;; Similarly, a union type is a subtype of another if and only if
2427 ;;; every element of TYPE1 is a subtype of TYPE2.
2428 (defun union-simple-subtypep (type1 type2)
2429   (every/type (swapped-args-fun #'union-complex-subtypep-arg2)
2430               type2
2431               (union-type-types type1)))
2432
2433 (!define-type-method (union :simple-subtypep) (type1 type2)
2434   (union-simple-subtypep type1 type2))
2435   
2436 (defun union-complex-subtypep-arg1 (type1 type2)
2437   (every/type (swapped-args-fun #'csubtypep)
2438               type2
2439               (union-type-types type1)))
2440
2441 (!define-type-method (union :complex-subtypep-arg1) (type1 type2)
2442   (union-complex-subtypep-arg1 type1 type2))
2443
2444 (defun union-complex-subtypep-arg2 (type1 type2)
2445   (multiple-value-bind (sub-value sub-certain?)
2446       ;; was: (any/type #'csubtypep type1 (union-type-types type2)),
2447       ;; which turns out to be too restrictive, causing bug 91.
2448       ;;
2449       ;; the following reimplementation might look dodgy.  It is
2450       ;; dodgy. It depends on the union :complex-= method not doing
2451       ;; very much work -- certainly, not using subtypep. Reasoning:
2452       (progn
2453         ;; At this stage, we know that type2 is a union type and type1
2454         ;; isn't. We might as well check this, though:
2455         (aver (union-type-p type2))
2456         (aver (not (union-type-p type1)))
2457         ;;     A is a subset of (B1 u B2)
2458         ;; <=> A n (B1 u B2) = A
2459         ;; <=> (A n B1) u (A n B2) = A
2460         ;;
2461         ;; But, we have to be careful not to delegate this type= to
2462         ;; something that could invoke subtypep, which might get us
2463         ;; back here -> stack explosion. We therefore ensure that the
2464         ;; second type (which is the one that's dispatched on) is
2465         ;; either a union type (where we've ensured that the complex-=
2466         ;; method will not call subtypep) or something with no union
2467         ;; types involved, in which case we'll never come back here.
2468         ;;
2469         ;; If we don't do this, then e.g.
2470         ;; (SUBTYPEP '(MEMBER 3) '(OR (SATISFIES FOO) (SATISFIES BAR)))
2471         ;; would loop infinitely, as the member :complex-= method is
2472         ;; implemented in terms of subtypep.
2473         ;;
2474         ;; Ouch. - CSR, 2002-04-10
2475         (type= type1
2476                (apply #'type-union
2477                       (mapcar (lambda (x) (type-intersection type1 x))
2478                               (union-type-types type2)))))
2479     (if sub-certain?
2480         (values sub-value sub-certain?)
2481         ;; The ANY/TYPE expression above is a sufficient condition for
2482         ;; subsetness, but not a necessary one, so we might get a more
2483         ;; certain answer by this CALL-NEXT-METHOD-ish step when the
2484         ;; ANY/TYPE expression is uncertain.
2485         (invoke-complex-subtypep-arg1-method type1 type2))))
2486
2487 (!define-type-method (union :complex-subtypep-arg2) (type1 type2)
2488   (union-complex-subtypep-arg2 type1 type2))
2489
2490 (!define-type-method (union :simple-intersection2 :complex-intersection2)
2491                      (type1 type2)
2492   ;; The CSUBTYPEP clauses here let us simplify e.g.
2493   ;;   (TYPE-INTERSECTION2 (SPECIFIER-TYPE 'LIST)
2494   ;;                       (SPECIFIER-TYPE '(OR LIST VECTOR)))
2495   ;; (where LIST is (OR CONS NULL)).
2496   ;;
2497   ;; The tests are more or less (CSUBTYPEP TYPE1 TYPE2) and vice
2498   ;; versa, but it's important that we pre-expand them into
2499   ;; specialized operations on individual elements of
2500   ;; UNION-TYPE-TYPES, instead of using the ordinary call to
2501   ;; CSUBTYPEP, in order to avoid possibly invoking any methods which
2502   ;; might in turn invoke (TYPE-INTERSECTION2 TYPE1 TYPE2) and thus
2503   ;; cause infinite recursion.
2504   ;;
2505   ;; Within this method, type2 is guaranteed to be a union type:
2506   (aver (union-type-p type2))
2507   ;; Make sure to call only the applicable methods...
2508   (cond ((and (union-type-p type1)
2509               (union-simple-subtypep type1 type2)) type1)
2510         ((and (union-type-p type1)
2511               (union-simple-subtypep type2 type1)) type2)
2512         ((and (not (union-type-p type1))
2513               (union-complex-subtypep-arg2 type1 type2))
2514          type1)
2515         ((and (not (union-type-p type1))
2516               (union-complex-subtypep-arg1 type2 type1))
2517          type2)
2518         (t 
2519          ;; KLUDGE: This code accumulates a sequence of TYPE-UNION2
2520          ;; operations in a particular order, and gives up if any of
2521          ;; the sub-unions turn out not to be simple. In other cases
2522          ;; ca. sbcl-0.6.11.15, that approach to taking a union was a
2523          ;; bad idea, since it can overlook simplifications which
2524          ;; might occur if the terms were accumulated in a different
2525          ;; order. It's possible that that will be a problem here too.
2526          ;; However, I can't think of a good example to demonstrate
2527          ;; it, and without an example to demonstrate it I can't write
2528          ;; test cases, and without test cases I don't want to
2529          ;; complicate the code to address what's still a hypothetical
2530          ;; problem. So I punted. -- WHN 2001-03-20
2531          (let ((accumulator *empty-type*))
2532            (dolist (t2 (union-type-types type2) accumulator)
2533              (setf accumulator
2534                    (type-union2 accumulator
2535                                 (type-intersection type1 t2)))
2536              ;; When our result isn't simple any more (because
2537              ;; TYPE-UNION2 was unable to give us a simple result)
2538              (unless accumulator
2539                (return nil)))))))
2540
2541 (!def-type-translator or (&rest type-specifiers)
2542   (apply #'type-union
2543          (mapcar #'specifier-type
2544                  type-specifiers)))
2545 \f
2546 ;;;; CONS types
2547
2548 (!define-type-class cons)
2549
2550 (!def-type-translator cons (&optional (car-type-spec '*) (cdr-type-spec '*))
2551   (let ((car-type (specifier-type car-type-spec))
2552         (cdr-type (specifier-type cdr-type-spec)))
2553     (if (or (eq car-type *empty-type*)
2554             (eq cdr-type *empty-type*))
2555         *empty-type*
2556         (make-cons-type car-type cdr-type))))
2557  
2558 (!define-type-method (cons :unparse) (type)
2559   (let ((car-eltype (type-specifier (cons-type-car-type type)))
2560         (cdr-eltype (type-specifier (cons-type-cdr-type type))))
2561     (if (and (member car-eltype '(t *))
2562              (member cdr-eltype '(t *)))
2563         'cons
2564         `(cons ,car-eltype ,cdr-eltype))))
2565  
2566 (!define-type-method (cons :simple-=) (type1 type2)
2567   (declare (type cons-type type1 type2))
2568   (and (type= (cons-type-car-type type1) (cons-type-car-type type2))
2569        (type= (cons-type-cdr-type type1) (cons-type-cdr-type type2))))
2570  
2571 (!define-type-method (cons :simple-subtypep) (type1 type2)
2572   (declare (type cons-type type1 type2))
2573   (multiple-value-bind (val-car win-car)
2574       (csubtypep (cons-type-car-type type1) (cons-type-car-type type2))
2575     (multiple-value-bind (val-cdr win-cdr)
2576         (csubtypep (cons-type-cdr-type type1) (cons-type-cdr-type type2))
2577       (if (and val-car val-cdr)
2578           (values t (and win-car win-cdr))
2579           (values nil (or win-car win-cdr))))))
2580  
2581 ;;; Give up if a precise type is not possible, to avoid returning
2582 ;;; overly general types.
2583 (!define-type-method (cons :simple-union2) (type1 type2)
2584   (declare (type cons-type type1 type2))
2585   (let ((car-type1 (cons-type-car-type type1))
2586         (car-type2 (cons-type-car-type type2))
2587         (cdr-type1 (cons-type-cdr-type type1))
2588         (cdr-type2 (cons-type-cdr-type type2)))
2589     (cond ((type= car-type1 car-type2)
2590            (make-cons-type car-type1
2591                            (type-union cdr-type1 cdr-type2)))
2592           ((type= cdr-type1 cdr-type2)
2593            (make-cons-type (type-union cdr-type1 cdr-type2)
2594                            cdr-type1)))))
2595
2596 (!define-type-method (cons :simple-intersection2) (type1 type2)
2597   (declare (type cons-type type1 type2))
2598   (let (car-int2
2599         cdr-int2)
2600     (and (setf car-int2 (type-intersection2 (cons-type-car-type type1)
2601                                             (cons-type-car-type type2)))
2602          (setf cdr-int2 (type-intersection2 (cons-type-cdr-type type1)
2603                                             (cons-type-cdr-type type2)))
2604          (make-cons-type car-int2 cdr-int2))))
2605 \f
2606 ;;; Return the type that describes all objects that are in X but not
2607 ;;; in Y. If we can't determine this type, then return NIL.
2608 ;;;
2609 ;;; For now, we only are clever dealing with union and member types.
2610 ;;; If either type is not a union type, then we pretend that it is a
2611 ;;; union of just one type. What we do is remove from X all the types
2612 ;;; that are a subtype any type in Y. If any type in X intersects with
2613 ;;; a type in Y but is not a subtype, then we give up.
2614 ;;;
2615 ;;; We must also special-case any member type that appears in the
2616 ;;; union. We remove from X's members all objects that are TYPEP to Y.
2617 ;;; If Y has any members, we must be careful that none of those
2618 ;;; members are CTYPEP to any of Y's non-member types. We give up in
2619 ;;; this case, since to compute that difference we would have to break
2620 ;;; the type from X into some collection of types that represents the
2621 ;;; type without that particular element. This seems too hairy to be
2622 ;;; worthwhile, given its low utility.
2623 (defun type-difference (x y)
2624   (let ((x-types (if (union-type-p x) (union-type-types x) (list x)))
2625         (y-types (if (union-type-p y) (union-type-types y) (list y))))
2626     (collect ((res))
2627       (dolist (x-type x-types)
2628         (if (member-type-p x-type)
2629             (collect ((members))
2630               (dolist (mem (member-type-members x-type))
2631                 (multiple-value-bind (val win) (ctypep mem y)
2632                   (unless win (return-from type-difference nil))
2633                   (unless val
2634                     (members mem))))
2635               (when (members)
2636                 (res (make-member-type :members (members)))))
2637             (dolist (y-type y-types (res x-type))
2638               (multiple-value-bind (val win) (csubtypep x-type y-type)
2639                 (unless win (return-from type-difference nil))
2640                 (when val (return))
2641                 (when (types-equal-or-intersect x-type y-type)
2642                   (return-from type-difference nil))))))
2643       (let ((y-mem (find-if #'member-type-p y-types)))
2644         (when y-mem
2645           (let ((members (member-type-members y-mem)))
2646             (dolist (x-type x-types)
2647               (unless (member-type-p x-type)
2648                 (dolist (member members)
2649                   (multiple-value-bind (val win) (ctypep member x-type)
2650                     (when (or (not win) val)
2651                       (return-from type-difference nil)))))))))
2652       (apply #'type-union (res)))))
2653 \f
2654 (!def-type-translator array (&optional (element-type '*)
2655                                        (dimensions '*))
2656   (specialize-array-type
2657    (make-array-type :dimensions (canonical-array-dimensions dimensions)
2658                     :complexp :maybe
2659                     :element-type (specifier-type element-type))))
2660
2661 (!def-type-translator simple-array (&optional (element-type '*)
2662                                               (dimensions '*))
2663   (specialize-array-type
2664    (make-array-type :dimensions (canonical-array-dimensions dimensions)
2665                     :complexp nil
2666                     :element-type (specifier-type element-type))))
2667 \f
2668 ;;;; utilities shared between cross-compiler and target system
2669
2670 ;;; Does the type derived from compilation of an actual function
2671 ;;; definition satisfy declarations of a function's type?
2672 (defun defined-ftype-matches-declared-ftype-p (defined-ftype declared-ftype)
2673   (declare (type ctype defined-ftype declared-ftype))
2674   (flet ((is-built-in-class-function-p (ctype)
2675            (and (built-in-class-p ctype)
2676                 (eq (built-in-class-%name ctype) 'function))))
2677     (cond (;; DECLARED-FTYPE could certainly be #<BUILT-IN-CLASS FUNCTION>;
2678            ;; that's what happens when we (DECLAIM (FTYPE FUNCTION FOO)).
2679            (is-built-in-class-function-p declared-ftype)
2680            ;; In that case, any definition satisfies the declaration.
2681            t)
2682           (;; It's not clear whether or how DEFINED-FTYPE might be
2683            ;; #<BUILT-IN-CLASS FUNCTION>, but it's not obviously
2684            ;; invalid, so let's handle that case too, just in case.
2685            (is-built-in-class-function-p defined-ftype)
2686            ;; No matter what DECLARED-FTYPE might be, we can't prove
2687            ;; that an object of type FUNCTION doesn't satisfy it, so
2688            ;; we return success no matter what.
2689            t)
2690           (;; Otherwise both of them must be FUN-TYPE objects.
2691            t
2692            ;; FIXME: For now we only check compatibility of the return
2693            ;; type, not argument types, and we don't even check the
2694            ;; return type very precisely (as per bug 94a). It would be
2695            ;; good to do a better job. Perhaps to check the
2696            ;; compatibility of the arguments, we should (1) redo
2697            ;; VALUES-TYPES-EQUAL-OR-INTERSECT as
2698            ;; ARGS-TYPES-EQUAL-OR-INTERSECT, and then (2) apply it to
2699            ;; the ARGS-TYPE slices of the FUN-TYPEs. (ARGS-TYPE
2700            ;; is a base class both of VALUES-TYPE and of FUN-TYPE.)
2701            (values-types-equal-or-intersect
2702             (fun-type-returns defined-ftype)
2703             (fun-type-returns declared-ftype))))))
2704            
2705 ;;; This messy case of CTYPE for NUMBER is shared between the
2706 ;;; cross-compiler and the target system.
2707 (defun ctype-of-number (x)
2708   (let ((num (if (complexp x) (realpart x) x)))
2709     (multiple-value-bind (complexp low high)
2710         (if (complexp x)
2711             (let ((imag (imagpart x)))
2712               (values :complex (min num imag) (max num imag)))
2713             (values :real num num))
2714       (make-numeric-type :class (etypecase num
2715                                   (integer 'integer)
2716                                   (rational 'rational)
2717                                   (float 'float))
2718                          :format (and (floatp num) (float-format-name num))
2719                          :complexp complexp
2720                          :low low
2721                          :high high))))
2722 \f
2723 (locally
2724   ;; Why SAFETY 0? To suppress the is-it-the-right-structure-type
2725   ;; checking for declarations in structure accessors. Otherwise we
2726   ;; can get caught in a chicken-and-egg bootstrapping problem, whose
2727   ;; symptom on x86 OpenBSD sbcl-0.pre7.37.flaky5.22 is an illegal
2728   ;; instruction trap. I haven't tracked it down, but I'm guessing it
2729   ;; has to do with setting LAYOUTs when the LAYOUT hasn't been set
2730   ;; yet. -- WHN
2731   (declare (optimize (safety 0)))
2732   (!defun-from-collected-cold-init-forms !late-type-cold-init))
2733
2734 (/show0 "late-type.lisp end of file")