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