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