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