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