Fri, 08 Aug 2008 17:43:24 +0100
6676362: Spurious forward reference error with final var + instance variable initializer
Summary: Some javac forward reference errors aren't compliant with the JLS
Reviewed-by: jjg
1 /*
2 * Copyright 2003-2008 Sun Microsystems, Inc. All Rights Reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation. Sun designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Sun in the LICENSE file that accompanied this code.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
22 * CA 95054 USA or visit www.sun.com if you need additional information or
23 * have any questions.
24 */
26 package com.sun.tools.javac.code;
28 import java.util.*;
30 import com.sun.tools.javac.util.*;
31 import com.sun.tools.javac.util.List;
33 import com.sun.tools.javac.jvm.ClassReader;
34 import com.sun.tools.javac.comp.Infer;
35 import com.sun.tools.javac.comp.Check;
37 import static com.sun.tools.javac.code.Type.*;
38 import static com.sun.tools.javac.code.TypeTags.*;
39 import static com.sun.tools.javac.code.Symbol.*;
40 import static com.sun.tools.javac.code.Flags.*;
41 import static com.sun.tools.javac.code.BoundKind.*;
42 import static com.sun.tools.javac.util.ListBuffer.lb;
44 /**
45 * Utility class containing various operations on types.
46 *
47 * <p>Unless other names are more illustrative, the following naming
48 * conventions should be observed in this file:
49 *
50 * <dl>
51 * <dt>t</dt>
52 * <dd>If the first argument to an operation is a type, it should be named t.</dd>
53 * <dt>s</dt>
54 * <dd>Similarly, if the second argument to an operation is a type, it should be named s.</dd>
55 * <dt>ts</dt>
56 * <dd>If an operations takes a list of types, the first should be named ts.</dd>
57 * <dt>ss</dt>
58 * <dd>A second list of types should be named ss.</dd>
59 * </dl>
60 *
61 * <p><b>This is NOT part of any API supported by Sun Microsystems.
62 * If you write code that depends on this, you do so at your own risk.
63 * This code and its internal interfaces are subject to change or
64 * deletion without notice.</b>
65 */
66 public class Types {
67 protected static final Context.Key<Types> typesKey =
68 new Context.Key<Types>();
70 final Symtab syms;
71 final Name.Table names;
72 final boolean allowBoxing;
73 final ClassReader reader;
74 final Source source;
75 final Check chk;
76 List<Warner> warnStack = List.nil();
77 final Name capturedName;
79 // <editor-fold defaultstate="collapsed" desc="Instantiating">
80 public static Types instance(Context context) {
81 Types instance = context.get(typesKey);
82 if (instance == null)
83 instance = new Types(context);
84 return instance;
85 }
87 protected Types(Context context) {
88 context.put(typesKey, this);
89 syms = Symtab.instance(context);
90 names = Name.Table.instance(context);
91 allowBoxing = Source.instance(context).allowBoxing();
92 reader = ClassReader.instance(context);
93 source = Source.instance(context);
94 chk = Check.instance(context);
95 capturedName = names.fromString("<captured wildcard>");
96 }
97 // </editor-fold>
99 // <editor-fold defaultstate="collapsed" desc="upperBound">
100 /**
101 * The "rvalue conversion".<br>
102 * The upper bound of most types is the type
103 * itself. Wildcards, on the other hand have upper
104 * and lower bounds.
105 * @param t a type
106 * @return the upper bound of the given type
107 */
108 public Type upperBound(Type t) {
109 return upperBound.visit(t);
110 }
111 // where
112 private final MapVisitor<Void> upperBound = new MapVisitor<Void>() {
114 @Override
115 public Type visitWildcardType(WildcardType t, Void ignored) {
116 if (t.isSuperBound())
117 return t.bound == null ? syms.objectType : t.bound.bound;
118 else
119 return visit(t.type);
120 }
122 @Override
123 public Type visitCapturedType(CapturedType t, Void ignored) {
124 return visit(t.bound);
125 }
126 };
127 // </editor-fold>
129 // <editor-fold defaultstate="collapsed" desc="lowerBound">
130 /**
131 * The "lvalue conversion".<br>
132 * The lower bound of most types is the type
133 * itself. Wildcards, on the other hand have upper
134 * and lower bounds.
135 * @param t a type
136 * @return the lower bound of the given type
137 */
138 public Type lowerBound(Type t) {
139 return lowerBound.visit(t);
140 }
141 // where
142 private final MapVisitor<Void> lowerBound = new MapVisitor<Void>() {
144 @Override
145 public Type visitWildcardType(WildcardType t, Void ignored) {
146 return t.isExtendsBound() ? syms.botType : visit(t.type);
147 }
149 @Override
150 public Type visitCapturedType(CapturedType t, Void ignored) {
151 return visit(t.getLowerBound());
152 }
153 };
154 // </editor-fold>
156 // <editor-fold defaultstate="collapsed" desc="isUnbounded">
157 /**
158 * Checks that all the arguments to a class are unbounded
159 * wildcards or something else that doesn't make any restrictions
160 * on the arguments. If a class isUnbounded, a raw super- or
161 * subclass can be cast to it without a warning.
162 * @param t a type
163 * @return true iff the given type is unbounded or raw
164 */
165 public boolean isUnbounded(Type t) {
166 return isUnbounded.visit(t);
167 }
168 // where
169 private final UnaryVisitor<Boolean> isUnbounded = new UnaryVisitor<Boolean>() {
171 public Boolean visitType(Type t, Void ignored) {
172 return true;
173 }
175 @Override
176 public Boolean visitClassType(ClassType t, Void ignored) {
177 List<Type> parms = t.tsym.type.allparams();
178 List<Type> args = t.allparams();
179 while (parms.nonEmpty()) {
180 WildcardType unb = new WildcardType(syms.objectType,
181 BoundKind.UNBOUND,
182 syms.boundClass,
183 (TypeVar)parms.head);
184 if (!containsType(args.head, unb))
185 return false;
186 parms = parms.tail;
187 args = args.tail;
188 }
189 return true;
190 }
191 };
192 // </editor-fold>
194 // <editor-fold defaultstate="collapsed" desc="asSub">
195 /**
196 * Return the least specific subtype of t that starts with symbol
197 * sym. If none exists, return null. The least specific subtype
198 * is determined as follows:
199 *
200 * <p>If there is exactly one parameterized instance of sym that is a
201 * subtype of t, that parameterized instance is returned.<br>
202 * Otherwise, if the plain type or raw type `sym' is a subtype of
203 * type t, the type `sym' itself is returned. Otherwise, null is
204 * returned.
205 */
206 public Type asSub(Type t, Symbol sym) {
207 return asSub.visit(t, sym);
208 }
209 // where
210 private final SimpleVisitor<Type,Symbol> asSub = new SimpleVisitor<Type,Symbol>() {
212 public Type visitType(Type t, Symbol sym) {
213 return null;
214 }
216 @Override
217 public Type visitClassType(ClassType t, Symbol sym) {
218 if (t.tsym == sym)
219 return t;
220 Type base = asSuper(sym.type, t.tsym);
221 if (base == null)
222 return null;
223 ListBuffer<Type> from = new ListBuffer<Type>();
224 ListBuffer<Type> to = new ListBuffer<Type>();
225 try {
226 adapt(base, t, from, to);
227 } catch (AdaptFailure ex) {
228 return null;
229 }
230 Type res = subst(sym.type, from.toList(), to.toList());
231 if (!isSubtype(res, t))
232 return null;
233 ListBuffer<Type> openVars = new ListBuffer<Type>();
234 for (List<Type> l = sym.type.allparams();
235 l.nonEmpty(); l = l.tail)
236 if (res.contains(l.head) && !t.contains(l.head))
237 openVars.append(l.head);
238 if (openVars.nonEmpty()) {
239 if (t.isRaw()) {
240 // The subtype of a raw type is raw
241 res = erasure(res);
242 } else {
243 // Unbound type arguments default to ?
244 List<Type> opens = openVars.toList();
245 ListBuffer<Type> qs = new ListBuffer<Type>();
246 for (List<Type> iter = opens; iter.nonEmpty(); iter = iter.tail) {
247 qs.append(new WildcardType(syms.objectType, BoundKind.UNBOUND, syms.boundClass, (TypeVar) iter.head));
248 }
249 res = subst(res, opens, qs.toList());
250 }
251 }
252 return res;
253 }
255 @Override
256 public Type visitErrorType(ErrorType t, Symbol sym) {
257 return t;
258 }
259 };
260 // </editor-fold>
262 // <editor-fold defaultstate="collapsed" desc="isConvertible">
263 /**
264 * Is t a subtype of or convertiable via boxing/unboxing
265 * convertions to s?
266 */
267 public boolean isConvertible(Type t, Type s, Warner warn) {
268 boolean tPrimitive = t.isPrimitive();
269 boolean sPrimitive = s.isPrimitive();
270 if (tPrimitive == sPrimitive)
271 return isSubtypeUnchecked(t, s, warn);
272 if (!allowBoxing) return false;
273 return tPrimitive
274 ? isSubtype(boxedClass(t).type, s)
275 : isSubtype(unboxedType(t), s);
276 }
278 /**
279 * Is t a subtype of or convertiable via boxing/unboxing
280 * convertions to s?
281 */
282 public boolean isConvertible(Type t, Type s) {
283 return isConvertible(t, s, Warner.noWarnings);
284 }
285 // </editor-fold>
287 // <editor-fold defaultstate="collapsed" desc="isSubtype">
288 /**
289 * Is t an unchecked subtype of s?
290 */
291 public boolean isSubtypeUnchecked(Type t, Type s) {
292 return isSubtypeUnchecked(t, s, Warner.noWarnings);
293 }
294 /**
295 * Is t an unchecked subtype of s?
296 */
297 public boolean isSubtypeUnchecked(Type t, Type s, Warner warn) {
298 if (t.tag == ARRAY && s.tag == ARRAY) {
299 return (((ArrayType)t).elemtype.tag <= lastBaseTag)
300 ? isSameType(elemtype(t), elemtype(s))
301 : isSubtypeUnchecked(elemtype(t), elemtype(s), warn);
302 } else if (isSubtype(t, s)) {
303 return true;
304 }
305 else if (t.tag == TYPEVAR) {
306 return isSubtypeUnchecked(t.getUpperBound(), s, warn);
307 }
308 else if (s.tag == UNDETVAR) {
309 UndetVar uv = (UndetVar)s;
310 if (uv.inst != null)
311 return isSubtypeUnchecked(t, uv.inst, warn);
312 }
313 else if (!s.isRaw()) {
314 Type t2 = asSuper(t, s.tsym);
315 if (t2 != null && t2.isRaw()) {
316 if (isReifiable(s))
317 warn.silentUnchecked();
318 else
319 warn.warnUnchecked();
320 return true;
321 }
322 }
323 return false;
324 }
326 /**
327 * Is t a subtype of s?<br>
328 * (not defined for Method and ForAll types)
329 */
330 final public boolean isSubtype(Type t, Type s) {
331 return isSubtype(t, s, true);
332 }
333 final public boolean isSubtypeNoCapture(Type t, Type s) {
334 return isSubtype(t, s, false);
335 }
336 public boolean isSubtype(Type t, Type s, boolean capture) {
337 if (t == s)
338 return true;
340 if (s.tag >= firstPartialTag)
341 return isSuperType(s, t);
343 Type lower = lowerBound(s);
344 if (s != lower)
345 return isSubtype(capture ? capture(t) : t, lower, false);
347 return isSubtype.visit(capture ? capture(t) : t, s);
348 }
349 // where
350 private TypeRelation isSubtype = new TypeRelation()
351 {
352 public Boolean visitType(Type t, Type s) {
353 switch (t.tag) {
354 case BYTE: case CHAR:
355 return (t.tag == s.tag ||
356 t.tag + 2 <= s.tag && s.tag <= DOUBLE);
357 case SHORT: case INT: case LONG: case FLOAT: case DOUBLE:
358 return t.tag <= s.tag && s.tag <= DOUBLE;
359 case BOOLEAN: case VOID:
360 return t.tag == s.tag;
361 case TYPEVAR:
362 return isSubtypeNoCapture(t.getUpperBound(), s);
363 case BOT:
364 return
365 s.tag == BOT || s.tag == CLASS ||
366 s.tag == ARRAY || s.tag == TYPEVAR;
367 case NONE:
368 return false;
369 default:
370 throw new AssertionError("isSubtype " + t.tag);
371 }
372 }
374 private Set<TypePair> cache = new HashSet<TypePair>();
376 private boolean containsTypeRecursive(Type t, Type s) {
377 TypePair pair = new TypePair(t, s);
378 if (cache.add(pair)) {
379 try {
380 return containsType(t.getTypeArguments(),
381 s.getTypeArguments());
382 } finally {
383 cache.remove(pair);
384 }
385 } else {
386 return containsType(t.getTypeArguments(),
387 rewriteSupers(s).getTypeArguments());
388 }
389 }
391 private Type rewriteSupers(Type t) {
392 if (!t.isParameterized())
393 return t;
394 ListBuffer<Type> from = lb();
395 ListBuffer<Type> to = lb();
396 adaptSelf(t, from, to);
397 if (from.isEmpty())
398 return t;
399 ListBuffer<Type> rewrite = lb();
400 boolean changed = false;
401 for (Type orig : to.toList()) {
402 Type s = rewriteSupers(orig);
403 if (s.isSuperBound() && !s.isExtendsBound()) {
404 s = new WildcardType(syms.objectType,
405 BoundKind.UNBOUND,
406 syms.boundClass);
407 changed = true;
408 } else if (s != orig) {
409 s = new WildcardType(upperBound(s),
410 BoundKind.EXTENDS,
411 syms.boundClass);
412 changed = true;
413 }
414 rewrite.append(s);
415 }
416 if (changed)
417 return subst(t.tsym.type, from.toList(), rewrite.toList());
418 else
419 return t;
420 }
422 @Override
423 public Boolean visitClassType(ClassType t, Type s) {
424 Type sup = asSuper(t, s.tsym);
425 return sup != null
426 && sup.tsym == s.tsym
427 // You're not allowed to write
428 // Vector<Object> vec = new Vector<String>();
429 // But with wildcards you can write
430 // Vector<? extends Object> vec = new Vector<String>();
431 // which means that subtype checking must be done
432 // here instead of same-type checking (via containsType).
433 && (!s.isParameterized() || containsTypeRecursive(s, sup))
434 && isSubtypeNoCapture(sup.getEnclosingType(),
435 s.getEnclosingType());
436 }
438 @Override
439 public Boolean visitArrayType(ArrayType t, Type s) {
440 if (s.tag == ARRAY) {
441 if (t.elemtype.tag <= lastBaseTag)
442 return isSameType(t.elemtype, elemtype(s));
443 else
444 return isSubtypeNoCapture(t.elemtype, elemtype(s));
445 }
447 if (s.tag == CLASS) {
448 Name sname = s.tsym.getQualifiedName();
449 return sname == names.java_lang_Object
450 || sname == names.java_lang_Cloneable
451 || sname == names.java_io_Serializable;
452 }
454 return false;
455 }
457 @Override
458 public Boolean visitUndetVar(UndetVar t, Type s) {
459 //todo: test against origin needed? or replace with substitution?
460 if (t == s || t.qtype == s || s.tag == ERROR || s.tag == UNKNOWN)
461 return true;
463 if (t.inst != null)
464 return isSubtypeNoCapture(t.inst, s); // TODO: ", warn"?
466 t.hibounds = t.hibounds.prepend(s);
467 return true;
468 }
470 @Override
471 public Boolean visitErrorType(ErrorType t, Type s) {
472 return true;
473 }
474 };
476 /**
477 * Is t a subtype of every type in given list `ts'?<br>
478 * (not defined for Method and ForAll types)<br>
479 * Allows unchecked conversions.
480 */
481 public boolean isSubtypeUnchecked(Type t, List<Type> ts, Warner warn) {
482 for (List<Type> l = ts; l.nonEmpty(); l = l.tail)
483 if (!isSubtypeUnchecked(t, l.head, warn))
484 return false;
485 return true;
486 }
488 /**
489 * Are corresponding elements of ts subtypes of ss? If lists are
490 * of different length, return false.
491 */
492 public boolean isSubtypes(List<Type> ts, List<Type> ss) {
493 while (ts.tail != null && ss.tail != null
494 /*inlined: ts.nonEmpty() && ss.nonEmpty()*/ &&
495 isSubtype(ts.head, ss.head)) {
496 ts = ts.tail;
497 ss = ss.tail;
498 }
499 return ts.tail == null && ss.tail == null;
500 /*inlined: ts.isEmpty() && ss.isEmpty();*/
501 }
503 /**
504 * Are corresponding elements of ts subtypes of ss, allowing
505 * unchecked conversions? If lists are of different length,
506 * return false.
507 **/
508 public boolean isSubtypesUnchecked(List<Type> ts, List<Type> ss, Warner warn) {
509 while (ts.tail != null && ss.tail != null
510 /*inlined: ts.nonEmpty() && ss.nonEmpty()*/ &&
511 isSubtypeUnchecked(ts.head, ss.head, warn)) {
512 ts = ts.tail;
513 ss = ss.tail;
514 }
515 return ts.tail == null && ss.tail == null;
516 /*inlined: ts.isEmpty() && ss.isEmpty();*/
517 }
518 // </editor-fold>
520 // <editor-fold defaultstate="collapsed" desc="isSuperType">
521 /**
522 * Is t a supertype of s?
523 */
524 public boolean isSuperType(Type t, Type s) {
525 switch (t.tag) {
526 case ERROR:
527 return true;
528 case UNDETVAR: {
529 UndetVar undet = (UndetVar)t;
530 if (t == s ||
531 undet.qtype == s ||
532 s.tag == ERROR ||
533 s.tag == BOT) return true;
534 if (undet.inst != null)
535 return isSubtype(s, undet.inst);
536 undet.lobounds = undet.lobounds.prepend(s);
537 return true;
538 }
539 default:
540 return isSubtype(s, t);
541 }
542 }
543 // </editor-fold>
545 // <editor-fold defaultstate="collapsed" desc="isSameType">
546 /**
547 * Are corresponding elements of the lists the same type? If
548 * lists are of different length, return false.
549 */
550 public boolean isSameTypes(List<Type> ts, List<Type> ss) {
551 while (ts.tail != null && ss.tail != null
552 /*inlined: ts.nonEmpty() && ss.nonEmpty()*/ &&
553 isSameType(ts.head, ss.head)) {
554 ts = ts.tail;
555 ss = ss.tail;
556 }
557 return ts.tail == null && ss.tail == null;
558 /*inlined: ts.isEmpty() && ss.isEmpty();*/
559 }
561 /**
562 * Is t the same type as s?
563 */
564 public boolean isSameType(Type t, Type s) {
565 return isSameType.visit(t, s);
566 }
567 // where
568 private TypeRelation isSameType = new TypeRelation() {
570 public Boolean visitType(Type t, Type s) {
571 if (t == s)
572 return true;
574 if (s.tag >= firstPartialTag)
575 return visit(s, t);
577 switch (t.tag) {
578 case BYTE: case CHAR: case SHORT: case INT: case LONG: case FLOAT:
579 case DOUBLE: case BOOLEAN: case VOID: case BOT: case NONE:
580 return t.tag == s.tag;
581 case TYPEVAR:
582 return s.isSuperBound()
583 && !s.isExtendsBound()
584 && visit(t, upperBound(s));
585 default:
586 throw new AssertionError("isSameType " + t.tag);
587 }
588 }
590 @Override
591 public Boolean visitWildcardType(WildcardType t, Type s) {
592 if (s.tag >= firstPartialTag)
593 return visit(s, t);
594 else
595 return false;
596 }
598 @Override
599 public Boolean visitClassType(ClassType t, Type s) {
600 if (t == s)
601 return true;
603 if (s.tag >= firstPartialTag)
604 return visit(s, t);
606 if (s.isSuperBound() && !s.isExtendsBound())
607 return visit(t, upperBound(s)) && visit(t, lowerBound(s));
609 if (t.isCompound() && s.isCompound()) {
610 if (!visit(supertype(t), supertype(s)))
611 return false;
613 HashSet<SingletonType> set = new HashSet<SingletonType>();
614 for (Type x : interfaces(t))
615 set.add(new SingletonType(x));
616 for (Type x : interfaces(s)) {
617 if (!set.remove(new SingletonType(x)))
618 return false;
619 }
620 return (set.size() == 0);
621 }
622 return t.tsym == s.tsym
623 && visit(t.getEnclosingType(), s.getEnclosingType())
624 && containsTypeEquivalent(t.getTypeArguments(), s.getTypeArguments());
625 }
627 @Override
628 public Boolean visitArrayType(ArrayType t, Type s) {
629 if (t == s)
630 return true;
632 if (s.tag >= firstPartialTag)
633 return visit(s, t);
635 return s.tag == ARRAY
636 && containsTypeEquivalent(t.elemtype, elemtype(s));
637 }
639 @Override
640 public Boolean visitMethodType(MethodType t, Type s) {
641 // isSameType for methods does not take thrown
642 // exceptions into account!
643 return hasSameArgs(t, s) && visit(t.getReturnType(), s.getReturnType());
644 }
646 @Override
647 public Boolean visitPackageType(PackageType t, Type s) {
648 return t == s;
649 }
651 @Override
652 public Boolean visitForAll(ForAll t, Type s) {
653 if (s.tag != FORALL)
654 return false;
656 ForAll forAll = (ForAll)s;
657 return hasSameBounds(t, forAll)
658 && visit(t.qtype, subst(forAll.qtype, forAll.tvars, t.tvars));
659 }
661 @Override
662 public Boolean visitUndetVar(UndetVar t, Type s) {
663 if (s.tag == WILDCARD)
664 // FIXME, this might be leftovers from before capture conversion
665 return false;
667 if (t == s || t.qtype == s || s.tag == ERROR || s.tag == UNKNOWN)
668 return true;
670 if (t.inst != null)
671 return visit(t.inst, s);
673 t.inst = fromUnknownFun.apply(s);
674 for (List<Type> l = t.lobounds; l.nonEmpty(); l = l.tail) {
675 if (!isSubtype(l.head, t.inst))
676 return false;
677 }
678 for (List<Type> l = t.hibounds; l.nonEmpty(); l = l.tail) {
679 if (!isSubtype(t.inst, l.head))
680 return false;
681 }
682 return true;
683 }
685 @Override
686 public Boolean visitErrorType(ErrorType t, Type s) {
687 return true;
688 }
689 };
690 // </editor-fold>
692 // <editor-fold defaultstate="collapsed" desc="fromUnknownFun">
693 /**
694 * A mapping that turns all unknown types in this type to fresh
695 * unknown variables.
696 */
697 public Mapping fromUnknownFun = new Mapping("fromUnknownFun") {
698 public Type apply(Type t) {
699 if (t.tag == UNKNOWN) return new UndetVar(t);
700 else return t.map(this);
701 }
702 };
703 // </editor-fold>
705 // <editor-fold defaultstate="collapsed" desc="Contains Type">
706 public boolean containedBy(Type t, Type s) {
707 switch (t.tag) {
708 case UNDETVAR:
709 if (s.tag == WILDCARD) {
710 UndetVar undetvar = (UndetVar)t;
712 // Because of wildcard capture, s must be on the left
713 // hand side of an assignment. Furthermore, t is an
714 // underconstrained type variable, for example, one
715 // that is only used in the return type of a method.
716 // If the type variable is truly underconstrained, it
717 // cannot have any low bounds:
718 assert undetvar.lobounds.isEmpty() : undetvar;
720 undetvar.inst = glb(upperBound(s), undetvar.inst);
721 return true;
722 } else {
723 return isSameType(t, s);
724 }
725 case ERROR:
726 return true;
727 default:
728 return containsType(s, t);
729 }
730 }
732 boolean containsType(List<Type> ts, List<Type> ss) {
733 while (ts.nonEmpty() && ss.nonEmpty()
734 && containsType(ts.head, ss.head)) {
735 ts = ts.tail;
736 ss = ss.tail;
737 }
738 return ts.isEmpty() && ss.isEmpty();
739 }
741 /**
742 * Check if t contains s.
743 *
744 * <p>T contains S if:
745 *
746 * <p>{@code L(T) <: L(S) && U(S) <: U(T)}
747 *
748 * <p>This relation is only used by ClassType.isSubtype(), that
749 * is,
750 *
751 * <p>{@code C<S> <: C<T> if T contains S.}
752 *
753 * <p>Because of F-bounds, this relation can lead to infinite
754 * recursion. Thus we must somehow break that recursion. Notice
755 * that containsType() is only called from ClassType.isSubtype().
756 * Since the arguments have already been checked against their
757 * bounds, we know:
758 *
759 * <p>{@code U(S) <: U(T) if T is "super" bound (U(T) *is* the bound)}
760 *
761 * <p>{@code L(T) <: L(S) if T is "extends" bound (L(T) is bottom)}
762 *
763 * @param t a type
764 * @param s a type
765 */
766 public boolean containsType(Type t, Type s) {
767 return containsType.visit(t, s);
768 }
769 // where
770 private TypeRelation containsType = new TypeRelation() {
772 private Type U(Type t) {
773 while (t.tag == WILDCARD) {
774 WildcardType w = (WildcardType)t;
775 if (w.isSuperBound())
776 return w.bound == null ? syms.objectType : w.bound.bound;
777 else
778 t = w.type;
779 }
780 return t;
781 }
783 private Type L(Type t) {
784 while (t.tag == WILDCARD) {
785 WildcardType w = (WildcardType)t;
786 if (w.isExtendsBound())
787 return syms.botType;
788 else
789 t = w.type;
790 }
791 return t;
792 }
794 public Boolean visitType(Type t, Type s) {
795 if (s.tag >= firstPartialTag)
796 return containedBy(s, t);
797 else
798 return isSameType(t, s);
799 }
801 void debugContainsType(WildcardType t, Type s) {
802 System.err.println();
803 System.err.format(" does %s contain %s?%n", t, s);
804 System.err.format(" %s U(%s) <: U(%s) %s = %s%n",
805 upperBound(s), s, t, U(t),
806 t.isSuperBound()
807 || isSubtypeNoCapture(upperBound(s), U(t)));
808 System.err.format(" %s L(%s) <: L(%s) %s = %s%n",
809 L(t), t, s, lowerBound(s),
810 t.isExtendsBound()
811 || isSubtypeNoCapture(L(t), lowerBound(s)));
812 System.err.println();
813 }
815 @Override
816 public Boolean visitWildcardType(WildcardType t, Type s) {
817 if (s.tag >= firstPartialTag)
818 return containedBy(s, t);
819 else {
820 // debugContainsType(t, s);
821 return isSameWildcard(t, s)
822 || isCaptureOf(s, t)
823 || ((t.isExtendsBound() || isSubtypeNoCapture(L(t), lowerBound(s))) &&
824 (t.isSuperBound() || isSubtypeNoCapture(upperBound(s), U(t))));
825 }
826 }
828 @Override
829 public Boolean visitUndetVar(UndetVar t, Type s) {
830 if (s.tag != WILDCARD)
831 return isSameType(t, s);
832 else
833 return false;
834 }
836 @Override
837 public Boolean visitErrorType(ErrorType t, Type s) {
838 return true;
839 }
840 };
842 public boolean isCaptureOf(Type s, WildcardType t) {
843 if (s.tag != TYPEVAR || !((TypeVar)s).isCaptured())
844 return false;
845 return isSameWildcard(t, ((CapturedType)s).wildcard);
846 }
848 public boolean isSameWildcard(WildcardType t, Type s) {
849 if (s.tag != WILDCARD)
850 return false;
851 WildcardType w = (WildcardType)s;
852 return w.kind == t.kind && w.type == t.type;
853 }
855 public boolean containsTypeEquivalent(List<Type> ts, List<Type> ss) {
856 while (ts.nonEmpty() && ss.nonEmpty()
857 && containsTypeEquivalent(ts.head, ss.head)) {
858 ts = ts.tail;
859 ss = ss.tail;
860 }
861 return ts.isEmpty() && ss.isEmpty();
862 }
863 // </editor-fold>
865 // <editor-fold defaultstate="collapsed" desc="isCastable">
866 public boolean isCastable(Type t, Type s) {
867 return isCastable(t, s, Warner.noWarnings);
868 }
870 /**
871 * Is t is castable to s?<br>
872 * s is assumed to be an erased type.<br>
873 * (not defined for Method and ForAll types).
874 */
875 public boolean isCastable(Type t, Type s, Warner warn) {
876 if (t == s)
877 return true;
879 if (t.isPrimitive() != s.isPrimitive())
880 return allowBoxing && isConvertible(t, s, warn);
882 if (warn != warnStack.head) {
883 try {
884 warnStack = warnStack.prepend(warn);
885 return isCastable.visit(t, s);
886 } finally {
887 warnStack = warnStack.tail;
888 }
889 } else {
890 return isCastable.visit(t, s);
891 }
892 }
893 // where
894 private TypeRelation isCastable = new TypeRelation() {
896 public Boolean visitType(Type t, Type s) {
897 if (s.tag == ERROR)
898 return true;
900 switch (t.tag) {
901 case BYTE: case CHAR: case SHORT: case INT: case LONG: case FLOAT:
902 case DOUBLE:
903 return s.tag <= DOUBLE;
904 case BOOLEAN:
905 return s.tag == BOOLEAN;
906 case VOID:
907 return false;
908 case BOT:
909 return isSubtype(t, s);
910 default:
911 throw new AssertionError();
912 }
913 }
915 @Override
916 public Boolean visitWildcardType(WildcardType t, Type s) {
917 return isCastable(upperBound(t), s, warnStack.head);
918 }
920 @Override
921 public Boolean visitClassType(ClassType t, Type s) {
922 if (s.tag == ERROR || s.tag == BOT)
923 return true;
925 if (s.tag == TYPEVAR) {
926 if (isCastable(s.getUpperBound(), t, Warner.noWarnings)) {
927 warnStack.head.warnUnchecked();
928 return true;
929 } else {
930 return false;
931 }
932 }
934 if (t.isCompound()) {
935 if (!visit(supertype(t), s))
936 return false;
937 for (Type intf : interfaces(t)) {
938 if (!visit(intf, s))
939 return false;
940 }
941 return true;
942 }
944 if (s.isCompound()) {
945 // call recursively to reuse the above code
946 return visitClassType((ClassType)s, t);
947 }
949 if (s.tag == CLASS || s.tag == ARRAY) {
950 boolean upcast;
951 if ((upcast = isSubtype(erasure(t), erasure(s)))
952 || isSubtype(erasure(s), erasure(t))) {
953 if (!upcast && s.tag == ARRAY) {
954 if (!isReifiable(s))
955 warnStack.head.warnUnchecked();
956 return true;
957 } else if (s.isRaw()) {
958 return true;
959 } else if (t.isRaw()) {
960 if (!isUnbounded(s))
961 warnStack.head.warnUnchecked();
962 return true;
963 }
964 // Assume |a| <: |b|
965 final Type a = upcast ? t : s;
966 final Type b = upcast ? s : t;
967 final boolean HIGH = true;
968 final boolean LOW = false;
969 final boolean DONT_REWRITE_TYPEVARS = false;
970 Type aHigh = rewriteQuantifiers(a, HIGH, DONT_REWRITE_TYPEVARS);
971 Type aLow = rewriteQuantifiers(a, LOW, DONT_REWRITE_TYPEVARS);
972 Type bHigh = rewriteQuantifiers(b, HIGH, DONT_REWRITE_TYPEVARS);
973 Type bLow = rewriteQuantifiers(b, LOW, DONT_REWRITE_TYPEVARS);
974 Type lowSub = asSub(bLow, aLow.tsym);
975 Type highSub = (lowSub == null) ? null : asSub(bHigh, aHigh.tsym);
976 if (highSub == null) {
977 final boolean REWRITE_TYPEVARS = true;
978 aHigh = rewriteQuantifiers(a, HIGH, REWRITE_TYPEVARS);
979 aLow = rewriteQuantifiers(a, LOW, REWRITE_TYPEVARS);
980 bHigh = rewriteQuantifiers(b, HIGH, REWRITE_TYPEVARS);
981 bLow = rewriteQuantifiers(b, LOW, REWRITE_TYPEVARS);
982 lowSub = asSub(bLow, aLow.tsym);
983 highSub = (lowSub == null) ? null : asSub(bHigh, aHigh.tsym);
984 }
985 if (highSub != null) {
986 assert a.tsym == highSub.tsym && a.tsym == lowSub.tsym
987 : a.tsym + " != " + highSub.tsym + " != " + lowSub.tsym;
988 if (!disjointTypes(aHigh.getTypeArguments(), highSub.getTypeArguments())
989 && !disjointTypes(aHigh.getTypeArguments(), lowSub.getTypeArguments())
990 && !disjointTypes(aLow.getTypeArguments(), highSub.getTypeArguments())
991 && !disjointTypes(aLow.getTypeArguments(), lowSub.getTypeArguments())) {
992 if (upcast ? giveWarning(a, highSub) || giveWarning(a, lowSub)
993 : giveWarning(highSub, a) || giveWarning(lowSub, a))
994 warnStack.head.warnUnchecked();
995 return true;
996 }
997 }
998 if (isReifiable(s))
999 return isSubtypeUnchecked(a, b);
1000 else
1001 return isSubtypeUnchecked(a, b, warnStack.head);
1002 }
1004 // Sidecast
1005 if (s.tag == CLASS) {
1006 if ((s.tsym.flags() & INTERFACE) != 0) {
1007 return ((t.tsym.flags() & FINAL) == 0)
1008 ? sideCast(t, s, warnStack.head)
1009 : sideCastFinal(t, s, warnStack.head);
1010 } else if ((t.tsym.flags() & INTERFACE) != 0) {
1011 return ((s.tsym.flags() & FINAL) == 0)
1012 ? sideCast(t, s, warnStack.head)
1013 : sideCastFinal(t, s, warnStack.head);
1014 } else {
1015 // unrelated class types
1016 return false;
1017 }
1018 }
1019 }
1020 return false;
1021 }
1023 @Override
1024 public Boolean visitArrayType(ArrayType t, Type s) {
1025 switch (s.tag) {
1026 case ERROR:
1027 case BOT:
1028 return true;
1029 case TYPEVAR:
1030 if (isCastable(s, t, Warner.noWarnings)) {
1031 warnStack.head.warnUnchecked();
1032 return true;
1033 } else {
1034 return false;
1035 }
1036 case CLASS:
1037 return isSubtype(t, s);
1038 case ARRAY:
1039 if (elemtype(t).tag <= lastBaseTag) {
1040 return elemtype(t).tag == elemtype(s).tag;
1041 } else {
1042 return visit(elemtype(t), elemtype(s));
1043 }
1044 default:
1045 return false;
1046 }
1047 }
1049 @Override
1050 public Boolean visitTypeVar(TypeVar t, Type s) {
1051 switch (s.tag) {
1052 case ERROR:
1053 case BOT:
1054 return true;
1055 case TYPEVAR:
1056 if (isSubtype(t, s)) {
1057 return true;
1058 } else if (isCastable(t.bound, s, Warner.noWarnings)) {
1059 warnStack.head.warnUnchecked();
1060 return true;
1061 } else {
1062 return false;
1063 }
1064 default:
1065 return isCastable(t.bound, s, warnStack.head);
1066 }
1067 }
1069 @Override
1070 public Boolean visitErrorType(ErrorType t, Type s) {
1071 return true;
1072 }
1073 };
1074 // </editor-fold>
1076 // <editor-fold defaultstate="collapsed" desc="disjointTypes">
1077 public boolean disjointTypes(List<Type> ts, List<Type> ss) {
1078 while (ts.tail != null && ss.tail != null) {
1079 if (disjointType(ts.head, ss.head)) return true;
1080 ts = ts.tail;
1081 ss = ss.tail;
1082 }
1083 return false;
1084 }
1086 /**
1087 * Two types or wildcards are considered disjoint if it can be
1088 * proven that no type can be contained in both. It is
1089 * conservative in that it is allowed to say that two types are
1090 * not disjoint, even though they actually are.
1091 *
1092 * The type C<X> is castable to C<Y> exactly if X and Y are not
1093 * disjoint.
1094 */
1095 public boolean disjointType(Type t, Type s) {
1096 return disjointType.visit(t, s);
1097 }
1098 // where
1099 private TypeRelation disjointType = new TypeRelation() {
1101 private Set<TypePair> cache = new HashSet<TypePair>();
1103 public Boolean visitType(Type t, Type s) {
1104 if (s.tag == WILDCARD)
1105 return visit(s, t);
1106 else
1107 return notSoftSubtypeRecursive(t, s) || notSoftSubtypeRecursive(s, t);
1108 }
1110 private boolean isCastableRecursive(Type t, Type s) {
1111 TypePair pair = new TypePair(t, s);
1112 if (cache.add(pair)) {
1113 try {
1114 return Types.this.isCastable(t, s);
1115 } finally {
1116 cache.remove(pair);
1117 }
1118 } else {
1119 return true;
1120 }
1121 }
1123 private boolean notSoftSubtypeRecursive(Type t, Type s) {
1124 TypePair pair = new TypePair(t, s);
1125 if (cache.add(pair)) {
1126 try {
1127 return Types.this.notSoftSubtype(t, s);
1128 } finally {
1129 cache.remove(pair);
1130 }
1131 } else {
1132 return false;
1133 }
1134 }
1136 @Override
1137 public Boolean visitWildcardType(WildcardType t, Type s) {
1138 if (t.isUnbound())
1139 return false;
1141 if (s.tag != WILDCARD) {
1142 if (t.isExtendsBound())
1143 return notSoftSubtypeRecursive(s, t.type);
1144 else // isSuperBound()
1145 return notSoftSubtypeRecursive(t.type, s);
1146 }
1148 if (s.isUnbound())
1149 return false;
1151 if (t.isExtendsBound()) {
1152 if (s.isExtendsBound())
1153 return !isCastableRecursive(t.type, upperBound(s));
1154 else if (s.isSuperBound())
1155 return notSoftSubtypeRecursive(lowerBound(s), t.type);
1156 } else if (t.isSuperBound()) {
1157 if (s.isExtendsBound())
1158 return notSoftSubtypeRecursive(t.type, upperBound(s));
1159 }
1160 return false;
1161 }
1162 };
1163 // </editor-fold>
1165 // <editor-fold defaultstate="collapsed" desc="lowerBoundArgtypes">
1166 /**
1167 * Returns the lower bounds of the formals of a method.
1168 */
1169 public List<Type> lowerBoundArgtypes(Type t) {
1170 return map(t.getParameterTypes(), lowerBoundMapping);
1171 }
1172 private final Mapping lowerBoundMapping = new Mapping("lowerBound") {
1173 public Type apply(Type t) {
1174 return lowerBound(t);
1175 }
1176 };
1177 // </editor-fold>
1179 // <editor-fold defaultstate="collapsed" desc="notSoftSubtype">
1180 /**
1181 * This relation answers the question: is impossible that
1182 * something of type `t' can be a subtype of `s'? This is
1183 * different from the question "is `t' not a subtype of `s'?"
1184 * when type variables are involved: Integer is not a subtype of T
1185 * where <T extends Number> but it is not true that Integer cannot
1186 * possibly be a subtype of T.
1187 */
1188 public boolean notSoftSubtype(Type t, Type s) {
1189 if (t == s) return false;
1190 if (t.tag == TYPEVAR) {
1191 TypeVar tv = (TypeVar) t;
1192 if (s.tag == TYPEVAR)
1193 s = s.getUpperBound();
1194 return !isCastable(tv.bound,
1195 s,
1196 Warner.noWarnings);
1197 }
1198 if (s.tag != WILDCARD)
1199 s = upperBound(s);
1200 if (s.tag == TYPEVAR)
1201 s = s.getUpperBound();
1202 return !isSubtype(t, s);
1203 }
1204 // </editor-fold>
1206 // <editor-fold defaultstate="collapsed" desc="isReifiable">
1207 public boolean isReifiable(Type t) {
1208 return isReifiable.visit(t);
1209 }
1210 // where
1211 private UnaryVisitor<Boolean> isReifiable = new UnaryVisitor<Boolean>() {
1213 public Boolean visitType(Type t, Void ignored) {
1214 return true;
1215 }
1217 @Override
1218 public Boolean visitClassType(ClassType t, Void ignored) {
1219 if (!t.isParameterized())
1220 return true;
1222 for (Type param : t.allparams()) {
1223 if (!param.isUnbound())
1224 return false;
1225 }
1226 return true;
1227 }
1229 @Override
1230 public Boolean visitArrayType(ArrayType t, Void ignored) {
1231 return visit(t.elemtype);
1232 }
1234 @Override
1235 public Boolean visitTypeVar(TypeVar t, Void ignored) {
1236 return false;
1237 }
1238 };
1239 // </editor-fold>
1241 // <editor-fold defaultstate="collapsed" desc="Array Utils">
1242 public boolean isArray(Type t) {
1243 while (t.tag == WILDCARD)
1244 t = upperBound(t);
1245 return t.tag == ARRAY;
1246 }
1248 /**
1249 * The element type of an array.
1250 */
1251 public Type elemtype(Type t) {
1252 switch (t.tag) {
1253 case WILDCARD:
1254 return elemtype(upperBound(t));
1255 case ARRAY:
1256 return ((ArrayType)t).elemtype;
1257 case FORALL:
1258 return elemtype(((ForAll)t).qtype);
1259 case ERROR:
1260 return t;
1261 default:
1262 return null;
1263 }
1264 }
1266 /**
1267 * Mapping to take element type of an arraytype
1268 */
1269 private Mapping elemTypeFun = new Mapping ("elemTypeFun") {
1270 public Type apply(Type t) { return elemtype(t); }
1271 };
1273 /**
1274 * The number of dimensions of an array type.
1275 */
1276 public int dimensions(Type t) {
1277 int result = 0;
1278 while (t.tag == ARRAY) {
1279 result++;
1280 t = elemtype(t);
1281 }
1282 return result;
1283 }
1284 // </editor-fold>
1286 // <editor-fold defaultstate="collapsed" desc="asSuper">
1287 /**
1288 * Return the (most specific) base type of t that starts with the
1289 * given symbol. If none exists, return null.
1290 *
1291 * @param t a type
1292 * @param sym a symbol
1293 */
1294 public Type asSuper(Type t, Symbol sym) {
1295 return asSuper.visit(t, sym);
1296 }
1297 // where
1298 private SimpleVisitor<Type,Symbol> asSuper = new SimpleVisitor<Type,Symbol>() {
1300 public Type visitType(Type t, Symbol sym) {
1301 return null;
1302 }
1304 @Override
1305 public Type visitClassType(ClassType t, Symbol sym) {
1306 if (t.tsym == sym)
1307 return t;
1309 Type st = supertype(t);
1310 if (st.tag == CLASS || st.tag == TYPEVAR || st.tag == ERROR) {
1311 Type x = asSuper(st, sym);
1312 if (x != null)
1313 return x;
1314 }
1315 if ((sym.flags() & INTERFACE) != 0) {
1316 for (List<Type> l = interfaces(t); l.nonEmpty(); l = l.tail) {
1317 Type x = asSuper(l.head, sym);
1318 if (x != null)
1319 return x;
1320 }
1321 }
1322 return null;
1323 }
1325 @Override
1326 public Type visitArrayType(ArrayType t, Symbol sym) {
1327 return isSubtype(t, sym.type) ? sym.type : null;
1328 }
1330 @Override
1331 public Type visitTypeVar(TypeVar t, Symbol sym) {
1332 if (t.tsym == sym)
1333 return t;
1334 else
1335 return asSuper(t.bound, sym);
1336 }
1338 @Override
1339 public Type visitErrorType(ErrorType t, Symbol sym) {
1340 return t;
1341 }
1342 };
1344 /**
1345 * Return the base type of t or any of its outer types that starts
1346 * with the given symbol. If none exists, return null.
1347 *
1348 * @param t a type
1349 * @param sym a symbol
1350 */
1351 public Type asOuterSuper(Type t, Symbol sym) {
1352 switch (t.tag) {
1353 case CLASS:
1354 do {
1355 Type s = asSuper(t, sym);
1356 if (s != null) return s;
1357 t = t.getEnclosingType();
1358 } while (t.tag == CLASS);
1359 return null;
1360 case ARRAY:
1361 return isSubtype(t, sym.type) ? sym.type : null;
1362 case TYPEVAR:
1363 return asSuper(t, sym);
1364 case ERROR:
1365 return t;
1366 default:
1367 return null;
1368 }
1369 }
1371 /**
1372 * Return the base type of t or any of its enclosing types that
1373 * starts with the given symbol. If none exists, return null.
1374 *
1375 * @param t a type
1376 * @param sym a symbol
1377 */
1378 public Type asEnclosingSuper(Type t, Symbol sym) {
1379 switch (t.tag) {
1380 case CLASS:
1381 do {
1382 Type s = asSuper(t, sym);
1383 if (s != null) return s;
1384 Type outer = t.getEnclosingType();
1385 t = (outer.tag == CLASS) ? outer :
1386 (t.tsym.owner.enclClass() != null) ? t.tsym.owner.enclClass().type :
1387 Type.noType;
1388 } while (t.tag == CLASS);
1389 return null;
1390 case ARRAY:
1391 return isSubtype(t, sym.type) ? sym.type : null;
1392 case TYPEVAR:
1393 return asSuper(t, sym);
1394 case ERROR:
1395 return t;
1396 default:
1397 return null;
1398 }
1399 }
1400 // </editor-fold>
1402 // <editor-fold defaultstate="collapsed" desc="memberType">
1403 /**
1404 * The type of given symbol, seen as a member of t.
1405 *
1406 * @param t a type
1407 * @param sym a symbol
1408 */
1409 public Type memberType(Type t, Symbol sym) {
1410 return (sym.flags() & STATIC) != 0
1411 ? sym.type
1412 : memberType.visit(t, sym);
1413 }
1414 // where
1415 private SimpleVisitor<Type,Symbol> memberType = new SimpleVisitor<Type,Symbol>() {
1417 public Type visitType(Type t, Symbol sym) {
1418 return sym.type;
1419 }
1421 @Override
1422 public Type visitWildcardType(WildcardType t, Symbol sym) {
1423 return memberType(upperBound(t), sym);
1424 }
1426 @Override
1427 public Type visitClassType(ClassType t, Symbol sym) {
1428 Symbol owner = sym.owner;
1429 long flags = sym.flags();
1430 if (((flags & STATIC) == 0) && owner.type.isParameterized()) {
1431 Type base = asOuterSuper(t, owner);
1432 if (base != null) {
1433 List<Type> ownerParams = owner.type.allparams();
1434 List<Type> baseParams = base.allparams();
1435 if (ownerParams.nonEmpty()) {
1436 if (baseParams.isEmpty()) {
1437 // then base is a raw type
1438 return erasure(sym.type);
1439 } else {
1440 return subst(sym.type, ownerParams, baseParams);
1441 }
1442 }
1443 }
1444 }
1445 return sym.type;
1446 }
1448 @Override
1449 public Type visitTypeVar(TypeVar t, Symbol sym) {
1450 return memberType(t.bound, sym);
1451 }
1453 @Override
1454 public Type visitErrorType(ErrorType t, Symbol sym) {
1455 return t;
1456 }
1457 };
1458 // </editor-fold>
1460 // <editor-fold defaultstate="collapsed" desc="isAssignable">
1461 public boolean isAssignable(Type t, Type s) {
1462 return isAssignable(t, s, Warner.noWarnings);
1463 }
1465 /**
1466 * Is t assignable to s?<br>
1467 * Equivalent to subtype except for constant values and raw
1468 * types.<br>
1469 * (not defined for Method and ForAll types)
1470 */
1471 public boolean isAssignable(Type t, Type s, Warner warn) {
1472 if (t.tag == ERROR)
1473 return true;
1474 if (t.tag <= INT && t.constValue() != null) {
1475 int value = ((Number)t.constValue()).intValue();
1476 switch (s.tag) {
1477 case BYTE:
1478 if (Byte.MIN_VALUE <= value && value <= Byte.MAX_VALUE)
1479 return true;
1480 break;
1481 case CHAR:
1482 if (Character.MIN_VALUE <= value && value <= Character.MAX_VALUE)
1483 return true;
1484 break;
1485 case SHORT:
1486 if (Short.MIN_VALUE <= value && value <= Short.MAX_VALUE)
1487 return true;
1488 break;
1489 case INT:
1490 return true;
1491 case CLASS:
1492 switch (unboxedType(s).tag) {
1493 case BYTE:
1494 case CHAR:
1495 case SHORT:
1496 return isAssignable(t, unboxedType(s), warn);
1497 }
1498 break;
1499 }
1500 }
1501 return isConvertible(t, s, warn);
1502 }
1503 // </editor-fold>
1505 // <editor-fold defaultstate="collapsed" desc="erasure">
1506 /**
1507 * The erasure of t {@code |t|} -- the type that results when all
1508 * type parameters in t are deleted.
1509 */
1510 public Type erasure(Type t) {
1511 return erasure(t, false);
1512 }
1513 //where
1514 private Type erasure(Type t, boolean recurse) {
1515 if (t.tag <= lastBaseTag)
1516 return t; /* fast special case */
1517 else
1518 return erasure.visit(t, recurse);
1519 }
1520 // where
1521 private SimpleVisitor<Type, Boolean> erasure = new SimpleVisitor<Type, Boolean>() {
1522 public Type visitType(Type t, Boolean recurse) {
1523 if (t.tag <= lastBaseTag)
1524 return t; /*fast special case*/
1525 else
1526 return t.map(recurse ? erasureRecFun : erasureFun);
1527 }
1529 @Override
1530 public Type visitWildcardType(WildcardType t, Boolean recurse) {
1531 return erasure(upperBound(t), recurse);
1532 }
1534 @Override
1535 public Type visitClassType(ClassType t, Boolean recurse) {
1536 Type erased = t.tsym.erasure(Types.this);
1537 if (recurse) {
1538 erased = new ErasedClassType(erased.getEnclosingType(),erased.tsym);
1539 }
1540 return erased;
1541 }
1543 @Override
1544 public Type visitTypeVar(TypeVar t, Boolean recurse) {
1545 return erasure(t.bound, recurse);
1546 }
1548 @Override
1549 public Type visitErrorType(ErrorType t, Boolean recurse) {
1550 return t;
1551 }
1552 };
1554 private Mapping erasureFun = new Mapping ("erasure") {
1555 public Type apply(Type t) { return erasure(t); }
1556 };
1558 private Mapping erasureRecFun = new Mapping ("erasureRecursive") {
1559 public Type apply(Type t) { return erasureRecursive(t); }
1560 };
1562 public List<Type> erasure(List<Type> ts) {
1563 return Type.map(ts, erasureFun);
1564 }
1566 public Type erasureRecursive(Type t) {
1567 return erasure(t, true);
1568 }
1570 public List<Type> erasureRecursive(List<Type> ts) {
1571 return Type.map(ts, erasureRecFun);
1572 }
1573 // </editor-fold>
1575 // <editor-fold defaultstate="collapsed" desc="makeCompoundType">
1576 /**
1577 * Make a compound type from non-empty list of types
1578 *
1579 * @param bounds the types from which the compound type is formed
1580 * @param supertype is objectType if all bounds are interfaces,
1581 * null otherwise.
1582 */
1583 public Type makeCompoundType(List<Type> bounds,
1584 Type supertype) {
1585 ClassSymbol bc =
1586 new ClassSymbol(ABSTRACT|PUBLIC|SYNTHETIC|COMPOUND|ACYCLIC,
1587 Type.moreInfo
1588 ? names.fromString(bounds.toString())
1589 : names.empty,
1590 syms.noSymbol);
1591 if (bounds.head.tag == TYPEVAR)
1592 // error condition, recover
1593 bc.erasure_field = syms.objectType;
1594 else
1595 bc.erasure_field = erasure(bounds.head);
1596 bc.members_field = new Scope(bc);
1597 ClassType bt = (ClassType)bc.type;
1598 bt.allparams_field = List.nil();
1599 if (supertype != null) {
1600 bt.supertype_field = supertype;
1601 bt.interfaces_field = bounds;
1602 } else {
1603 bt.supertype_field = bounds.head;
1604 bt.interfaces_field = bounds.tail;
1605 }
1606 assert bt.supertype_field.tsym.completer != null
1607 || !bt.supertype_field.isInterface()
1608 : bt.supertype_field;
1609 return bt;
1610 }
1612 /**
1613 * Same as {@link #makeCompoundType(List,Type)}, except that the
1614 * second parameter is computed directly. Note that this might
1615 * cause a symbol completion. Hence, this version of
1616 * makeCompoundType may not be called during a classfile read.
1617 */
1618 public Type makeCompoundType(List<Type> bounds) {
1619 Type supertype = (bounds.head.tsym.flags() & INTERFACE) != 0 ?
1620 supertype(bounds.head) : null;
1621 return makeCompoundType(bounds, supertype);
1622 }
1624 /**
1625 * A convenience wrapper for {@link #makeCompoundType(List)}; the
1626 * arguments are converted to a list and passed to the other
1627 * method. Note that this might cause a symbol completion.
1628 * Hence, this version of makeCompoundType may not be called
1629 * during a classfile read.
1630 */
1631 public Type makeCompoundType(Type bound1, Type bound2) {
1632 return makeCompoundType(List.of(bound1, bound2));
1633 }
1634 // </editor-fold>
1636 // <editor-fold defaultstate="collapsed" desc="supertype">
1637 public Type supertype(Type t) {
1638 return supertype.visit(t);
1639 }
1640 // where
1641 private UnaryVisitor<Type> supertype = new UnaryVisitor<Type>() {
1643 public Type visitType(Type t, Void ignored) {
1644 // A note on wildcards: there is no good way to
1645 // determine a supertype for a super bounded wildcard.
1646 return null;
1647 }
1649 @Override
1650 public Type visitClassType(ClassType t, Void ignored) {
1651 if (t.supertype_field == null) {
1652 Type supertype = ((ClassSymbol)t.tsym).getSuperclass();
1653 // An interface has no superclass; its supertype is Object.
1654 if (t.isInterface())
1655 supertype = ((ClassType)t.tsym.type).supertype_field;
1656 if (t.supertype_field == null) {
1657 List<Type> actuals = classBound(t).allparams();
1658 List<Type> formals = t.tsym.type.allparams();
1659 if (t.hasErasedSupertypes()) {
1660 t.supertype_field = erasureRecursive(supertype);
1661 } else if (formals.nonEmpty()) {
1662 t.supertype_field = subst(supertype, formals, actuals);
1663 }
1664 else {
1665 t.supertype_field = supertype;
1666 }
1667 }
1668 }
1669 return t.supertype_field;
1670 }
1672 /**
1673 * The supertype is always a class type. If the type
1674 * variable's bounds start with a class type, this is also
1675 * the supertype. Otherwise, the supertype is
1676 * java.lang.Object.
1677 */
1678 @Override
1679 public Type visitTypeVar(TypeVar t, Void ignored) {
1680 if (t.bound.tag == TYPEVAR ||
1681 (!t.bound.isCompound() && !t.bound.isInterface())) {
1682 return t.bound;
1683 } else {
1684 return supertype(t.bound);
1685 }
1686 }
1688 @Override
1689 public Type visitArrayType(ArrayType t, Void ignored) {
1690 if (t.elemtype.isPrimitive() || isSameType(t.elemtype, syms.objectType))
1691 return arraySuperType();
1692 else
1693 return new ArrayType(supertype(t.elemtype), t.tsym);
1694 }
1696 @Override
1697 public Type visitErrorType(ErrorType t, Void ignored) {
1698 return t;
1699 }
1700 };
1701 // </editor-fold>
1703 // <editor-fold defaultstate="collapsed" desc="interfaces">
1704 /**
1705 * Return the interfaces implemented by this class.
1706 */
1707 public List<Type> interfaces(Type t) {
1708 return interfaces.visit(t);
1709 }
1710 // where
1711 private UnaryVisitor<List<Type>> interfaces = new UnaryVisitor<List<Type>>() {
1713 public List<Type> visitType(Type t, Void ignored) {
1714 return List.nil();
1715 }
1717 @Override
1718 public List<Type> visitClassType(ClassType t, Void ignored) {
1719 if (t.interfaces_field == null) {
1720 List<Type> interfaces = ((ClassSymbol)t.tsym).getInterfaces();
1721 if (t.interfaces_field == null) {
1722 // If t.interfaces_field is null, then t must
1723 // be a parameterized type (not to be confused
1724 // with a generic type declaration).
1725 // Terminology:
1726 // Parameterized type: List<String>
1727 // Generic type declaration: class List<E> { ... }
1728 // So t corresponds to List<String> and
1729 // t.tsym.type corresponds to List<E>.
1730 // The reason t must be parameterized type is
1731 // that completion will happen as a side
1732 // effect of calling
1733 // ClassSymbol.getInterfaces. Since
1734 // t.interfaces_field is null after
1735 // completion, we can assume that t is not the
1736 // type of a class/interface declaration.
1737 assert t != t.tsym.type : t.toString();
1738 List<Type> actuals = t.allparams();
1739 List<Type> formals = t.tsym.type.allparams();
1740 if (t.hasErasedSupertypes()) {
1741 t.interfaces_field = erasureRecursive(interfaces);
1742 } else if (formals.nonEmpty()) {
1743 t.interfaces_field =
1744 upperBounds(subst(interfaces, formals, actuals));
1745 }
1746 else {
1747 t.interfaces_field = interfaces;
1748 }
1749 }
1750 }
1751 return t.interfaces_field;
1752 }
1754 @Override
1755 public List<Type> visitTypeVar(TypeVar t, Void ignored) {
1756 if (t.bound.isCompound())
1757 return interfaces(t.bound);
1759 if (t.bound.isInterface())
1760 return List.of(t.bound);
1762 return List.nil();
1763 }
1764 };
1765 // </editor-fold>
1767 // <editor-fold defaultstate="collapsed" desc="isDerivedRaw">
1768 Map<Type,Boolean> isDerivedRawCache = new HashMap<Type,Boolean>();
1770 public boolean isDerivedRaw(Type t) {
1771 Boolean result = isDerivedRawCache.get(t);
1772 if (result == null) {
1773 result = isDerivedRawInternal(t);
1774 isDerivedRawCache.put(t, result);
1775 }
1776 return result;
1777 }
1779 public boolean isDerivedRawInternal(Type t) {
1780 if (t.isErroneous())
1781 return false;
1782 return
1783 t.isRaw() ||
1784 supertype(t) != null && isDerivedRaw(supertype(t)) ||
1785 isDerivedRaw(interfaces(t));
1786 }
1788 public boolean isDerivedRaw(List<Type> ts) {
1789 List<Type> l = ts;
1790 while (l.nonEmpty() && !isDerivedRaw(l.head)) l = l.tail;
1791 return l.nonEmpty();
1792 }
1793 // </editor-fold>
1795 // <editor-fold defaultstate="collapsed" desc="setBounds">
1796 /**
1797 * Set the bounds field of the given type variable to reflect a
1798 * (possibly multiple) list of bounds.
1799 * @param t a type variable
1800 * @param bounds the bounds, must be nonempty
1801 * @param supertype is objectType if all bounds are interfaces,
1802 * null otherwise.
1803 */
1804 public void setBounds(TypeVar t, List<Type> bounds, Type supertype) {
1805 if (bounds.tail.isEmpty())
1806 t.bound = bounds.head;
1807 else
1808 t.bound = makeCompoundType(bounds, supertype);
1809 t.rank_field = -1;
1810 }
1812 /**
1813 * Same as {@link #setBounds(Type.TypeVar,List,Type)}, except that
1814 * third parameter is computed directly. Note that this test
1815 * might cause a symbol completion. Hence, this version of
1816 * setBounds may not be called during a classfile read.
1817 */
1818 public void setBounds(TypeVar t, List<Type> bounds) {
1819 Type supertype = (bounds.head.tsym.flags() & INTERFACE) != 0 ?
1820 supertype(bounds.head) : null;
1821 setBounds(t, bounds, supertype);
1822 t.rank_field = -1;
1823 }
1824 // </editor-fold>
1826 // <editor-fold defaultstate="collapsed" desc="getBounds">
1827 /**
1828 * Return list of bounds of the given type variable.
1829 */
1830 public List<Type> getBounds(TypeVar t) {
1831 if (t.bound.isErroneous() || !t.bound.isCompound())
1832 return List.of(t.bound);
1833 else if ((erasure(t).tsym.flags() & INTERFACE) == 0)
1834 return interfaces(t).prepend(supertype(t));
1835 else
1836 // No superclass was given in bounds.
1837 // In this case, supertype is Object, erasure is first interface.
1838 return interfaces(t);
1839 }
1840 // </editor-fold>
1842 // <editor-fold defaultstate="collapsed" desc="classBound">
1843 /**
1844 * If the given type is a (possibly selected) type variable,
1845 * return the bounding class of this type, otherwise return the
1846 * type itself.
1847 */
1848 public Type classBound(Type t) {
1849 return classBound.visit(t);
1850 }
1851 // where
1852 private UnaryVisitor<Type> classBound = new UnaryVisitor<Type>() {
1854 public Type visitType(Type t, Void ignored) {
1855 return t;
1856 }
1858 @Override
1859 public Type visitClassType(ClassType t, Void ignored) {
1860 Type outer1 = classBound(t.getEnclosingType());
1861 if (outer1 != t.getEnclosingType())
1862 return new ClassType(outer1, t.getTypeArguments(), t.tsym);
1863 else
1864 return t;
1865 }
1867 @Override
1868 public Type visitTypeVar(TypeVar t, Void ignored) {
1869 return classBound(supertype(t));
1870 }
1872 @Override
1873 public Type visitErrorType(ErrorType t, Void ignored) {
1874 return t;
1875 }
1876 };
1877 // </editor-fold>
1879 // <editor-fold defaultstate="collapsed" desc="sub signature / override equivalence">
1880 /**
1881 * Returns true iff the first signature is a <em>sub
1882 * signature</em> of the other. This is <b>not</b> an equivalence
1883 * relation.
1884 *
1885 * @see "The Java Language Specification, Third Ed. (8.4.2)."
1886 * @see #overrideEquivalent(Type t, Type s)
1887 * @param t first signature (possibly raw).
1888 * @param s second signature (could be subjected to erasure).
1889 * @return true if t is a sub signature of s.
1890 */
1891 public boolean isSubSignature(Type t, Type s) {
1892 return hasSameArgs(t, s) || hasSameArgs(t, erasure(s));
1893 }
1895 /**
1896 * Returns true iff these signatures are related by <em>override
1897 * equivalence</em>. This is the natural extension of
1898 * isSubSignature to an equivalence relation.
1899 *
1900 * @see "The Java Language Specification, Third Ed. (8.4.2)."
1901 * @see #isSubSignature(Type t, Type s)
1902 * @param t a signature (possible raw, could be subjected to
1903 * erasure).
1904 * @param s a signature (possible raw, could be subjected to
1905 * erasure).
1906 * @return true if either argument is a sub signature of the other.
1907 */
1908 public boolean overrideEquivalent(Type t, Type s) {
1909 return hasSameArgs(t, s) ||
1910 hasSameArgs(t, erasure(s)) || hasSameArgs(erasure(t), s);
1911 }
1913 /**
1914 * Does t have the same arguments as s? It is assumed that both
1915 * types are (possibly polymorphic) method types. Monomorphic
1916 * method types "have the same arguments", if their argument lists
1917 * are equal. Polymorphic method types "have the same arguments",
1918 * if they have the same arguments after renaming all type
1919 * variables of one to corresponding type variables in the other,
1920 * where correspondence is by position in the type parameter list.
1921 */
1922 public boolean hasSameArgs(Type t, Type s) {
1923 return hasSameArgs.visit(t, s);
1924 }
1925 // where
1926 private TypeRelation hasSameArgs = new TypeRelation() {
1928 public Boolean visitType(Type t, Type s) {
1929 throw new AssertionError();
1930 }
1932 @Override
1933 public Boolean visitMethodType(MethodType t, Type s) {
1934 return s.tag == METHOD
1935 && containsTypeEquivalent(t.argtypes, s.getParameterTypes());
1936 }
1938 @Override
1939 public Boolean visitForAll(ForAll t, Type s) {
1940 if (s.tag != FORALL)
1941 return false;
1943 ForAll forAll = (ForAll)s;
1944 return hasSameBounds(t, forAll)
1945 && visit(t.qtype, subst(forAll.qtype, forAll.tvars, t.tvars));
1946 }
1948 @Override
1949 public Boolean visitErrorType(ErrorType t, Type s) {
1950 return false;
1951 }
1952 };
1953 // </editor-fold>
1955 // <editor-fold defaultstate="collapsed" desc="subst">
1956 public List<Type> subst(List<Type> ts,
1957 List<Type> from,
1958 List<Type> to) {
1959 return new Subst(from, to).subst(ts);
1960 }
1962 /**
1963 * Substitute all occurrences of a type in `from' with the
1964 * corresponding type in `to' in 't'. Match lists `from' and `to'
1965 * from the right: If lists have different length, discard leading
1966 * elements of the longer list.
1967 */
1968 public Type subst(Type t, List<Type> from, List<Type> to) {
1969 return new Subst(from, to).subst(t);
1970 }
1972 private class Subst extends UnaryVisitor<Type> {
1973 List<Type> from;
1974 List<Type> to;
1976 public Subst(List<Type> from, List<Type> to) {
1977 int fromLength = from.length();
1978 int toLength = to.length();
1979 while (fromLength > toLength) {
1980 fromLength--;
1981 from = from.tail;
1982 }
1983 while (fromLength < toLength) {
1984 toLength--;
1985 to = to.tail;
1986 }
1987 this.from = from;
1988 this.to = to;
1989 }
1991 Type subst(Type t) {
1992 if (from.tail == null)
1993 return t;
1994 else
1995 return visit(t);
1996 }
1998 List<Type> subst(List<Type> ts) {
1999 if (from.tail == null)
2000 return ts;
2001 boolean wild = false;
2002 if (ts.nonEmpty() && from.nonEmpty()) {
2003 Type head1 = subst(ts.head);
2004 List<Type> tail1 = subst(ts.tail);
2005 if (head1 != ts.head || tail1 != ts.tail)
2006 return tail1.prepend(head1);
2007 }
2008 return ts;
2009 }
2011 public Type visitType(Type t, Void ignored) {
2012 return t;
2013 }
2015 @Override
2016 public Type visitMethodType(MethodType t, Void ignored) {
2017 List<Type> argtypes = subst(t.argtypes);
2018 Type restype = subst(t.restype);
2019 List<Type> thrown = subst(t.thrown);
2020 if (argtypes == t.argtypes &&
2021 restype == t.restype &&
2022 thrown == t.thrown)
2023 return t;
2024 else
2025 return new MethodType(argtypes, restype, thrown, t.tsym);
2026 }
2028 @Override
2029 public Type visitTypeVar(TypeVar t, Void ignored) {
2030 for (List<Type> from = this.from, to = this.to;
2031 from.nonEmpty();
2032 from = from.tail, to = to.tail) {
2033 if (t == from.head) {
2034 return to.head.withTypeVar(t);
2035 }
2036 }
2037 return t;
2038 }
2040 @Override
2041 public Type visitClassType(ClassType t, Void ignored) {
2042 if (!t.isCompound()) {
2043 List<Type> typarams = t.getTypeArguments();
2044 List<Type> typarams1 = subst(typarams);
2045 Type outer = t.getEnclosingType();
2046 Type outer1 = subst(outer);
2047 if (typarams1 == typarams && outer1 == outer)
2048 return t;
2049 else
2050 return new ClassType(outer1, typarams1, t.tsym);
2051 } else {
2052 Type st = subst(supertype(t));
2053 List<Type> is = upperBounds(subst(interfaces(t)));
2054 if (st == supertype(t) && is == interfaces(t))
2055 return t;
2056 else
2057 return makeCompoundType(is.prepend(st));
2058 }
2059 }
2061 @Override
2062 public Type visitWildcardType(WildcardType t, Void ignored) {
2063 Type bound = t.type;
2064 if (t.kind != BoundKind.UNBOUND)
2065 bound = subst(bound);
2066 if (bound == t.type) {
2067 return t;
2068 } else {
2069 if (t.isExtendsBound() && bound.isExtendsBound())
2070 bound = upperBound(bound);
2071 return new WildcardType(bound, t.kind, syms.boundClass, t.bound);
2072 }
2073 }
2075 @Override
2076 public Type visitArrayType(ArrayType t, Void ignored) {
2077 Type elemtype = subst(t.elemtype);
2078 if (elemtype == t.elemtype)
2079 return t;
2080 else
2081 return new ArrayType(upperBound(elemtype), t.tsym);
2082 }
2084 @Override
2085 public Type visitForAll(ForAll t, Void ignored) {
2086 List<Type> tvars1 = substBounds(t.tvars, from, to);
2087 Type qtype1 = subst(t.qtype);
2088 if (tvars1 == t.tvars && qtype1 == t.qtype) {
2089 return t;
2090 } else if (tvars1 == t.tvars) {
2091 return new ForAll(tvars1, qtype1);
2092 } else {
2093 return new ForAll(tvars1, Types.this.subst(qtype1, t.tvars, tvars1));
2094 }
2095 }
2097 @Override
2098 public Type visitErrorType(ErrorType t, Void ignored) {
2099 return t;
2100 }
2101 }
2103 public List<Type> substBounds(List<Type> tvars,
2104 List<Type> from,
2105 List<Type> to) {
2106 if (tvars.isEmpty())
2107 return tvars;
2108 if (tvars.tail.isEmpty())
2109 // fast common case
2110 return List.<Type>of(substBound((TypeVar)tvars.head, from, to));
2111 ListBuffer<Type> newBoundsBuf = lb();
2112 boolean changed = false;
2113 // calculate new bounds
2114 for (Type t : tvars) {
2115 TypeVar tv = (TypeVar) t;
2116 Type bound = subst(tv.bound, from, to);
2117 if (bound != tv.bound)
2118 changed = true;
2119 newBoundsBuf.append(bound);
2120 }
2121 if (!changed)
2122 return tvars;
2123 ListBuffer<Type> newTvars = lb();
2124 // create new type variables without bounds
2125 for (Type t : tvars) {
2126 newTvars.append(new TypeVar(t.tsym, null, syms.botType));
2127 }
2128 // the new bounds should use the new type variables in place
2129 // of the old
2130 List<Type> newBounds = newBoundsBuf.toList();
2131 from = tvars;
2132 to = newTvars.toList();
2133 for (; !newBounds.isEmpty(); newBounds = newBounds.tail) {
2134 newBounds.head = subst(newBounds.head, from, to);
2135 }
2136 newBounds = newBoundsBuf.toList();
2137 // set the bounds of new type variables to the new bounds
2138 for (Type t : newTvars.toList()) {
2139 TypeVar tv = (TypeVar) t;
2140 tv.bound = newBounds.head;
2141 newBounds = newBounds.tail;
2142 }
2143 return newTvars.toList();
2144 }
2146 public TypeVar substBound(TypeVar t, List<Type> from, List<Type> to) {
2147 Type bound1 = subst(t.bound, from, to);
2148 if (bound1 == t.bound)
2149 return t;
2150 else
2151 return new TypeVar(t.tsym, bound1, syms.botType);
2152 }
2153 // </editor-fold>
2155 // <editor-fold defaultstate="collapsed" desc="hasSameBounds">
2156 /**
2157 * Does t have the same bounds for quantified variables as s?
2158 */
2159 boolean hasSameBounds(ForAll t, ForAll s) {
2160 List<Type> l1 = t.tvars;
2161 List<Type> l2 = s.tvars;
2162 while (l1.nonEmpty() && l2.nonEmpty() &&
2163 isSameType(l1.head.getUpperBound(),
2164 subst(l2.head.getUpperBound(),
2165 s.tvars,
2166 t.tvars))) {
2167 l1 = l1.tail;
2168 l2 = l2.tail;
2169 }
2170 return l1.isEmpty() && l2.isEmpty();
2171 }
2172 // </editor-fold>
2174 // <editor-fold defaultstate="collapsed" desc="newInstances">
2175 /** Create new vector of type variables from list of variables
2176 * changing all recursive bounds from old to new list.
2177 */
2178 public List<Type> newInstances(List<Type> tvars) {
2179 List<Type> tvars1 = Type.map(tvars, newInstanceFun);
2180 for (List<Type> l = tvars1; l.nonEmpty(); l = l.tail) {
2181 TypeVar tv = (TypeVar) l.head;
2182 tv.bound = subst(tv.bound, tvars, tvars1);
2183 }
2184 return tvars1;
2185 }
2186 static private Mapping newInstanceFun = new Mapping("newInstanceFun") {
2187 public Type apply(Type t) { return new TypeVar(t.tsym, t.getUpperBound(), t.getLowerBound()); }
2188 };
2189 // </editor-fold>
2191 // <editor-fold defaultstate="collapsed" desc="rank">
2192 /**
2193 * The rank of a class is the length of the longest path between
2194 * the class and java.lang.Object in the class inheritance
2195 * graph. Undefined for all but reference types.
2196 */
2197 public int rank(Type t) {
2198 switch(t.tag) {
2199 case CLASS: {
2200 ClassType cls = (ClassType)t;
2201 if (cls.rank_field < 0) {
2202 Name fullname = cls.tsym.getQualifiedName();
2203 if (fullname == fullname.table.java_lang_Object)
2204 cls.rank_field = 0;
2205 else {
2206 int r = rank(supertype(cls));
2207 for (List<Type> l = interfaces(cls);
2208 l.nonEmpty();
2209 l = l.tail) {
2210 if (rank(l.head) > r)
2211 r = rank(l.head);
2212 }
2213 cls.rank_field = r + 1;
2214 }
2215 }
2216 return cls.rank_field;
2217 }
2218 case TYPEVAR: {
2219 TypeVar tvar = (TypeVar)t;
2220 if (tvar.rank_field < 0) {
2221 int r = rank(supertype(tvar));
2222 for (List<Type> l = interfaces(tvar);
2223 l.nonEmpty();
2224 l = l.tail) {
2225 if (rank(l.head) > r) r = rank(l.head);
2226 }
2227 tvar.rank_field = r + 1;
2228 }
2229 return tvar.rank_field;
2230 }
2231 case ERROR:
2232 return 0;
2233 default:
2234 throw new AssertionError();
2235 }
2236 }
2237 // </editor-fold>
2239 // <editor-fold defaultstate="collapsed" desc="toString">
2240 /**
2241 * This toString is slightly more descriptive than the one on Type.
2242 */
2243 public String toString(Type t) {
2244 if (t.tag == FORALL) {
2245 ForAll forAll = (ForAll)t;
2246 return typaramsString(forAll.tvars) + forAll.qtype;
2247 }
2248 return "" + t;
2249 }
2250 // where
2251 private String typaramsString(List<Type> tvars) {
2252 StringBuffer s = new StringBuffer();
2253 s.append('<');
2254 boolean first = true;
2255 for (Type t : tvars) {
2256 if (!first) s.append(", ");
2257 first = false;
2258 appendTyparamString(((TypeVar)t), s);
2259 }
2260 s.append('>');
2261 return s.toString();
2262 }
2263 private void appendTyparamString(TypeVar t, StringBuffer buf) {
2264 buf.append(t);
2265 if (t.bound == null ||
2266 t.bound.tsym.getQualifiedName() == names.java_lang_Object)
2267 return;
2268 buf.append(" extends "); // Java syntax; no need for i18n
2269 Type bound = t.bound;
2270 if (!bound.isCompound()) {
2271 buf.append(bound);
2272 } else if ((erasure(t).tsym.flags() & INTERFACE) == 0) {
2273 buf.append(supertype(t));
2274 for (Type intf : interfaces(t)) {
2275 buf.append('&');
2276 buf.append(intf);
2277 }
2278 } else {
2279 // No superclass was given in bounds.
2280 // In this case, supertype is Object, erasure is first interface.
2281 boolean first = true;
2282 for (Type intf : interfaces(t)) {
2283 if (!first) buf.append('&');
2284 first = false;
2285 buf.append(intf);
2286 }
2287 }
2288 }
2289 // </editor-fold>
2291 // <editor-fold defaultstate="collapsed" desc="Determining least upper bounds of types">
2292 /**
2293 * A cache for closures.
2294 *
2295 * <p>A closure is a list of all the supertypes and interfaces of
2296 * a class or interface type, ordered by ClassSymbol.precedes
2297 * (that is, subclasses come first, arbitrary but fixed
2298 * otherwise).
2299 */
2300 private Map<Type,List<Type>> closureCache = new HashMap<Type,List<Type>>();
2302 /**
2303 * Returns the closure of a class or interface type.
2304 */
2305 public List<Type> closure(Type t) {
2306 List<Type> cl = closureCache.get(t);
2307 if (cl == null) {
2308 Type st = supertype(t);
2309 if (!t.isCompound()) {
2310 if (st.tag == CLASS) {
2311 cl = insert(closure(st), t);
2312 } else if (st.tag == TYPEVAR) {
2313 cl = closure(st).prepend(t);
2314 } else {
2315 cl = List.of(t);
2316 }
2317 } else {
2318 cl = closure(supertype(t));
2319 }
2320 for (List<Type> l = interfaces(t); l.nonEmpty(); l = l.tail)
2321 cl = union(cl, closure(l.head));
2322 closureCache.put(t, cl);
2323 }
2324 return cl;
2325 }
2327 /**
2328 * Insert a type in a closure
2329 */
2330 public List<Type> insert(List<Type> cl, Type t) {
2331 if (cl.isEmpty() || t.tsym.precedes(cl.head.tsym, this)) {
2332 return cl.prepend(t);
2333 } else if (cl.head.tsym.precedes(t.tsym, this)) {
2334 return insert(cl.tail, t).prepend(cl.head);
2335 } else {
2336 return cl;
2337 }
2338 }
2340 /**
2341 * Form the union of two closures
2342 */
2343 public List<Type> union(List<Type> cl1, List<Type> cl2) {
2344 if (cl1.isEmpty()) {
2345 return cl2;
2346 } else if (cl2.isEmpty()) {
2347 return cl1;
2348 } else if (cl1.head.tsym.precedes(cl2.head.tsym, this)) {
2349 return union(cl1.tail, cl2).prepend(cl1.head);
2350 } else if (cl2.head.tsym.precedes(cl1.head.tsym, this)) {
2351 return union(cl1, cl2.tail).prepend(cl2.head);
2352 } else {
2353 return union(cl1.tail, cl2.tail).prepend(cl1.head);
2354 }
2355 }
2357 /**
2358 * Intersect two closures
2359 */
2360 public List<Type> intersect(List<Type> cl1, List<Type> cl2) {
2361 if (cl1 == cl2)
2362 return cl1;
2363 if (cl1.isEmpty() || cl2.isEmpty())
2364 return List.nil();
2365 if (cl1.head.tsym.precedes(cl2.head.tsym, this))
2366 return intersect(cl1.tail, cl2);
2367 if (cl2.head.tsym.precedes(cl1.head.tsym, this))
2368 return intersect(cl1, cl2.tail);
2369 if (isSameType(cl1.head, cl2.head))
2370 return intersect(cl1.tail, cl2.tail).prepend(cl1.head);
2371 if (cl1.head.tsym == cl2.head.tsym &&
2372 cl1.head.tag == CLASS && cl2.head.tag == CLASS) {
2373 if (cl1.head.isParameterized() && cl2.head.isParameterized()) {
2374 Type merge = merge(cl1.head,cl2.head);
2375 return intersect(cl1.tail, cl2.tail).prepend(merge);
2376 }
2377 if (cl1.head.isRaw() || cl2.head.isRaw())
2378 return intersect(cl1.tail, cl2.tail).prepend(erasure(cl1.head));
2379 }
2380 return intersect(cl1.tail, cl2.tail);
2381 }
2382 // where
2383 class TypePair {
2384 final Type t1;
2385 final Type t2;
2386 TypePair(Type t1, Type t2) {
2387 this.t1 = t1;
2388 this.t2 = t2;
2389 }
2390 @Override
2391 public int hashCode() {
2392 return 127 * Types.this.hashCode(t1) + Types.this.hashCode(t2);
2393 }
2394 @Override
2395 public boolean equals(Object obj) {
2396 if (!(obj instanceof TypePair))
2397 return false;
2398 TypePair typePair = (TypePair)obj;
2399 return isSameType(t1, typePair.t1)
2400 && isSameType(t2, typePair.t2);
2401 }
2402 }
2403 Set<TypePair> mergeCache = new HashSet<TypePair>();
2404 private Type merge(Type c1, Type c2) {
2405 ClassType class1 = (ClassType) c1;
2406 List<Type> act1 = class1.getTypeArguments();
2407 ClassType class2 = (ClassType) c2;
2408 List<Type> act2 = class2.getTypeArguments();
2409 ListBuffer<Type> merged = new ListBuffer<Type>();
2410 List<Type> typarams = class1.tsym.type.getTypeArguments();
2412 while (act1.nonEmpty() && act2.nonEmpty() && typarams.nonEmpty()) {
2413 if (containsType(act1.head, act2.head)) {
2414 merged.append(act1.head);
2415 } else if (containsType(act2.head, act1.head)) {
2416 merged.append(act2.head);
2417 } else {
2418 TypePair pair = new TypePair(c1, c2);
2419 Type m;
2420 if (mergeCache.add(pair)) {
2421 m = new WildcardType(lub(upperBound(act1.head),
2422 upperBound(act2.head)),
2423 BoundKind.EXTENDS,
2424 syms.boundClass);
2425 mergeCache.remove(pair);
2426 } else {
2427 m = new WildcardType(syms.objectType,
2428 BoundKind.UNBOUND,
2429 syms.boundClass);
2430 }
2431 merged.append(m.withTypeVar(typarams.head));
2432 }
2433 act1 = act1.tail;
2434 act2 = act2.tail;
2435 typarams = typarams.tail;
2436 }
2437 assert(act1.isEmpty() && act2.isEmpty() && typarams.isEmpty());
2438 return new ClassType(class1.getEnclosingType(), merged.toList(), class1.tsym);
2439 }
2441 /**
2442 * Return the minimum type of a closure, a compound type if no
2443 * unique minimum exists.
2444 */
2445 private Type compoundMin(List<Type> cl) {
2446 if (cl.isEmpty()) return syms.objectType;
2447 List<Type> compound = closureMin(cl);
2448 if (compound.isEmpty())
2449 return null;
2450 else if (compound.tail.isEmpty())
2451 return compound.head;
2452 else
2453 return makeCompoundType(compound);
2454 }
2456 /**
2457 * Return the minimum types of a closure, suitable for computing
2458 * compoundMin or glb.
2459 */
2460 private List<Type> closureMin(List<Type> cl) {
2461 ListBuffer<Type> classes = lb();
2462 ListBuffer<Type> interfaces = lb();
2463 while (!cl.isEmpty()) {
2464 Type current = cl.head;
2465 if (current.isInterface())
2466 interfaces.append(current);
2467 else
2468 classes.append(current);
2469 ListBuffer<Type> candidates = lb();
2470 for (Type t : cl.tail) {
2471 if (!isSubtypeNoCapture(current, t))
2472 candidates.append(t);
2473 }
2474 cl = candidates.toList();
2475 }
2476 return classes.appendList(interfaces).toList();
2477 }
2479 /**
2480 * Return the least upper bound of pair of types. if the lub does
2481 * not exist return null.
2482 */
2483 public Type lub(Type t1, Type t2) {
2484 return lub(List.of(t1, t2));
2485 }
2487 /**
2488 * Return the least upper bound (lub) of set of types. If the lub
2489 * does not exist return the type of null (bottom).
2490 */
2491 public Type lub(List<Type> ts) {
2492 final int ARRAY_BOUND = 1;
2493 final int CLASS_BOUND = 2;
2494 int boundkind = 0;
2495 for (Type t : ts) {
2496 switch (t.tag) {
2497 case CLASS:
2498 boundkind |= CLASS_BOUND;
2499 break;
2500 case ARRAY:
2501 boundkind |= ARRAY_BOUND;
2502 break;
2503 case TYPEVAR:
2504 do {
2505 t = t.getUpperBound();
2506 } while (t.tag == TYPEVAR);
2507 if (t.tag == ARRAY) {
2508 boundkind |= ARRAY_BOUND;
2509 } else {
2510 boundkind |= CLASS_BOUND;
2511 }
2512 break;
2513 default:
2514 if (t.isPrimitive())
2515 return syms.errType;
2516 }
2517 }
2518 switch (boundkind) {
2519 case 0:
2520 return syms.botType;
2522 case ARRAY_BOUND:
2523 // calculate lub(A[], B[])
2524 List<Type> elements = Type.map(ts, elemTypeFun);
2525 for (Type t : elements) {
2526 if (t.isPrimitive()) {
2527 // if a primitive type is found, then return
2528 // arraySuperType unless all the types are the
2529 // same
2530 Type first = ts.head;
2531 for (Type s : ts.tail) {
2532 if (!isSameType(first, s)) {
2533 // lub(int[], B[]) is Cloneable & Serializable
2534 return arraySuperType();
2535 }
2536 }
2537 // all the array types are the same, return one
2538 // lub(int[], int[]) is int[]
2539 return first;
2540 }
2541 }
2542 // lub(A[], B[]) is lub(A, B)[]
2543 return new ArrayType(lub(elements), syms.arrayClass);
2545 case CLASS_BOUND:
2546 // calculate lub(A, B)
2547 while (ts.head.tag != CLASS && ts.head.tag != TYPEVAR)
2548 ts = ts.tail;
2549 assert !ts.isEmpty();
2550 List<Type> cl = closure(ts.head);
2551 for (Type t : ts.tail) {
2552 if (t.tag == CLASS || t.tag == TYPEVAR)
2553 cl = intersect(cl, closure(t));
2554 }
2555 return compoundMin(cl);
2557 default:
2558 // calculate lub(A, B[])
2559 List<Type> classes = List.of(arraySuperType());
2560 for (Type t : ts) {
2561 if (t.tag != ARRAY) // Filter out any arrays
2562 classes = classes.prepend(t);
2563 }
2564 // lub(A, B[]) is lub(A, arraySuperType)
2565 return lub(classes);
2566 }
2567 }
2568 // where
2569 private Type arraySuperType = null;
2570 private Type arraySuperType() {
2571 // initialized lazily to avoid problems during compiler startup
2572 if (arraySuperType == null) {
2573 synchronized (this) {
2574 if (arraySuperType == null) {
2575 // JLS 10.8: all arrays implement Cloneable and Serializable.
2576 arraySuperType = makeCompoundType(List.of(syms.serializableType,
2577 syms.cloneableType),
2578 syms.objectType);
2579 }
2580 }
2581 }
2582 return arraySuperType;
2583 }
2584 // </editor-fold>
2586 // <editor-fold defaultstate="collapsed" desc="Greatest lower bound">
2587 public Type glb(Type t, Type s) {
2588 if (s == null)
2589 return t;
2590 else if (isSubtypeNoCapture(t, s))
2591 return t;
2592 else if (isSubtypeNoCapture(s, t))
2593 return s;
2595 List<Type> closure = union(closure(t), closure(s));
2596 List<Type> bounds = closureMin(closure);
2598 if (bounds.isEmpty()) { // length == 0
2599 return syms.objectType;
2600 } else if (bounds.tail.isEmpty()) { // length == 1
2601 return bounds.head;
2602 } else { // length > 1
2603 int classCount = 0;
2604 for (Type bound : bounds)
2605 if (!bound.isInterface())
2606 classCount++;
2607 if (classCount > 1)
2608 return syms.errType;
2609 }
2610 return makeCompoundType(bounds);
2611 }
2612 // </editor-fold>
2614 // <editor-fold defaultstate="collapsed" desc="hashCode">
2615 /**
2616 * Compute a hash code on a type.
2617 */
2618 public static int hashCode(Type t) {
2619 return hashCode.visit(t);
2620 }
2621 // where
2622 private static final UnaryVisitor<Integer> hashCode = new UnaryVisitor<Integer>() {
2624 public Integer visitType(Type t, Void ignored) {
2625 return t.tag;
2626 }
2628 @Override
2629 public Integer visitClassType(ClassType t, Void ignored) {
2630 int result = visit(t.getEnclosingType());
2631 result *= 127;
2632 result += t.tsym.flatName().hashCode();
2633 for (Type s : t.getTypeArguments()) {
2634 result *= 127;
2635 result += visit(s);
2636 }
2637 return result;
2638 }
2640 @Override
2641 public Integer visitWildcardType(WildcardType t, Void ignored) {
2642 int result = t.kind.hashCode();
2643 if (t.type != null) {
2644 result *= 127;
2645 result += visit(t.type);
2646 }
2647 return result;
2648 }
2650 @Override
2651 public Integer visitArrayType(ArrayType t, Void ignored) {
2652 return visit(t.elemtype) + 12;
2653 }
2655 @Override
2656 public Integer visitTypeVar(TypeVar t, Void ignored) {
2657 return System.identityHashCode(t.tsym);
2658 }
2660 @Override
2661 public Integer visitUndetVar(UndetVar t, Void ignored) {
2662 return System.identityHashCode(t);
2663 }
2665 @Override
2666 public Integer visitErrorType(ErrorType t, Void ignored) {
2667 return 0;
2668 }
2669 };
2670 // </editor-fold>
2672 // <editor-fold defaultstate="collapsed" desc="Return-Type-Substitutable">
2673 /**
2674 * Does t have a result that is a subtype of the result type of s,
2675 * suitable for covariant returns? It is assumed that both types
2676 * are (possibly polymorphic) method types. Monomorphic method
2677 * types are handled in the obvious way. Polymorphic method types
2678 * require renaming all type variables of one to corresponding
2679 * type variables in the other, where correspondence is by
2680 * position in the type parameter list. */
2681 public boolean resultSubtype(Type t, Type s, Warner warner) {
2682 List<Type> tvars = t.getTypeArguments();
2683 List<Type> svars = s.getTypeArguments();
2684 Type tres = t.getReturnType();
2685 Type sres = subst(s.getReturnType(), svars, tvars);
2686 return covariantReturnType(tres, sres, warner);
2687 }
2689 /**
2690 * Return-Type-Substitutable.
2691 * @see <a href="http://java.sun.com/docs/books/jls/">The Java
2692 * Language Specification, Third Ed. (8.4.5)</a>
2693 */
2694 public boolean returnTypeSubstitutable(Type r1, Type r2) {
2695 if (hasSameArgs(r1, r2))
2696 return resultSubtype(r1, r2, Warner.noWarnings);
2697 else
2698 return covariantReturnType(r1.getReturnType(),
2699 erasure(r2.getReturnType()),
2700 Warner.noWarnings);
2701 }
2703 public boolean returnTypeSubstitutable(Type r1,
2704 Type r2, Type r2res,
2705 Warner warner) {
2706 if (isSameType(r1.getReturnType(), r2res))
2707 return true;
2708 if (r1.getReturnType().isPrimitive() || r2res.isPrimitive())
2709 return false;
2711 if (hasSameArgs(r1, r2))
2712 return covariantReturnType(r1.getReturnType(), r2res, warner);
2713 if (!source.allowCovariantReturns())
2714 return false;
2715 if (isSubtypeUnchecked(r1.getReturnType(), r2res, warner))
2716 return true;
2717 if (!isSubtype(r1.getReturnType(), erasure(r2res)))
2718 return false;
2719 warner.warnUnchecked();
2720 return true;
2721 }
2723 /**
2724 * Is t an appropriate return type in an overrider for a
2725 * method that returns s?
2726 */
2727 public boolean covariantReturnType(Type t, Type s, Warner warner) {
2728 return
2729 isSameType(t, s) ||
2730 source.allowCovariantReturns() &&
2731 !t.isPrimitive() &&
2732 !s.isPrimitive() &&
2733 isAssignable(t, s, warner);
2734 }
2735 // </editor-fold>
2737 // <editor-fold defaultstate="collapsed" desc="Box/unbox support">
2738 /**
2739 * Return the class that boxes the given primitive.
2740 */
2741 public ClassSymbol boxedClass(Type t) {
2742 return reader.enterClass(syms.boxedName[t.tag]);
2743 }
2745 /**
2746 * Return the primitive type corresponding to a boxed type.
2747 */
2748 public Type unboxedType(Type t) {
2749 if (allowBoxing) {
2750 for (int i=0; i<syms.boxedName.length; i++) {
2751 Name box = syms.boxedName[i];
2752 if (box != null &&
2753 asSuper(t, reader.enterClass(box)) != null)
2754 return syms.typeOfTag[i];
2755 }
2756 }
2757 return Type.noType;
2758 }
2759 // </editor-fold>
2761 // <editor-fold defaultstate="collapsed" desc="Capture conversion">
2762 /*
2763 * JLS 3rd Ed. 5.1.10 Capture Conversion:
2764 *
2765 * Let G name a generic type declaration with n formal type
2766 * parameters A1 ... An with corresponding bounds U1 ... Un. There
2767 * exists a capture conversion from G<T1 ... Tn> to G<S1 ... Sn>,
2768 * where, for 1 <= i <= n:
2769 *
2770 * + If Ti is a wildcard type argument (4.5.1) of the form ? then
2771 * Si is a fresh type variable whose upper bound is
2772 * Ui[A1 := S1, ..., An := Sn] and whose lower bound is the null
2773 * type.
2774 *
2775 * + If Ti is a wildcard type argument of the form ? extends Bi,
2776 * then Si is a fresh type variable whose upper bound is
2777 * glb(Bi, Ui[A1 := S1, ..., An := Sn]) and whose lower bound is
2778 * the null type, where glb(V1,... ,Vm) is V1 & ... & Vm. It is
2779 * a compile-time error if for any two classes (not interfaces)
2780 * Vi and Vj,Vi is not a subclass of Vj or vice versa.
2781 *
2782 * + If Ti is a wildcard type argument of the form ? super Bi,
2783 * then Si is a fresh type variable whose upper bound is
2784 * Ui[A1 := S1, ..., An := Sn] and whose lower bound is Bi.
2785 *
2786 * + Otherwise, Si = Ti.
2787 *
2788 * Capture conversion on any type other than a parameterized type
2789 * (4.5) acts as an identity conversion (5.1.1). Capture
2790 * conversions never require a special action at run time and
2791 * therefore never throw an exception at run time.
2792 *
2793 * Capture conversion is not applied recursively.
2794 */
2795 /**
2796 * Capture conversion as specified by JLS 3rd Ed.
2797 */
2798 public Type capture(Type t) {
2799 if (t.tag != CLASS)
2800 return t;
2801 ClassType cls = (ClassType)t;
2802 if (cls.isRaw() || !cls.isParameterized())
2803 return cls;
2805 ClassType G = (ClassType)cls.asElement().asType();
2806 List<Type> A = G.getTypeArguments();
2807 List<Type> T = cls.getTypeArguments();
2808 List<Type> S = freshTypeVariables(T);
2810 List<Type> currentA = A;
2811 List<Type> currentT = T;
2812 List<Type> currentS = S;
2813 boolean captured = false;
2814 while (!currentA.isEmpty() &&
2815 !currentT.isEmpty() &&
2816 !currentS.isEmpty()) {
2817 if (currentS.head != currentT.head) {
2818 captured = true;
2819 WildcardType Ti = (WildcardType)currentT.head;
2820 Type Ui = currentA.head.getUpperBound();
2821 CapturedType Si = (CapturedType)currentS.head;
2822 if (Ui == null)
2823 Ui = syms.objectType;
2824 switch (Ti.kind) {
2825 case UNBOUND:
2826 Si.bound = subst(Ui, A, S);
2827 Si.lower = syms.botType;
2828 break;
2829 case EXTENDS:
2830 Si.bound = glb(Ti.getExtendsBound(), subst(Ui, A, S));
2831 Si.lower = syms.botType;
2832 break;
2833 case SUPER:
2834 Si.bound = subst(Ui, A, S);
2835 Si.lower = Ti.getSuperBound();
2836 break;
2837 }
2838 if (Si.bound == Si.lower)
2839 currentS.head = Si.bound;
2840 }
2841 currentA = currentA.tail;
2842 currentT = currentT.tail;
2843 currentS = currentS.tail;
2844 }
2845 if (!currentA.isEmpty() || !currentT.isEmpty() || !currentS.isEmpty())
2846 return erasure(t); // some "rare" type involved
2848 if (captured)
2849 return new ClassType(cls.getEnclosingType(), S, cls.tsym);
2850 else
2851 return t;
2852 }
2853 // where
2854 private List<Type> freshTypeVariables(List<Type> types) {
2855 ListBuffer<Type> result = lb();
2856 for (Type t : types) {
2857 if (t.tag == WILDCARD) {
2858 Type bound = ((WildcardType)t).getExtendsBound();
2859 if (bound == null)
2860 bound = syms.objectType;
2861 result.append(new CapturedType(capturedName,
2862 syms.noSymbol,
2863 bound,
2864 syms.botType,
2865 (WildcardType)t));
2866 } else {
2867 result.append(t);
2868 }
2869 }
2870 return result.toList();
2871 }
2872 // </editor-fold>
2874 // <editor-fold defaultstate="collapsed" desc="Internal utility methods">
2875 private List<Type> upperBounds(List<Type> ss) {
2876 if (ss.isEmpty()) return ss;
2877 Type head = upperBound(ss.head);
2878 List<Type> tail = upperBounds(ss.tail);
2879 if (head != ss.head || tail != ss.tail)
2880 return tail.prepend(head);
2881 else
2882 return ss;
2883 }
2885 private boolean sideCast(Type from, Type to, Warner warn) {
2886 // We are casting from type $from$ to type $to$, which are
2887 // non-final unrelated types. This method
2888 // tries to reject a cast by transferring type parameters
2889 // from $to$ to $from$ by common superinterfaces.
2890 boolean reverse = false;
2891 Type target = to;
2892 if ((to.tsym.flags() & INTERFACE) == 0) {
2893 assert (from.tsym.flags() & INTERFACE) != 0;
2894 reverse = true;
2895 to = from;
2896 from = target;
2897 }
2898 List<Type> commonSupers = superClosure(to, erasure(from));
2899 boolean giveWarning = commonSupers.isEmpty();
2900 // The arguments to the supers could be unified here to
2901 // get a more accurate analysis
2902 while (commonSupers.nonEmpty()) {
2903 Type t1 = asSuper(from, commonSupers.head.tsym);
2904 Type t2 = commonSupers.head; // same as asSuper(to, commonSupers.head.tsym);
2905 if (disjointTypes(t1.getTypeArguments(), t2.getTypeArguments()))
2906 return false;
2907 giveWarning = giveWarning || (reverse ? giveWarning(t2, t1) : giveWarning(t1, t2));
2908 commonSupers = commonSupers.tail;
2909 }
2910 if (giveWarning && !isReifiable(to))
2911 warn.warnUnchecked();
2912 if (!source.allowCovariantReturns())
2913 // reject if there is a common method signature with
2914 // incompatible return types.
2915 chk.checkCompatibleAbstracts(warn.pos(), from, to);
2916 return true;
2917 }
2919 private boolean sideCastFinal(Type from, Type to, Warner warn) {
2920 // We are casting from type $from$ to type $to$, which are
2921 // unrelated types one of which is final and the other of
2922 // which is an interface. This method
2923 // tries to reject a cast by transferring type parameters
2924 // from the final class to the interface.
2925 boolean reverse = false;
2926 Type target = to;
2927 if ((to.tsym.flags() & INTERFACE) == 0) {
2928 assert (from.tsym.flags() & INTERFACE) != 0;
2929 reverse = true;
2930 to = from;
2931 from = target;
2932 }
2933 assert (from.tsym.flags() & FINAL) != 0;
2934 Type t1 = asSuper(from, to.tsym);
2935 if (t1 == null) return false;
2936 Type t2 = to;
2937 if (disjointTypes(t1.getTypeArguments(), t2.getTypeArguments()))
2938 return false;
2939 if (!source.allowCovariantReturns())
2940 // reject if there is a common method signature with
2941 // incompatible return types.
2942 chk.checkCompatibleAbstracts(warn.pos(), from, to);
2943 if (!isReifiable(target) &&
2944 (reverse ? giveWarning(t2, t1) : giveWarning(t1, t2)))
2945 warn.warnUnchecked();
2946 return true;
2947 }
2949 private boolean giveWarning(Type from, Type to) {
2950 // To and from are (possibly different) parameterizations
2951 // of the same class or interface
2952 return to.isParameterized() && !containsType(to.getTypeArguments(), from.getTypeArguments());
2953 }
2955 private List<Type> superClosure(Type t, Type s) {
2956 List<Type> cl = List.nil();
2957 for (List<Type> l = interfaces(t); l.nonEmpty(); l = l.tail) {
2958 if (isSubtype(s, erasure(l.head))) {
2959 cl = insert(cl, l.head);
2960 } else {
2961 cl = union(cl, superClosure(l.head, s));
2962 }
2963 }
2964 return cl;
2965 }
2967 private boolean containsTypeEquivalent(Type t, Type s) {
2968 return
2969 isSameType(t, s) || // shortcut
2970 containsType(t, s) && containsType(s, t);
2971 }
2973 /**
2974 * Adapt a type by computing a substitution which maps a source
2975 * type to a target type.
2976 *
2977 * @param source the source type
2978 * @param target the target type
2979 * @param from the type variables of the computed substitution
2980 * @param to the types of the computed substitution.
2981 */
2982 public void adapt(Type source,
2983 Type target,
2984 ListBuffer<Type> from,
2985 ListBuffer<Type> to) throws AdaptFailure {
2986 Map<Symbol,Type> mapping = new HashMap<Symbol,Type>();
2987 adaptRecursive(source, target, from, to, mapping);
2988 List<Type> fromList = from.toList();
2989 List<Type> toList = to.toList();
2990 while (!fromList.isEmpty()) {
2991 Type val = mapping.get(fromList.head.tsym);
2992 if (toList.head != val)
2993 toList.head = val;
2994 fromList = fromList.tail;
2995 toList = toList.tail;
2996 }
2997 }
2998 // where
2999 private void adaptRecursive(Type source,
3000 Type target,
3001 ListBuffer<Type> from,
3002 ListBuffer<Type> to,
3003 Map<Symbol,Type> mapping) throws AdaptFailure {
3004 if (source.tag == TYPEVAR) {
3005 // Check to see if there is
3006 // already a mapping for $source$, in which case
3007 // the old mapping will be merged with the new
3008 Type val = mapping.get(source.tsym);
3009 if (val != null) {
3010 if (val.isSuperBound() && target.isSuperBound()) {
3011 val = isSubtype(lowerBound(val), lowerBound(target))
3012 ? target : val;
3013 } else if (val.isExtendsBound() && target.isExtendsBound()) {
3014 val = isSubtype(upperBound(val), upperBound(target))
3015 ? val : target;
3016 } else if (!isSameType(val, target)) {
3017 throw new AdaptFailure();
3018 }
3019 } else {
3020 val = target;
3021 from.append(source);
3022 to.append(target);
3023 }
3024 mapping.put(source.tsym, val);
3025 } else if (source.tag == target.tag) {
3026 switch (source.tag) {
3027 case CLASS:
3028 adapt(source.allparams(), target.allparams(),
3029 from, to, mapping);
3030 break;
3031 case ARRAY:
3032 adaptRecursive(elemtype(source), elemtype(target),
3033 from, to, mapping);
3034 break;
3035 case WILDCARD:
3036 if (source.isExtendsBound()) {
3037 adaptRecursive(upperBound(source), upperBound(target),
3038 from, to, mapping);
3039 } else if (source.isSuperBound()) {
3040 adaptRecursive(lowerBound(source), lowerBound(target),
3041 from, to, mapping);
3042 }
3043 break;
3044 }
3045 }
3046 }
3047 public static class AdaptFailure extends Exception {
3048 static final long serialVersionUID = -7490231548272701566L;
3049 }
3051 /**
3052 * Adapt a type by computing a substitution which maps a list of
3053 * source types to a list of target types.
3054 *
3055 * @param source the source type
3056 * @param target the target type
3057 * @param from the type variables of the computed substitution
3058 * @param to the types of the computed substitution.
3059 */
3060 private void adapt(List<Type> source,
3061 List<Type> target,
3062 ListBuffer<Type> from,
3063 ListBuffer<Type> to,
3064 Map<Symbol,Type> mapping) throws AdaptFailure {
3065 if (source.length() == target.length()) {
3066 while (source.nonEmpty()) {
3067 adaptRecursive(source.head, target.head, from, to, mapping);
3068 source = source.tail;
3069 target = target.tail;
3070 }
3071 }
3072 }
3074 private void adaptSelf(Type t,
3075 ListBuffer<Type> from,
3076 ListBuffer<Type> to) {
3077 try {
3078 //if (t.tsym.type != t)
3079 adapt(t.tsym.type, t, from, to);
3080 } catch (AdaptFailure ex) {
3081 // Adapt should never fail calculating a mapping from
3082 // t.tsym.type to t as there can be no merge problem.
3083 throw new AssertionError(ex);
3084 }
3085 }
3087 /**
3088 * Rewrite all type variables (universal quantifiers) in the given
3089 * type to wildcards (existential quantifiers). This is used to
3090 * determine if a cast is allowed. For example, if high is true
3091 * and {@code T <: Number}, then {@code List<T>} is rewritten to
3092 * {@code List<? extends Number>}. Since {@code List<Integer> <:
3093 * List<? extends Number>} a {@code List<T>} can be cast to {@code
3094 * List<Integer>} with a warning.
3095 * @param t a type
3096 * @param high if true return an upper bound; otherwise a lower
3097 * bound
3098 * @param rewriteTypeVars only rewrite captured wildcards if false;
3099 * otherwise rewrite all type variables
3100 * @return the type rewritten with wildcards (existential
3101 * quantifiers) only
3102 */
3103 private Type rewriteQuantifiers(Type t, boolean high, boolean rewriteTypeVars) {
3104 ListBuffer<Type> from = new ListBuffer<Type>();
3105 ListBuffer<Type> to = new ListBuffer<Type>();
3106 adaptSelf(t, from, to);
3107 ListBuffer<Type> rewritten = new ListBuffer<Type>();
3108 List<Type> formals = from.toList();
3109 boolean changed = false;
3110 for (Type arg : to.toList()) {
3111 Type bound;
3112 if (rewriteTypeVars && arg.tag == TYPEVAR) {
3113 TypeVar tv = (TypeVar)arg;
3114 bound = high ? tv.bound : syms.botType;
3115 } else {
3116 bound = high ? upperBound(arg) : lowerBound(arg);
3117 }
3118 Type newarg = bound;
3119 if (arg != bound) {
3120 changed = true;
3121 newarg = high ? makeExtendsWildcard(bound, (TypeVar)formals.head)
3122 : makeSuperWildcard(bound, (TypeVar)formals.head);
3123 }
3124 rewritten.append(newarg);
3125 formals = formals.tail;
3126 }
3127 if (changed)
3128 return subst(t.tsym.type, from.toList(), rewritten.toList());
3129 else
3130 return t;
3131 }
3133 /**
3134 * Create a wildcard with the given upper (extends) bound; create
3135 * an unbounded wildcard if bound is Object.
3136 *
3137 * @param bound the upper bound
3138 * @param formal the formal type parameter that will be
3139 * substituted by the wildcard
3140 */
3141 private WildcardType makeExtendsWildcard(Type bound, TypeVar formal) {
3142 if (bound == syms.objectType) {
3143 return new WildcardType(syms.objectType,
3144 BoundKind.UNBOUND,
3145 syms.boundClass,
3146 formal);
3147 } else {
3148 return new WildcardType(bound,
3149 BoundKind.EXTENDS,
3150 syms.boundClass,
3151 formal);
3152 }
3153 }
3155 /**
3156 * Create a wildcard with the given lower (super) bound; create an
3157 * unbounded wildcard if bound is bottom (type of {@code null}).
3158 *
3159 * @param bound the lower bound
3160 * @param formal the formal type parameter that will be
3161 * substituted by the wildcard
3162 */
3163 private WildcardType makeSuperWildcard(Type bound, TypeVar formal) {
3164 if (bound.tag == BOT) {
3165 return new WildcardType(syms.objectType,
3166 BoundKind.UNBOUND,
3167 syms.boundClass,
3168 formal);
3169 } else {
3170 return new WildcardType(bound,
3171 BoundKind.SUPER,
3172 syms.boundClass,
3173 formal);
3174 }
3175 }
3177 /**
3178 * A wrapper for a type that allows use in sets.
3179 */
3180 class SingletonType {
3181 final Type t;
3182 SingletonType(Type t) {
3183 this.t = t;
3184 }
3185 public int hashCode() {
3186 return Types.this.hashCode(t);
3187 }
3188 public boolean equals(Object obj) {
3189 return (obj instanceof SingletonType) &&
3190 isSameType(t, ((SingletonType)obj).t);
3191 }
3192 public String toString() {
3193 return t.toString();
3194 }
3195 }
3196 // </editor-fold>
3198 // <editor-fold defaultstate="collapsed" desc="Visitors">
3199 /**
3200 * A default visitor for types. All visitor methods except
3201 * visitType are implemented by delegating to visitType. Concrete
3202 * subclasses must provide an implementation of visitType and can
3203 * override other methods as needed.
3204 *
3205 * @param <R> the return type of the operation implemented by this
3206 * visitor; use Void if no return type is needed.
3207 * @param <S> the type of the second argument (the first being the
3208 * type itself) of the operation implemented by this visitor; use
3209 * Void if a second argument is not needed.
3210 */
3211 public static abstract class DefaultTypeVisitor<R,S> implements Type.Visitor<R,S> {
3212 final public R visit(Type t, S s) { return t.accept(this, s); }
3213 public R visitClassType(ClassType t, S s) { return visitType(t, s); }
3214 public R visitWildcardType(WildcardType t, S s) { return visitType(t, s); }
3215 public R visitArrayType(ArrayType t, S s) { return visitType(t, s); }
3216 public R visitMethodType(MethodType t, S s) { return visitType(t, s); }
3217 public R visitPackageType(PackageType t, S s) { return visitType(t, s); }
3218 public R visitTypeVar(TypeVar t, S s) { return visitType(t, s); }
3219 public R visitCapturedType(CapturedType t, S s) { return visitType(t, s); }
3220 public R visitForAll(ForAll t, S s) { return visitType(t, s); }
3221 public R visitUndetVar(UndetVar t, S s) { return visitType(t, s); }
3222 public R visitErrorType(ErrorType t, S s) { return visitType(t, s); }
3223 }
3225 /**
3226 * A <em>simple</em> visitor for types. This visitor is simple as
3227 * captured wildcards, for-all types (generic methods), and
3228 * undetermined type variables (part of inference) are hidden.
3229 * Captured wildcards are hidden by treating them as type
3230 * variables and the rest are hidden by visiting their qtypes.
3231 *
3232 * @param <R> the return type of the operation implemented by this
3233 * visitor; use Void if no return type is needed.
3234 * @param <S> the type of the second argument (the first being the
3235 * type itself) of the operation implemented by this visitor; use
3236 * Void if a second argument is not needed.
3237 */
3238 public static abstract class SimpleVisitor<R,S> extends DefaultTypeVisitor<R,S> {
3239 @Override
3240 public R visitCapturedType(CapturedType t, S s) {
3241 return visitTypeVar(t, s);
3242 }
3243 @Override
3244 public R visitForAll(ForAll t, S s) {
3245 return visit(t.qtype, s);
3246 }
3247 @Override
3248 public R visitUndetVar(UndetVar t, S s) {
3249 return visit(t.qtype, s);
3250 }
3251 }
3253 /**
3254 * A plain relation on types. That is a 2-ary function on the
3255 * form Type × Type → Boolean.
3256 * <!-- In plain text: Type x Type -> Boolean -->
3257 */
3258 public static abstract class TypeRelation extends SimpleVisitor<Boolean,Type> {}
3260 /**
3261 * A convenience visitor for implementing operations that only
3262 * require one argument (the type itself), that is, unary
3263 * operations.
3264 *
3265 * @param <R> the return type of the operation implemented by this
3266 * visitor; use Void if no return type is needed.
3267 */
3268 public static abstract class UnaryVisitor<R> extends SimpleVisitor<R,Void> {
3269 final public R visit(Type t) { return t.accept(this, null); }
3270 }
3272 /**
3273 * A visitor for implementing a mapping from types to types. The
3274 * default behavior of this class is to implement the identity
3275 * mapping (mapping a type to itself). This can be overridden in
3276 * subclasses.
3277 *
3278 * @param <S> the type of the second argument (the first being the
3279 * type itself) of this mapping; use Void if a second argument is
3280 * not needed.
3281 */
3282 public static class MapVisitor<S> extends DefaultTypeVisitor<Type,S> {
3283 final public Type visit(Type t) { return t.accept(this, null); }
3284 public Type visitType(Type t, S s) { return t; }
3285 }
3286 // </editor-fold>
3287 }