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