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